TooltipView.js 28.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/

S
sushuang 已提交
20
import * as echarts from '../../echarts';
S
sushuang 已提交
21 22
import * as zrUtil from 'zrender/src/core/util';
import env from 'zrender/src/core/env';
S
sushuang 已提交
23
import TooltipContent from './TooltipContent';
24
import TooltipRichContent from './TooltipRichContent';
S
sushuang 已提交
25 26 27 28 29 30 31 32 33
import * as formatUtil from '../../util/format';
import * as numberUtil from '../../util/number';
import * as graphic from '../../util/graphic';
import findPointFromSeries from '../axisPointer/findPointFromSeries';
import * as layoutUtil from '../../util/layout';
import Model from '../../model/Model';
import * as globalListener from '../axisPointer/globalListener';
import * as axisHelper from '../../coord/axisHelper';
import * as axisPointerViewHelper from '../axisPointer/viewHelper';
34
import { getTooltipRenderMode } from '../../util/model';
S
sushuang 已提交
35 36 37 38 39 40 41 42

var bind = zrUtil.bind;
var each = zrUtil.each;
var parsePercent = numberUtil.parsePercent;

var proxyRect = new graphic.Rect({
    shape: {x: -1, y: -1, width: 2, height: 2}
});
L
lang 已提交
43

S
sushuang 已提交
44
export default echarts.extendComponentView({
L
lang 已提交
45

S
sushuang 已提交
46
    type: 'tooltip',
L
lang 已提交
47

S
sushuang 已提交
48 49 50 51
    init: function (ecModel, api) {
        if (env.node) {
            return;
        }
52

O
Ovilia 已提交
53 54
        var tooltipModel = ecModel.getComponent('tooltip');
        var renderMode = tooltipModel.get('renderMode');
55
        this._renderMode = getTooltipRenderMode(renderMode);
56

57 58 59 60
        var tooltipContent;
        if (this._renderMode === 'html') {
            tooltipContent = new TooltipContent(api.getDom(), api);
            this._newLine = '<br/>';
61 62
        }
        else {
63 64
            tooltipContent = new TooltipRichContent(api);
            this._newLine = '\n';
65 66
        }

S
sushuang 已提交
67
        this._tooltipContent = tooltipContent;
68 69 70 71

        this._event = {};
        this._viewWidth = document.body.clientWidth;
        this._viewHeight = document.body.clientHeight;
S
sushuang 已提交
72
    },
73

S
sushuang 已提交
74
    render: function (tooltipModel, ecModel, api) {
O
Ovilia 已提交
75
        if (env.node) {
S
sushuang 已提交
76 77
            return;
        }
L
lang 已提交
78

S
sushuang 已提交
79 80
        // Reset
        this.group.removeAll();
L
lang 已提交
81

S
sushuang 已提交
82 83 84 85 86
        /**
         * @private
         * @type {module:echarts/component/tooltip/TooltipModel}
         */
        this._tooltipModel = tooltipModel;
87

S
sushuang 已提交
88 89 90 91 92
        /**
         * @private
         * @type {module:echarts/model/Global}
         */
        this._ecModel = ecModel;
P
pah100 已提交
93

S
sushuang 已提交
94 95 96 97 98
        /**
         * @private
         * @type {module:echarts/ExtensionAPI}
         */
        this._api = api;
L
lang 已提交
99 100

        /**
S
sushuang 已提交
101 102 103
         * Should be cleaned when render.
         * @private
         * @type {Array.<Array.<Object>>}
L
lang 已提交
104
         */
S
sushuang 已提交
105
        this._lastDataByCoordSys = null;
P
pah100 已提交
106

S
sushuang 已提交
107 108 109 110 111
        /**
         * @private
         * @type {boolean}
         */
        this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
P
pah100 已提交
112

S
sushuang 已提交
113 114 115
        var tooltipContent = this._tooltipContent;
        tooltipContent.update();
        tooltipContent.setEnterable(tooltipModel.get('enterable'));
P
pah100 已提交
116

S
sushuang 已提交
117
        this._initGlobalListener();
118

S
sushuang 已提交
119 120
        this._keepShow();
    },
121

S
sushuang 已提交
122 123 124
    _initGlobalListener: function () {
        var tooltipModel = this._tooltipModel;
        var triggerOn = tooltipModel.get('triggerOn');
125

S
sushuang 已提交
126 127 128 129 130 131 132
        globalListener.register(
            'itemTooltip',
            this._api,
            bind(function (currTrigger, e, dispatchAction) {
                // If 'none', it is not controlled by mouse totally.
                if (triggerOn !== 'none') {
                    if (triggerOn.indexOf(currTrigger) >= 0) {
133
                        this._event = e.event;
S
sushuang 已提交
134 135 136 137 138
                        this._tryShow(e, dispatchAction);
                    }
                    else if (currTrigger === 'leave') {
                        this._hide(dispatchAction);
                    }
L
lang 已提交
139
                }
S
sushuang 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
            }, this)
        );
    },

    _keepShow: function () {
        var tooltipModel = this._tooltipModel;
        var ecModel = this._ecModel;
        var api = this._api;

        // Try to keep the tooltip show when refreshing
        if (this._lastX != null
            && this._lastY != null
            // When user is willing to control tooltip totally using API,
            // self.manuallyShowTip({x, y}) might cause tooltip hide,
            // which is not expected.
            && tooltipModel.get('triggerOn') !== 'none'
        ) {
            var self = this;
            clearTimeout(this._refreshUpdateTimeout);
            this._refreshUpdateTimeout = setTimeout(function () {
                // Show tip next tick after other charts are rendered
                // In case highlight action has wrong result
162
                // FIXME
163
                !api.isDisposed() && self.manuallyShowTip(tooltipModel, ecModel, api, {
S
sushuang 已提交
164 165
                    x: self._lastX,
                    y: self._lastY
166
                });
S
sushuang 已提交
167 168 169
            });
        }
    },
170

S
sushuang 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
    /**
     * Show tip manually by
     * dispatchAction({
     *     type: 'showTip',
     *     x: 10,
     *     y: 10
     * });
     * Or
     * dispatchAction({
     *      type: 'showTip',
     *      seriesIndex: 0,
     *      dataIndex or dataIndexInside or name
     * });
     *
     *  TODO Batch
     */
    manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
        if (payload.from === this.uid || env.node) {
            return;
        }
191

S
sushuang 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
        var dispatchAction = makeDispatchAction(payload, api);

        // Reset ticket
        this._ticket = '';

        // When triggered from axisPointer.
        var dataByCoordSys = payload.dataByCoordSys;

        if (payload.tooltip && payload.x != null && payload.y != null) {
            var el = proxyRect;
            el.position = [payload.x, payload.y];
            el.update();
            el.tooltip = payload.tooltip;
            // Manually show tooltip while view is not using zrender elements.
            this._tryShow({
                offsetX: payload.x,
                offsetY: payload.y,
209 210
                target: el,
                event: this._event
S
sushuang 已提交
211 212 213 214 215 216 217
            }, dispatchAction);
        }
        else if (dataByCoordSys) {
            this._tryShow({
                offsetX: payload.x,
                offsetY: payload.y,
                position: payload.position,
218
                event: this._event,
S
sushuang 已提交
219 220 221 222 223
                dataByCoordSys: payload.dataByCoordSys,
                tooltipOption: payload.tooltipOption
            }, dispatchAction);
        }
        else if (payload.seriesIndex != null) {
224

S
sushuang 已提交
225
            if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
226 227 228
                return;
            }

S
sushuang 已提交
229 230 231 232 233 234 235 236 237
            var pointInfo = findPointFromSeries(payload, ecModel);
            var cx = pointInfo.point[0];
            var cy = pointInfo.point[1];
            if (cx != null && cy != null) {
                this._tryShow({
                    offsetX: cx,
                    offsetY: cy,
                    position: payload.position,
                    target: pointInfo.el,
238
                    event: this._event
S
sushuang 已提交
239
                }, dispatchAction);
240
            }
S
sushuang 已提交
241 242 243 244
        }
        else if (payload.x != null && payload.y != null) {
            // FIXME
            // should wrap dispatchAction like `axisPointer/globalListener` ?
245 246
            api.dispatchAction({
                type: 'updateAxisPointer',
S
sushuang 已提交
247 248
                x: payload.x,
                y: payload.y
249 250
            });

S
sushuang 已提交
251 252 253 254 255
            this._tryShow({
                offsetX: payload.x,
                offsetY: payload.y,
                position: payload.position,
                target: api.getZr().findHover(payload.x, payload.y).target,
256
                event: this._event
S
sushuang 已提交
257 258 259
            }, dispatchAction);
        }
    },
260

S
sushuang 已提交
261 262
    manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
        var tooltipContent = this._tooltipContent;
L
lang 已提交
263

O
Ovilia 已提交
264
        if (!this._alwaysShowContent && this._tooltipModel) {
S
sushuang 已提交
265 266
            tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
        }
L
lang 已提交
267

S
sushuang 已提交
268
        this._lastX = this._lastY = null;
269

S
sushuang 已提交
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
        if (payload.from !== this.uid) {
            this._hide(makeDispatchAction(payload, api));
        }
    },

    // Be compatible with previous design, that is, when tooltip.type is 'axis' and
    // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
    // and tooltip.
    _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
        var seriesIndex = payload.seriesIndex;
        var dataIndex = payload.dataIndex;
        var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;

        if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
            return;
        }
L
lang 已提交
286

S
sushuang 已提交
287 288 289 290
        var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
        if (!seriesModel) {
            return;
        }
P
pah100 已提交
291

S
sushuang 已提交
292 293 294 295 296 297 298
        var data = seriesModel.getData();
        var tooltipModel = buildTooltipModel([
            data.getItemModel(dataIndex),
            seriesModel,
            (seriesModel.coordinateSystem || {}).model,
            tooltipModel
        ]);
D
deqingli 已提交
299

S
sushuang 已提交
300 301 302
        if (tooltipModel.get('trigger') !== 'axis') {
            return;
        }
P
pah100 已提交
303

S
sushuang 已提交
304 305 306 307 308 309
        api.dispatchAction({
            type: 'updateAxisPointer',
            seriesIndex: seriesIndex,
            dataIndex: dataIndex,
            position: payload.position
        });
P
pah100 已提交
310

S
sushuang 已提交
311 312
        return true;
    },
313

S
sushuang 已提交
314 315 316
    _tryShow: function (e, dispatchAction) {
        var el = e.target;
        var tooltipModel = this._tooltipModel;
L
lang 已提交
317

S
sushuang 已提交
318 319 320
        if (!tooltipModel) {
            return;
        }
P
pah100 已提交
321

S
sushuang 已提交
322
        // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
323 324
        this._lastX = e.event.pageX;
        this._lastY = e.event.pageY;
L
lang 已提交
325

S
sushuang 已提交
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
        var dataByCoordSys = e.dataByCoordSys;
        if (dataByCoordSys && dataByCoordSys.length) {
            this._showAxisTooltip(dataByCoordSys, e);
        }
        // Always show item tooltip if mouse is on the element with dataIndex
        else if (el && el.dataIndex != null) {
            this._lastDataByCoordSys = null;
            this._showSeriesItemTooltip(e, el, dispatchAction);
        }
        // Tooltip provided directly. Like legend.
        else if (el && el.tooltip) {
            this._lastDataByCoordSys = null;
            this._showComponentItemTooltip(e, el, dispatchAction);
        }
        else {
            this._lastDataByCoordSys = null;
            this._hide(dispatchAction);
        }
    },

    _showOrMove: function (tooltipModel, cb) {
        // showDelay is used in this case: tooltip.enterable is set
        // as true. User intent to move mouse into tooltip and click
        // something. `showDelay` makes it easyer to enter the content
        // but tooltip do not move immediately.
        var delay = tooltipModel.get('showDelay');
        cb = zrUtil.bind(cb, this);
        clearTimeout(this._showTimout);
        delay > 0
            ? (this._showTimout = setTimeout(cb, delay))
            : cb();
    },

    _showAxisTooltip: function (dataByCoordSys, e) {
        var ecModel = this._ecModel;
        var globalTooltipModel = this._tooltipModel;
362
        var point = [e.event.pageX, e.event.pageY];
S
sushuang 已提交
363 364 365 366 367 368 369
        var singleDefaultHTML = [];
        var singleParamsList = [];
        var singleTooltipModel = buildTooltipModel([
            e.tooltipOption,
            globalTooltipModel
        ]);

370
        var renderMode = this._renderMode;
371 372 373 374
        var newLine = this._newLine;

        var markers = {};

S
sushuang 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
        each(dataByCoordSys, function (itemCoordSys) {
            // var coordParamList = [];
            // var coordDefaultHTML = [];
            // var coordTooltipModel = buildTooltipModel([
            //     e.tooltipOption,
            //     itemCoordSys.tooltipOption,
            //     ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
            //     globalTooltipModel
            // ]);
            // var displayMode = coordTooltipModel.get('displayMode');
            // var paramsList = displayMode === 'single' ? singleParamsList : [];

            each(itemCoordSys.dataByAxis, function (item) {
                var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
                var axisValue = item.value;
                var seriesDefaultHTML = [];

                if (!axisModel || axisValue == null) {
                    return;
                }
L
lang 已提交
395

S
sushuang 已提交
396 397 398 399
                var valueLabel = axisPointerViewHelper.getValueLabel(
                    axisValue, axisModel.axis, ecModel,
                    item.seriesDataIndices,
                    item.valueLabelOpt
400
                );
P
tweak  
pah100 已提交
401

S
sushuang 已提交
402 403 404 405 406 407 408 409 410 411 412 413 414
                zrUtil.each(item.seriesDataIndices, function (idxItem) {
                    var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
                    var dataIndex = idxItem.dataIndexInside;
                    var dataParams = series && series.getDataParams(dataIndex);
                    dataParams.axisDim = item.axisDim;
                    dataParams.axisIndex = item.axisIndex;
                    dataParams.axisType = item.axisType;
                    dataParams.axisId = item.axisId;
                    dataParams.axisValue = axisHelper.getAxisRawValue(axisModel.axis, axisValue);
                    dataParams.axisValueLabel = valueLabel;

                    if (dataParams) {
                        singleParamsList.push(dataParams);
415
                        var seriesTooltip = series.formatTooltip(dataIndex, true, null, renderMode);
416 417 418 419 420 421 422 423 424 425 426

                        var html;
                        if (zrUtil.isObject(seriesTooltip)) {
                            html = seriesTooltip.html;
                            var newMarkers = seriesTooltip.markers;
                            zrUtil.merge(markers, newMarkers);
                        }
                        else {
                            html = seriesTooltip;
                        }
                        seriesDefaultHTML.push(html);
L
lang 已提交
427
                    }
P
pah100 已提交
428
                });
L
lang 已提交
429

S
sushuang 已提交
430 431 432 433 434
                // Default tooltip content
                // FIXME
                // (1) shold be the first data which has name?
                // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
                var firstLine = valueLabel;
435
                if (renderMode !== 'html') {
S
sushuang 已提交
436
                    singleDefaultHTML.push(seriesDefaultHTML.join(newLine));
437 438 439 440 441 442 443
                }
                else {
                    singleDefaultHTML.push(
                        (firstLine ? formatUtil.encodeHTML(firstLine) + newLine : '')
                        + seriesDefaultHTML.join(newLine)
                    );
                }
S
sushuang 已提交
444 445 446 447 448
            });
        }, this);

        // In most case, the second axis is shown upper than the first one.
        singleDefaultHTML.reverse();
449
        singleDefaultHTML = singleDefaultHTML.join(this._newLine + this._newLine);
S
sushuang 已提交
450 451 452 453 454 455 456 457 458 459

        var positionExpr = e.position;
        this._showOrMove(singleTooltipModel, function () {
            if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
                this._updatePosition(
                    singleTooltipModel,
                    positionExpr,
                    point[0], point[1],
                    this._tooltipContent,
                    singleParamsList
P
pah100 已提交
460
                );
L
lang 已提交
461 462
            }
            else {
S
sushuang 已提交
463 464
                this._showTooltipContent(
                    singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
465
                    point[0], point[1], positionExpr, undefined, markers
P
pah100 已提交
466
                );
L
lang 已提交
467
            }
S
sushuang 已提交
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
        });

        // Do not trigger events here, because this branch only be entered
        // from dispatchAction.
    },

    _showSeriesItemTooltip: function (e, el, dispatchAction) {
        var ecModel = this._ecModel;
        // Use dataModel in element if possible
        // Used when mouseover on a element like markPoint or edge
        // In which case, the data is not main data in series.
        var seriesIndex = el.seriesIndex;
        var seriesModel = ecModel.getSeriesByIndex(seriesIndex);

        // For example, graph link.
        var dataModel = el.dataModel || seriesModel;
        var dataIndex = el.dataIndex;
        var dataType = el.dataType;
        var data = dataModel.getData();

        var tooltipModel = buildTooltipModel([
            data.getItemModel(dataIndex),
            dataModel,
            seriesModel && (seriesModel.coordinateSystem || {}).model,
            this._tooltipModel
        ]);

        var tooltipTrigger = tooltipModel.get('trigger');
        if (tooltipTrigger != null && tooltipTrigger !== 'item') {
            return;
        }
L
lang 已提交
499

S
sushuang 已提交
500
        var params = dataModel.getDataParams(dataIndex, dataType);
501
        var seriesTooltip = dataModel.formatTooltip(dataIndex, false, dataType, this._renderMode);
O
Ovilia 已提交
502 503
        var defaultHtml;
        var markers;
504 505 506 507 508 509 510 511 512
        if (zrUtil.isObject(seriesTooltip)) {
            defaultHtml = seriesTooltip.html;
            markers = seriesTooltip.markers;
        }
        else {
            defaultHtml = seriesTooltip;
            markers = null;
        }

S
sushuang 已提交
513
        var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
L
lang 已提交
514

S
sushuang 已提交
515 516 517
        this._showOrMove(tooltipModel, function () {
            this._showTooltipContent(
                tooltipModel, defaultHtml, params, asyncTicket,
S
sushuang 已提交
518
                e.event.pageX, e.event.pageY, e.position, e.target, markers
S
sushuang 已提交
519 520
            );
        });
P
pah100 已提交
521 522

        // FIXME
S
sushuang 已提交
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
        // duplicated showtip if manuallyShowTip is called from dispatchAction.
        dispatchAction({
            type: 'showTip',
            dataIndexInside: dataIndex,
            dataIndex: data.getRawIndex(dataIndex),
            seriesIndex: seriesIndex,
            from: this.uid
        });
    },

    _showComponentItemTooltip: function (e, el, dispatchAction) {
        var tooltipOpt = el.tooltip;
        if (typeof tooltipOpt === 'string') {
            var content = tooltipOpt;
            tooltipOpt = {
                content: content,
                // Fixed formatter
                formatter: content
            };
        }
        var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
        var defaultHtml = subTooltipModel.get('content');
        var asyncTicket = Math.random();

        // Do not check whether `trigger` is 'none' here, because `trigger`
        // only works on cooridinate system. In fact, we have not found case
        // that requires setting `trigger` nothing on component yet.

        this._showOrMove(subTooltipModel, function () {
            this._showTooltipContent(
                subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
554
                asyncTicket, e.event.pageX, e.event.pageY, e.position, el
S
sushuang 已提交
555 556 557 558 559 560 561 562 563 564 565
            );
        });

        // If not dispatch showTip, tip may be hide triggered by axis.
        dispatchAction({
            type: 'showTip',
            from: this.uid
        });
    },

    _showTooltipContent: function (
566
        tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markers
S
sushuang 已提交
567 568 569 570 571 572 573
    ) {
        // Reset ticket
        this._ticket = '';

        if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
            return;
        }
P
pah100 已提交
574

S
sushuang 已提交
575
        var tooltipContent = this._tooltipContent;
P
pah100 已提交
576

S
sushuang 已提交
577 578 579
        var formatter = tooltipModel.get('formatter');
        positionExpr = positionExpr || tooltipModel.get('position');
        var html = defaultHtml;
P
pah100 已提交
580

S
sushuang 已提交
581 582 583 584 585 586
        if (formatter && typeof formatter === 'string') {
            html = formatUtil.formatTpl(formatter, params, true);
        }
        else if (typeof formatter === 'function') {
            var callback = bind(function (cbTicket, html) {
                if (cbTicket === this._ticket) {
587
                    tooltipContent.setContent(html, markers, tooltipModel);
S
sushuang 已提交
588 589 590 591 592 593 594 595
                    this._updatePosition(
                        tooltipModel, positionExpr, x, y, tooltipContent, params, el
                    );
                }
            }, this);
            this._ticket = asyncTicket;
            html = formatter(params, asyncTicket, callback);
        }
P
pah100 已提交
596

597
        tooltipContent.setContent(html, markers, tooltipModel);
S
sushuang 已提交
598
        tooltipContent.show(tooltipModel);
P
pah100 已提交
599

S
sushuang 已提交
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
        this._updatePosition(
            tooltipModel, positionExpr, x, y, tooltipContent, params, el
        );
    },

    /**
     * @param  {string|Function|Array.<number>|Object} positionExpr
     * @param  {number} x Mouse x
     * @param  {number} y Mouse y
     * @param  {boolean} confine Whether confine tooltip content in view rect.
     * @param  {Object|<Array.<Object>} params
     * @param  {module:zrender/Element} el target element
     * @param  {module:echarts/ExtensionAPI} api
     * @return {Array.<number>}
     */
    _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
616 617
        var viewWidth = this._viewWidth;
        var viewHeight = this._viewHeight;
S
sushuang 已提交
618 619 620 621 622 623 624 625 626 627 628 629 630
        positionExpr = positionExpr || tooltipModel.get('position');

        var contentSize = content.getSize();
        var align = tooltipModel.get('align');
        var vAlign = tooltipModel.get('verticalAlign');
        var rect = el && el.getBoundingRect().clone();
        el && rect.applyTransform(el.transform);

        if (typeof positionExpr === 'function') {
            // Callback of position can be an array or a string specify the position
            positionExpr = positionExpr([x, y], params, content.el, rect, {
                viewSize: [viewWidth, viewHeight],
                contentSize: contentSize.slice()
631
            });
S
sushuang 已提交
632
        }
L
lang 已提交
633

S
sushuang 已提交
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
        if (zrUtil.isArray(positionExpr)) {
            x = parsePercent(positionExpr[0], viewWidth);
            y = parsePercent(positionExpr[1], viewHeight);
        }
        else if (zrUtil.isObject(positionExpr)) {
            positionExpr.width = contentSize[0];
            positionExpr.height = contentSize[1];
            var layoutRect = layoutUtil.getLayoutRect(
                positionExpr, {width: viewWidth, height: viewHeight}
            );
            x = layoutRect.x;
            y = layoutRect.y;
            align = null;
            // When positionExpr is left/top/right/bottom,
            // align and verticalAlign will not work.
            vAlign = null;
        }
        // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
        else if (typeof positionExpr === 'string' && el) {
            var pos = calcTooltipPosition(
                positionExpr, rect, contentSize
            );
            x = pos[0];
            y = pos[1];
        }
        else {
            var pos = refixTooltipPosition(
661
                x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
S
sushuang 已提交
662 663 664
            );
            x = pos[0];
            y = pos[1];
L
lang 已提交
665
        }
P
pah100 已提交
666

S
sushuang 已提交
667 668
        align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
        vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
P
pah100 已提交
669

S
sushuang 已提交
670 671
        if (tooltipModel.get('confine')) {
            var pos = confineTooltipPosition(
672
                x, y, content, viewWidth, viewHeight
S
sushuang 已提交
673 674 675
            );
            x = pos[0];
            y = pos[1];
P
pah100 已提交
676 677
        }

S
sushuang 已提交
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
        content.moveTo(x, y);
    },

    // FIXME
    // Should we remove this but leave this to user?
    _updateContentNotChangedOnAxis: function (dataByCoordSys) {
        var lastCoordSys = this._lastDataByCoordSys;
        var contentNotChanged = !!lastCoordSys
            && lastCoordSys.length === dataByCoordSys.length;

        contentNotChanged && each(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
            var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
            var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
            var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
            contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;

            contentNotChanged && each(lastDataByAxis, function (lastItem, indexAxis) {
                var thisItem = thisDataByAxis[indexAxis] || {};
                var lastIndices = lastItem.seriesDataIndices || [];
                var newIndices = thisItem.seriesDataIndices || [];

S
sushuang 已提交
699 700
                contentNotChanged
                    &= lastItem.value === thisItem.value
S
sushuang 已提交
701 702 703 704 705 706
                    && lastItem.axisType === thisItem.axisType
                    && lastItem.axisId === thisItem.axisId
                    && lastIndices.length === newIndices.length;

                contentNotChanged && each(lastIndices, function (lastIdxItem, j) {
                    var newIdxItem = newIndices[j];
S
sushuang 已提交
707 708
                    contentNotChanged
                        &= lastIdxItem.seriesIndex === newIdxItem.seriesIndex
S
sushuang 已提交
709 710 711 712
                        && lastIdxItem.dataIndex === newIdxItem.dataIndex;
                });
            });
        });
P
pah100 已提交
713

S
sushuang 已提交
714
        this._lastDataByCoordSys = dataByCoordSys;
P
pah100 已提交
715

S
sushuang 已提交
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
        return !!contentNotChanged;
    },

    _hide: function (dispatchAction) {
        // Do not directly hideLater here, because this behavior may be prevented
        // in dispatchAction when showTip is dispatched.

        // FIXME
        // duplicated hideTip if manuallyHideTip is called from dispatchAction.
        this._lastDataByCoordSys = null;
        dispatchAction({
            type: 'hideTip',
            from: this.uid
        });
    },

    dispose: function (ecModel, api) {
O
Ovilia 已提交
733
        if (env.node) {
S
sushuang 已提交
734
            return;
P
pah100 已提交
735
        }
736
        this._tooltipContent.dispose();
S
sushuang 已提交
737 738 739 740 741 742 743 744 745 746 747 748 749 750
        globalListener.unregister('itemTooltip', api);
    }
});


/**
 * @param {Array.<Object|module:echarts/model/Model>} modelCascade
 * From top to bottom. (the last one should be globalTooltipModel);
 */
function buildTooltipModel(modelCascade) {
    var resultModel = modelCascade.pop();
    while (modelCascade.length) {
        var tooltipOpt = modelCascade.pop();
        if (tooltipOpt) {
751
            if (Model.isInstance(tooltipOpt)) {
S
sushuang 已提交
752 753 754 755 756 757 758 759 760
                tooltipOpt = tooltipOpt.get('tooltip', true);
            }
            // In each data item tooltip can be simply write:
            // {
            //  value: 10,
            //  tooltip: 'Something you need to know'
            // }
            if (typeof tooltipOpt === 'string') {
                tooltipOpt = {formatter: tooltipOpt};
P
tweak  
pah100 已提交
761
            }
S
sushuang 已提交
762
            resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
P
pah100 已提交
763 764
        }
    }
S
sushuang 已提交
765 766
    return resultModel;
}
P
pah100 已提交
767

S
sushuang 已提交
768 769 770
function makeDispatchAction(payload, api) {
    return payload.dispatchAction || zrUtil.bind(api.dispatchAction, api);
}
P
pah100 已提交
771

772 773
function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
    var size = content.getOuterSize();
S
sushuang 已提交
774 775
    var width = size.width;
    var height = size.height;
P
pah100 已提交
776

S
sushuang 已提交
777 778 779 780 781 782 783
    if (gapH != null) {
        if (x + width + gapH > viewWidth) {
            x -= width + gapH;
        }
        else {
            x += gapH;
        }
P
pah100 已提交
784
    }
S
sushuang 已提交
785 786 787 788 789 790
    if (gapV != null) {
        if (y + height + gapV > viewHeight) {
            y -= height + gapV;
        }
        else {
            y += gapV;
P
pah100 已提交
791 792
        }
    }
S
sushuang 已提交
793 794 795
    return [x, y];
}

796 797
function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
    var size = content.getOuterSize();
S
sushuang 已提交
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
    var width = size.width;
    var height = size.height;

    x = Math.min(x + width, viewWidth) - width;
    y = Math.min(y + height, viewHeight) - height;
    x = Math.max(x, 0);
    y = Math.max(y, 0);

    return [x, y];
}

function calcTooltipPosition(position, rect, contentSize) {
    var domWidth = contentSize[0];
    var domHeight = contentSize[1];
    var gap = 5;
    var x = 0;
    var y = 0;
    var rectWidth = rect.width;
    var rectHeight = rect.height;
    switch (position) {
        case 'inside':
            x = rect.x + rectWidth / 2 - domWidth / 2;
            y = rect.y + rectHeight / 2 - domHeight / 2;
            break;
        case 'top':
            x = rect.x + rectWidth / 2 - domWidth / 2;
            y = rect.y - domHeight - gap;
            break;
        case 'bottom':
            x = rect.x + rectWidth / 2 - domWidth / 2;
            y = rect.y + rectHeight + gap;
            break;
        case 'left':
            x = rect.x - domWidth - gap;
            y = rect.y + rectHeight / 2 - domHeight / 2;
            break;
        case 'right':
            x = rect.x + rectWidth + gap;
            y = rect.y + rectHeight / 2 - domHeight / 2;
P
pah100 已提交
837
    }
S
sushuang 已提交
838 839
    return [x, y];
}
P
pah100 已提交
840

S
sushuang 已提交
841 842 843
function isCenterAlign(align) {
    return align === 'center' || align === 'middle';
}