TooltipView.js 45.6 KB
Newer Older
L
lang 已提交
1 2 3 4 5 6 7
define(function (require) {

    var TooltipContent = require('./TooltipContent');
    var graphic = require('../../util/graphic');
    var zrUtil = require('zrender/core/util');
    var formatUtil = require('../../util/format');
    var numberUtil = require('../../util/number');
8
    var modelUtil = require('../../util/model');
L
lang 已提交
9
    var parsePercent = numberUtil.parsePercent;
L
lang 已提交
10
    var env = require('zrender/core/env');
L
lang 已提交
11
    var Model = require('../../model/Model');
L
lang 已提交
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

    function dataEqual(a, b) {
        if (!a || !b) {
            return false;
        }
        var round = numberUtil.round;
        return round(a[0]) === round(b[0])
            && round(a[1]) === round(b[1]);
    }
    /**
     * @inner
     */
    function makeLineShape(x1, y1, x2, y2) {
        return {
            x1: x1,
            y1: y1,
            x2: x2,
            y2: y2
        };
    }

    /**
     * @inner
     */
    function makeRectShape(x, y, width, height) {
        return {
            x: x,
            y: y,
            width: width,
            height: height
        };
    }

    /**
     * @inner
     */
    function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) {
        return {
            cx: cx,
            cy: cy,
            r0: r0,
            r: r,
            startAngle: startAngle,
            endAngle: endAngle,
            clockwise: true
        };
    }

    function refixTooltipPosition(x, y, el, viewWidth, viewHeight) {
        var width = el.clientWidth;
        var height = el.clientHeight;
        var gap = 20;

        if (x + width + gap > viewWidth) {
            x -= width + gap;
        }
        else {
            x += gap;
        }
        if (y + height + gap > viewHeight) {
            y -= height + gap;
        }
        else {
            y += gap;
        }
        return [x, y];
    }

1
100pah 已提交
80 81 82 83 84 85 86 87 88 89 90 91
    function confineTooltipPosition(x, y, el, viewWidth, viewHeight) {
        var width = el.clientWidth;
        var height = el.clientHeight;

        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];
    }

L
lang 已提交
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
    function calcTooltipPosition(position, rect, dom) {
        var domWidth = dom.clientWidth;
        var domHeight = dom.clientHeight;
        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;
        }
        return [x, y];
    }

    /**
     * @param  {string|Function|Array.<number>} positionExpr
     * @param  {number} x Mouse x
     * @param  {number} y Mouse y
1
100pah 已提交
128
     * @param  {boolean} confine Whether confine tooltip content in view rect.
L
lang 已提交
129 130 131 132 133 134
     * @param  {module:echarts/component/tooltip/TooltipContent} content
     * @param  {Object|<Array.<Object>} params
     * @param  {module:zrender/Element} el target element
     * @param  {module:echarts/ExtensionAPI} api
     * @return {Array.<number>}
     */
1
100pah 已提交
135
    function updatePosition(positionExpr, x, y, confine, content, params, el, api) {
L
lang 已提交
136 137 138 139 140 141
        var viewWidth = api.getWidth();
        var viewHeight = api.getHeight();

        var rect = el && el.getBoundingRect().clone();
        el && rect.applyTransform(el.transform);
        if (typeof positionExpr === 'function') {
L
lang 已提交
142 143
            // Callback of position can be an array or a string specify the position
            positionExpr = positionExpr([x, y], params, content.el, rect);
L
lang 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
        }

        if (zrUtil.isArray(positionExpr)) {
            x = parsePercent(positionExpr[0], viewWidth);
            y = parsePercent(positionExpr[1], viewHeight);
        }
        // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
        else if (typeof positionExpr === 'string' && el) {
            var pos = calcTooltipPosition(
                positionExpr, rect, content.el
            );
            x = pos[0];
            y = pos[1];
        }
        else {
            var pos = refixTooltipPosition(
                x, y, content.el, viewWidth, viewHeight
            );
            x = pos[0];
            y = pos[1];
        }

1
100pah 已提交
166 167 168 169 170 171 172 173
        if (confine) {
            var pos = confineTooltipPosition(
                x, y, content.el, viewWidth, viewHeight
            );
            x = pos[0];
            y = pos[1];
        }

L
lang 已提交
174 175 176 177 178 179 180 181
        content.moveTo(x, y);
    }

    function ifSeriesSupportAxisTrigger(seriesModel) {
        var coordSys = seriesModel.coordinateSystem;
        var trigger = seriesModel.get('tooltip.trigger', true);
        // Ignore series use item tooltip trigger and series coordinate system is not cartesian or
        return !(!coordSys
182
            || (coordSys.type !== 'cartesian2d' && coordSys.type !== 'polar' && coordSys.type !== 'singleAxis')
L
lang 已提交
183 184 185 186 187 188 189 190 191 192
            || trigger === 'item');
    }

    require('../../echarts').extendComponentView({

        type: 'tooltip',

        _axisPointers: {},

        init: function (ecModel, api) {
193
            if (env.node) {
L
lang 已提交
194 195
                return;
            }
L
lang 已提交
196 197 198 199
            var tooltipContent = new TooltipContent(api.getDom(), api);
            this._tooltipContent = tooltipContent;

            api.on('showTip', this._manuallyShowTip, this);
200
            api.on('hideTip', this._manuallyHideTip, this);
L
lang 已提交
201 202 203
        },

        render: function (tooltipModel, ecModel, api) {
204
            if (env.node) {
L
lang 已提交
205 206
                return;
            }
207

L
lang 已提交
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
            // Reset
            this.group.removeAll();

            /**
             * @type {Object}
             * @private
             */
            this._axisPointers = {};

            /**
             * @private
             * @type {module:echarts/component/tooltip/TooltipModel}
             */
            this._tooltipModel = tooltipModel;

            /**
             * @private
             * @type {module:echarts/model/Global}
             */
            this._ecModel = ecModel;

            /**
             * @private
             * @type {module:echarts/ExtensionAPI}
             */
            this._api = api;

            /**
             * @type {Object}
             * @private
             */
            this._lastHover = {
                // data
                // payloadBatch
            };

            var tooltipContent = this._tooltipContent;
            tooltipContent.update();
L
Typo  
lang 已提交
246
            tooltipContent.enterable = tooltipModel.get('enterable');
L
lang 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260
            this._alwaysShowContent = tooltipModel.get('alwaysShowContent');

            /**
             * @type {Object.<string, Array>}
             */
            this._seriesGroupByAxis = this._prepareAxisTriggerData(
                tooltipModel, ecModel
            );

            var crossText = this._crossText;
            if (crossText) {
                this.group.add(crossText);
            }

1
100pah 已提交
261 262
            var triggerOn = tooltipModel.get('triggerOn');

263
            // Try to keep the tooltip show when refreshing
1
100pah 已提交
264 265 266 267 268 269 270
            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.
                && triggerOn !== 'none'
            ) {
L
tweak  
lang 已提交
271 272 273 274 275 276 277 278 279 280
                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
                    // FIXME
                    self._manuallyShowTip({
                        x: self._lastX,
                        y: self._lastY
                    });
281 282 283
                });
            }

L
lang 已提交
284
            var zr = this._api.getZr();
L
lang 已提交
285 286
            zr.off('click', this._tryShow);
            zr.off('mousemove', this._mousemove);
L
lang 已提交
287
            zr.off('mouseout', this._hide);
L
lang 已提交
288
            zr.off('globalout', this._hide);
1
100pah 已提交
289

290
            if (triggerOn === 'click') {
L
lang 已提交
291
                zr.on('click', this._tryShow, this);
L
lang 已提交
292
            }
293
            else if (triggerOn === 'mousemove') {
L
lang 已提交
294
                zr.on('mousemove', this._mousemove, this);
L
lang 已提交
295
                zr.on('mouseout', this._hide, this);
L
lang 已提交
296
                zr.on('globalout', this._hide, this);
L
lang 已提交
297
            }
298 299
            // else triggerOn is 'none', which enable user
            // to control tooltip totally using API.
L
lang 已提交
300
        },
301

L
lang 已提交
302 303 304 305 306 307 308 309 310 311 312 313
        _mousemove: function (e) {
            var showDelay = this._tooltipModel.get('showDelay');
            var self = this;
            clearTimeout(this._showTimeout);
            if (showDelay > 0) {
                this._showTimeout = setTimeout(function () {
                    self._tryShow(e);
                }, showDelay);
            }
            else {
                this._tryShow(e);
            }
L
lang 已提交
314 315 316 317
        },

        /**
         * Show tip manually by
318 319 320 321 322
         * dispatchAction({
         *     type: 'showTip',
         *     x: 10,
         *     y: 10
         * });
L
lang 已提交
323
         * Or
324
         * dispatchAction({
L
lang 已提交
325 326
         *      type: 'showTip',
         *      seriesIndex: 0,
327 328
         *      dataIndex or dataIndexInside or name
         * });
329 330
         *
         *  TODO Batch
L
lang 已提交
331 332 333 334 335 336 337 338 339 340 341 342
         */
        _manuallyShowTip: function (event) {
            // From self
            if (event.from === this.uid) {
                return;
            }

            var ecModel = this._ecModel;
            var seriesIndex = event.seriesIndex;
            var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
            var api = this._api;

343 344 345 346 347 348 349 350 351 352 353 354
            var isTriggerAxis = this._tooltipModel.get('trigger') === 'axis';
            function seriesHaveDataOnIndex(_series) {
                var data = _series.getData();
                var dataIndex = modelUtil.queryDataIndex(data, event);
                // Have single dataIndex
                if (dataIndex != null && !zrUtil.isArray(dataIndex)
                    && data.hasValue(dataIndex)
                ) {
                    return true;
                }
            }

L
lang 已提交
355
            if (event.x == null || event.y == null) {
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
                if (isTriggerAxis) {
                    // Find another series.
                    if (seriesModel && !seriesHaveDataOnIndex(seriesModel)) {
                        seriesModel = null;
                    }
                    if (!seriesModel) {
                        // Find the first series can use axis trigger And data is not null
                        ecModel.eachSeries(function (_series) {
                            if (ifSeriesSupportAxisTrigger(_series) && !seriesModel) {
                                if (seriesHaveDataOnIndex(_series)) {
                                    seriesModel = _series;
                                }
                            }
                        });
                    }
                }
                else {
                    // Use the first series by default.
                    seriesModel = seriesModel || ecModel.getSeriesByIndex(0);
L
lang 已提交
375 376
                }
                if (seriesModel) {
L
lang 已提交
377
                    var data = seriesModel.getData();
378 379 380 381
                    var dataIndex = modelUtil.queryDataIndex(data, event);

                    if (dataIndex == null || zrUtil.isArray(dataIndex)) {
                        return;
L
lang 已提交
382
                    }
383

L
lang 已提交
384
                    var el = data.getItemGraphicEl(dataIndex);
385 386
                    var cx;
                    var cy;
387 388
                    // Try to get the point in coordinate system
                    var coordSys = seriesModel.coordinateSystem;
389 390 391 392 393 394
                    if (seriesModel.getTooltipPosition) {
                        var point = seriesModel.getTooltipPosition(dataIndex) || [];
                        cx = point[0];
                        cy = point[1];
                    }
                    else if (coordSys && coordSys.dataToPoint) {
395
                        var point = coordSys.dataToPoint(
396 397 398 399 400
                            data.getValues(
                                zrUtil.map(coordSys.dimensions, function (dim) {
                                    return seriesModel.coordDimToDataDim(dim)[0];
                                }), dataIndex, true
                            )
401 402 403 404 405
                        );
                        cx = point && point[0];
                        cy = point && point[1];
                    }
                    else if (el) {
L
lang 已提交
406 407 408
                        // Use graphic bounding rect
                        var rect = el.getBoundingRect().clone();
                        rect.applyTransform(el.transform);
409 410 411
                        cx = rect.x + rect.width / 2;
                        cy = rect.y + rect.height / 2;
                    }
412

413
                    if (cx != null && cy != null) {
L
lang 已提交
414 415 416
                        this._tryShow({
                            offsetX: cx,
                            offsetY: cy,
417
                            position: event.position,
L
lang 已提交
418 419 420 421 422 423 424
                            target: el,
                            event: {}
                        });
                    }
                }
            }
            else {
425 426 427 428
                var el = api.getZr().handler.findHover(event.x, event.y);
                this._tryShow({
                    offsetX: event.x,
                    offsetY: event.y,
429
                    position: event.position,
430 431
                    target: el,
                    event: {}
L
lang 已提交
432 433 434 435
                });
            }
        },

436 437 438 439 440 441 442 443
        _manuallyHideTip: function (e) {
            if (e.from === this.uid) {
                return;
            }

            this._hide();
        },

L
lang 已提交
444 445 446 447 448 449 450 451 452
        _prepareAxisTriggerData: function (tooltipModel, ecModel) {
            // Prepare data for axis trigger
            var seriesGroupByAxis = {};
            ecModel.eachSeries(function (seriesModel) {
                if (ifSeriesSupportAxisTrigger(seriesModel)) {
                    var coordSys = seriesModel.coordinateSystem;
                    var baseAxis;
                    var key;

L
lang 已提交
453
                    // Only cartesian2d, polar and single support axis trigger
L
lang 已提交
454 455 456
                    if (coordSys.type === 'cartesian2d') {
                        // FIXME `axisPointer.axis` is not baseAxis
                        baseAxis = coordSys.getBaseAxis();
L
lang 已提交
457
                        key = baseAxis.dim + baseAxis.index;
L
lang 已提交
458
                    }
459
                    else if (coordSys.type === 'singleAxis') {
D
deqingli 已提交
460 461 462
                        baseAxis = coordSys.getAxis();
                        key = baseAxis.dim + baseAxis.type;
                    }
L
lang 已提交
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
                    else {
                        baseAxis = coordSys.getBaseAxis();
                        key = baseAxis.dim + coordSys.name;
                    }

                    seriesGroupByAxis[key] = seriesGroupByAxis[key] || {
                        coordSys: [],
                        series: []
                    };
                    seriesGroupByAxis[key].coordSys.push(coordSys);
                    seriesGroupByAxis[key].series.push(seriesModel);
                }
            }, this);

            return seriesGroupByAxis;
        },

        /**
         * mousemove handler
         * @param {Object} e
         * @private
         */
        _tryShow: function (e) {
            var el = e.target;
            var tooltipModel = this._tooltipModel;
            var globalTrigger = tooltipModel.get('trigger');
            var ecModel = this._ecModel;
            var api = this._api;

            if (!tooltipModel) {
                return;
            }

496 497 498 499
            // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
            this._lastX = e.offsetX;
            this._lastY = e.offsetY;

L
lang 已提交
500 501
            // Always show item tooltip if mouse is on the element with dataIndex
            if (el && el.dataIndex != null) {
L
lang 已提交
502
                // Use dataModel in element if possible
L
lang 已提交
503 504
                // Used when mouseover on a element like markPoint or edge
                // In which case, the data is not main data in series.
L
lang 已提交
505
                var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
L
lang 已提交
506
                var dataIndex = el.dataIndex;
507 508
                var data = dataModel.getData();
                var itemModel = data.getItemModel(dataIndex);
L
lang 已提交
509 510 511 512 513 514 515 516 517 518 519 520
                // Series or single data may use item trigger when global is axis trigger
                if ((itemModel.get('tooltip.trigger') || globalTrigger) === 'axis') {
                    this._showAxisTooltip(tooltipModel, ecModel, e);
                }
                else {
                    // Reset ticket
                    this._ticket = '';
                    // If either single data or series use item trigger
                    this._hideAxisPointer();
                    // Reset last hover and dispatch downplay action
                    this._resetLastHover();

521
                    this._showItemTooltipContent(dataModel, dataIndex, el.dataType, e);
L
lang 已提交
522 523 524 525 526
                }

                api.dispatchAction({
                    type: 'showTip',
                    from: this.uid,
527 528
                    dataIndexInside: dataIndex,
                    dataIndex: data.getRawIndex(dataIndex), // expose to user.
L
lang 已提交
529 530 531
                    seriesIndex: el.seriesIndex
                });
            }
L
lang 已提交
532 533
            // Tooltip provided directly. Like legend
            else if (el && el.tooltip) {
L
lang 已提交
534 535
                var tooltipOpt = el.tooltip;
                if (typeof tooltipOpt === 'string') {
536
                    var content = tooltipOpt;
L
lang 已提交
537
                    tooltipOpt = {
538 539
                        content: content,
                        // Fixed formatter
540
                        formatter: content
L
lang 已提交
541 542 543 544 545 546 547 548
                    };
                }
                var subTooltipModel = new Model(tooltipOpt, tooltipModel);
                var defaultHtml = subTooltipModel.get('content');
                var asyncTicket = Math.random();
                this._showTooltipContent(
                    // TODO params
                    subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
549
                    asyncTicket, e.offsetX, e.offsetY, e.position, el, api
L
lang 已提交
550
                );
L
lang 已提交
551
            }
L
lang 已提交
552 553 554 555 556 557 558 559 560
            else {
                if (globalTrigger === 'item') {
                    this._hide();
                }
                else {
                    // Try show axis tooltip
                    this._showAxisTooltip(tooltipModel, ecModel, e);
                }

561 562 563 564 565 566 567 568 569 570
                // Action of cross pointer
                // other pointer types will trigger action in _dispatchAndShowSeriesTooltipContent method
                if (tooltipModel.get('axisPointer.type') === 'cross') {
                    api.dispatchAction({
                        type: 'showTip',
                        from: this.uid,
                        x: e.offsetX,
                        y: e.offsetY
                    });
                }
L
lang 已提交
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
            }
        },

        /**
         * Show tooltip on axis
         * @param {module:echarts/component/tooltip/TooltipModel} tooltipModel
         * @param {module:echarts/model/Global} ecModel
         * @param {Object} e
         * @private
         */
        _showAxisTooltip: function (tooltipModel, ecModel, e) {
            var axisPointerModel = tooltipModel.getModel('axisPointer');
            var axisPointerType = axisPointerModel.get('type');

            if (axisPointerType === 'cross') {
                var el = e.target;
                if (el && el.dataIndex != null) {
                    var seriesModel = ecModel.getSeriesByIndex(el.seriesIndex);
                    var dataIndex = el.dataIndex;
590
                    this._showItemTooltipContent(seriesModel, dataIndex, el.dataType, e);
L
lang 已提交
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
                }
            }

            this._showAxisPointer();
            var allNotShow = true;
            zrUtil.each(this._seriesGroupByAxis, function (seriesCoordSysSameAxis) {
                // Try show the axis pointer
                var allCoordSys = seriesCoordSysSameAxis.coordSys;
                var coordSys = allCoordSys[0];

                // If mouse position is not in the grid or polar
                var point = [e.offsetX, e.offsetY];

                if (!coordSys.containPoint(point)) {
                    // Hide axis pointer
                    this._hideAxisPointer(coordSys.name);
                    return;
                }

                allNotShow = false;
                // Make sure point is discrete on cateogry axis
                var dimensions = coordSys.dimensions;
                var value = coordSys.pointToData(point, true);
                point = coordSys.dataToPoint(value);
                var baseAxis = coordSys.getBaseAxis();
                var axisType = axisPointerModel.get('axis');
                if (axisType === 'auto') {
                    axisType = baseAxis.dim;
                }

                var contentNotChange = false;
                var lastHover = this._lastHover;
                if (axisPointerType === 'cross') {
                    // If hover data not changed
                    // Possible when two axes are all category
                    if (dataEqual(lastHover.data, value)) {
                        contentNotChange = true;
                    }
                    lastHover.data = value;
                }
                else {
                    var valIndex = zrUtil.indexOf(dimensions, axisType);
D
deqingli 已提交
633

L
lang 已提交
634 635 636 637 638 639 640
                    // If hover data not changed on the axis dimension
                    if (lastHover.data === value[valIndex]) {
                        contentNotChange = true;
                    }
                    lastHover.data = value[valIndex];
                }

1
100pah 已提交
641 642
                var enableAnimation = tooltipModel.get('animation');

L
lang 已提交
643 644
                if (coordSys.type === 'cartesian2d' && !contentNotChange) {
                    this._showCartesianPointer(
1
100pah 已提交
645
                        axisPointerModel, coordSys, axisType, point, enableAnimation
L
lang 已提交
646 647 648 649
                    );
                }
                else if (coordSys.type === 'polar' && !contentNotChange) {
                    this._showPolarPointer(
1
100pah 已提交
650
                        axisPointerModel, coordSys, axisType, point, enableAnimation
L
lang 已提交
651 652
                    );
                }
653
                else if (coordSys.type === 'singleAxis' && !contentNotChange) {
D
deqingli 已提交
654
                    this._showSinglePointer(
1
100pah 已提交
655
                        axisPointerModel, coordSys, axisType, point, enableAnimation
D
deqingli 已提交
656 657
                    );
                }
L
lang 已提交
658 659

                if (axisPointerType !== 'cross') {
660
                    this._dispatchAndShowSeriesTooltipContent(
661
                        coordSys, seriesCoordSysSameAxis.series, point, value, contentNotChange, e.position
L
lang 已提交
662 663 664 665
                    );
                }
            }, this);

P
pah100 已提交
666 667 668 669
            if (!this._tooltipModel.get('show')) {
                this._hideAxisPointer();
            }

L
lang 已提交
670 671 672 673 674 675 676 677 678 679 680 681 682
            if (allNotShow) {
                this._hide();
            }
        },

        /**
         * Show tooltip on axis of cartesian coordinate
         * @param {module:echarts/model/Model} axisPointerModel
         * @param {module:echarts/coord/cartesian/Cartesian2D} cartesians
         * @param {string} axisType
         * @param {Array.<number>} point
         * @private
         */
1
100pah 已提交
683
        _showCartesianPointer: function (axisPointerModel, cartesian, axisType, point, enableAnimation) {
L
lang 已提交
684 685 686
            var self = this;

            var axisPointerType = axisPointerModel.get('type');
687
            var baseAxis = cartesian.getBaseAxis();
1
100pah 已提交
688 689
            var moveAnimation = enableAnimation
                && axisPointerType !== 'cross'
690 691
                && baseAxis.type === 'category'
                && baseAxis.getBandWidth() > 20;
L
lang 已提交
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

            if (axisPointerType === 'cross') {
                moveGridLine('x', point, cartesian.getAxis('y').getGlobalExtent());
                moveGridLine('y', point, cartesian.getAxis('x').getGlobalExtent());

                this._updateCrossText(cartesian, point, axisPointerModel);
            }
            else {
                var otherAxis = cartesian.getAxis(axisType === 'x' ? 'y' : 'x');
                var otherExtent = otherAxis.getGlobalExtent();

                if (cartesian.type === 'cartesian2d') {
                    (axisPointerType === 'line' ? moveGridLine : moveGridShadow)(
                        axisType, point, otherExtent
                    );
                }
            }

            /**
             * @inner
             */
            function moveGridLine(axisType, point, otherExtent) {
                var targetShape = axisType === 'x'
                    ? makeLineShape(point[0], otherExtent[0], point[0], otherExtent[1])
                    : makeLineShape(otherExtent[0], point[1], otherExtent[1], point[1]);

                var pointerEl = self._getPointerElement(
                    cartesian, axisPointerModel, axisType, targetShape
                );
L
lang 已提交
721 722 723 724 725
                graphic.subPixelOptimizeLine({
                    shape: targetShape,
                    style: pointerEl.style
                });

L
lang 已提交
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
                moveAnimation
                    ? graphic.updateProps(pointerEl, {
                        shape: targetShape
                    }, axisPointerModel)
                    :  pointerEl.attr({
                        shape: targetShape
                    });
            }

            /**
             * @inner
             */
            function moveGridShadow(axisType, point, otherExtent) {
                var axis = cartesian.getAxis(axisType);
                var bandWidth = axis.getBandWidth();
                var span = otherExtent[1] - otherExtent[0];
                var targetShape = axisType === 'x'
                    ? makeRectShape(point[0] - bandWidth / 2, otherExtent[0], bandWidth, span)
                    : makeRectShape(otherExtent[0], point[1] - bandWidth / 2, span, bandWidth);

                var pointerEl = self._getPointerElement(
                    cartesian, axisPointerModel, axisType, targetShape
                );
                moveAnimation
                    ? graphic.updateProps(pointerEl, {
                        shape: targetShape
                    }, axisPointerModel)
                    :  pointerEl.attr({
                        shape: targetShape
                    });
            }
        },

1
100pah 已提交
759
        _showSinglePointer: function (axisPointerModel, single, axisType, point, enableAnimation) {
D
deqingli 已提交
760 761
            var self = this;
            var axisPointerType = axisPointerModel.get('type');
1
100pah 已提交
762 763 764 765
            var moveAnimation =
                enableAnimation
                && axisPointerType !== 'cross'
                && single.getBaseAxis().type === 'category';
D
deqingli 已提交
766 767 768 769
            var rect = single.getRect();
            var otherExtent = [rect.y, rect.y + rect.height];

            moveSingleLine(axisType, point, otherExtent);
L
Typo  
lang 已提交
770

D
deqingli 已提交
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
            /**
             * @inner
             */
            function moveSingleLine(axisType, point, otherExtent) {
                var axis = single.getAxis();
                var orient = axis.orient;

                var targetShape = orient === 'horizontal'
                    ? makeLineShape(point[0], otherExtent[0], point[0], otherExtent[1])
                    : makeLineShape(otherExtent[0], point[1], otherExtent[1], point[1]);

                var pointerEl = self._getPointerElement(
                    single, axisPointerModel, axisType, targetShape
                );
                moveAnimation
                    ? graphic.updateProps(pointerEl, {
                        shape: targetShape
                    }, axisPointerModel)
                    :  pointerEl.attr({
                        shape: targetShape
                    });
            }
L
Typo  
lang 已提交
793

D
deqingli 已提交
794 795
        },

L
lang 已提交
796 797 798 799 800 801 802
        /**
         * Show tooltip on axis of polar coordinate
         * @param {module:echarts/model/Model} axisPointerModel
         * @param {Array.<module:echarts/coord/polar/Polar>} polar
         * @param {string} axisType
         * @param {Array.<number>} point
         */
1
100pah 已提交
803
        _showPolarPointer: function (axisPointerModel, polar, axisType, point, enableAnimation) {
L
lang 已提交
804 805 806 807 808 809 810
            var self = this;

            var axisPointerType = axisPointerModel.get('type');

            var angleAxis = polar.getAngleAxis();
            var radiusAxis = polar.getRadiusAxis();

1
100pah 已提交
811 812
            var moveAnimation = enableAnimation
                && axisPointerType !== 'cross'
813
                && polar.getBaseAxis().type === 'category';
L
lang 已提交
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

            if (axisPointerType === 'cross') {
                movePolarLine('angle', point, radiusAxis.getExtent());
                movePolarLine('radius', point, angleAxis.getExtent());

                this._updateCrossText(polar, point, axisPointerModel);
            }
            else {
                var otherAxis = polar.getAxis(axisType === 'radius' ? 'angle' : 'radius');
                var otherExtent = otherAxis.getExtent();

                (axisPointerType === 'line' ? movePolarLine : movePolarShadow)(
                    axisType, point, otherExtent
                );
            }
            /**
             * @inner
             */
            function movePolarLine(axisType, point, otherExtent) {
                var mouseCoord = polar.pointToCoord(point);

                var targetShape;

                if (axisType === 'angle') {
                    var p1 = polar.coordToPoint([otherExtent[0], mouseCoord[1]]);
                    var p2 = polar.coordToPoint([otherExtent[1], mouseCoord[1]]);
                    targetShape = makeLineShape(p1[0], p1[1], p2[0], p2[1]);
                }
                else {
                    targetShape = {
                        cx: polar.cx,
                        cy: polar.cy,
                        r: mouseCoord[0]
                    };
                }

                var pointerEl = self._getPointerElement(
                    polar, axisPointerModel, axisType, targetShape
                );

                moveAnimation
                    ? graphic.updateProps(pointerEl, {
                        shape: targetShape
                    }, axisPointerModel)
                    :  pointerEl.attr({
                        shape: targetShape
                    });
            }

            /**
             * @inner
             */
            function movePolarShadow(axisType, point, otherExtent) {
                var axis = polar.getAxis(axisType);
                var bandWidth = axis.getBandWidth();

                var mouseCoord = polar.pointToCoord(point);

                var targetShape;

                var radian = Math.PI / 180;

                if (axisType === 'angle') {
                    targetShape = makeSectorShape(
                        polar.cx, polar.cy,
                        otherExtent[0], otherExtent[1],
                        // In ECharts y is negative if angle is positive
                        (-mouseCoord[1] - bandWidth / 2) * radian,
                        (-mouseCoord[1] + bandWidth / 2) * radian
                    );
                }
                else {
                    targetShape = makeSectorShape(
                        polar.cx, polar.cy,
                        mouseCoord[0] - bandWidth / 2,
                        mouseCoord[0] + bandWidth / 2,
                        0, Math.PI * 2
                    );
                }

                var pointerEl = self._getPointerElement(
                    polar, axisPointerModel, axisType, targetShape
                );
                moveAnimation
                    ? graphic.updateProps(pointerEl, {
                        shape: targetShape
                    }, axisPointerModel)
                    :  pointerEl.attr({
                        shape: targetShape
                    });
            }
        },

        _updateCrossText: function (coordSys, point, axisPointerModel) {
            var crossStyleModel = axisPointerModel.getModel('crossStyle');
            var textStyleModel = crossStyleModel.getModel('textStyle');

            var tooltipModel = this._tooltipModel;

            var text = this._crossText;
            if (!text) {
                text = this._crossText = new graphic.Text({
                    style: {
                        textAlign: 'left',
L
lang 已提交
918
                        textVerticalAlign: 'bottom'
L
lang 已提交
919 920 921 922 923 924 925 926 927 928
                    }
                });
                this.group.add(text);
            }

            var value = coordSys.pointToData(point);

            var dims = coordSys.dimensions;
            value = zrUtil.map(value, function (val, idx) {
                var axis = coordSys.getAxis(dims[idx]);
929
                if (axis.type === 'category' || axis.type === 'time') {
L
lang 已提交
930 931 932 933
                    val = axis.scale.getLabel(val);
                }
                else {
                    val = formatUtil.addCommas(
934
                        val.toFixed(axis.getPixelPrecision())
L
lang 已提交
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
                    );
                }
                return val;
            });

            text.setStyle({
                fill: textStyleModel.getTextColor() || crossStyleModel.get('color'),
                textFont: textStyleModel.getFont(),
                text: value.join(', '),
                x: point[0] + 5,
                y: point[1] - 5
            });
            text.z = tooltipModel.get('z');
            text.zlevel = tooltipModel.get('zlevel');
        },

        _getPointerElement: function (coordSys, pointerModel, axisType, initShape) {
            var tooltipModel = this._tooltipModel;
            var z = tooltipModel.get('z');
            var zlevel = tooltipModel.get('zlevel');
            var axisPointers = this._axisPointers;
            var coordSysName = coordSys.name;
            axisPointers[coordSysName] = axisPointers[coordSysName] || {};
            if (axisPointers[coordSysName][axisType]) {
                return axisPointers[coordSysName][axisType];
            }

            // Create if not exists
            var pointerType = pointerModel.get('type');
            var styleModel = pointerModel.getModel(pointerType + 'Style');
            var isShadow = pointerType === 'shadow';
            var style = styleModel[isShadow ? 'getAreaStyle' : 'getLineStyle']();

            var elementType = coordSys.type === 'polar'
                ? (isShadow ? 'Sector' : (axisType === 'radius' ? 'Circle' : 'Line'))
                : (isShadow ? 'Rect' : 'Line');

P
pah100 已提交
972
            isShadow ? (style.stroke = null) : (style.fill = null);
L
lang 已提交
973 974 975 976 977 978 979 980 981 982 983 984 985 986

            var el = axisPointers[coordSysName][axisType] = new graphic[elementType]({
                style: style,
                z: z,
                zlevel: zlevel,
                silent: true,
                shape: initShape
            });

            this.group.add(el);
            return el;
        },

        /**
987
         * Dispatch actions and show tooltip on series
L
lang 已提交
988 989 990 991
         * @param {Array.<module:echarts/model/Series>} seriesList
         * @param {Array.<number>} point
         * @param {Array.<number>} value
         * @param {boolean} contentNotChange
992
         * @param {Array.<number>|string|Function} [positionExpr]
L
lang 已提交
993
         */
994
        _dispatchAndShowSeriesTooltipContent: function (
995
            coordSys, seriesList, point, value, contentNotChange, positionExpr
L
lang 已提交
996 997 998 999 1000
        ) {

            var rootTooltipModel = this._tooltipModel;

            var baseAxis = coordSys.getBaseAxis();
1001
            var baseDimIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
L
lang 已提交
1002

1003 1004 1005 1006
            if (!seriesList.length) {
                return;
            }

L
lang 已提交
1007 1008 1009
            var payloadBatch = zrUtil.map(seriesList, function (series) {
                return {
                    seriesIndex: series.seriesIndex,
1010
                    dataIndexInside: series.getAxisTooltipDataIndex
1011
                        ? series.getAxisTooltipDataIndex(series.coordDimToDataDim(baseAxis.dim), value, baseAxis)
D
deqingli 已提交
1012
                        : series.getData().indexOfNearest(
1013
                            series.coordDimToDataDim(baseAxis.dim)[0],
1014
                            value[baseDimIndex],
1015 1016
                            // Add a threshold to avoid find the wrong dataIndex when data length is not same
                            false, baseAxis.type === 'category' ? 0.5 : null
D
deqingli 已提交
1017
                        )
L
lang 已提交
1018 1019
                };
            });
1020
            var sampleSeriesIndex;
1
100pah 已提交
1021
            zrUtil.each(payloadBatch, function (payload, idx) {
1022 1023 1024 1025 1026 1027
                if (seriesList[idx].getData().hasValue(payload.dataIndexInside)) {
                    sampleSeriesIndex = idx;
                }
            });
            // Fallback to 0.
            sampleSeriesIndex = sampleSeriesIndex || 0;
L
lang 已提交
1028 1029

            var lastHover = this._lastHover;
1030 1031
            var api = this._api;
            // Dispatch downplay action
L
lang 已提交
1032
            if (lastHover.payloadBatch && !contentNotChange) {
1033
                api.dispatchAction({
L
lang 已提交
1034
                    type: 'downplay',
1035
                    batch: lastHover.payloadBatch
L
lang 已提交
1036 1037 1038 1039
                });
            }
            // Dispatch highlight action
            if (!contentNotChange) {
1040
                api.dispatchAction({
L
lang 已提交
1041
                    type: 'highlight',
1042
                    batch: payloadBatch
L
lang 已提交
1043 1044 1045
                });
                lastHover.payloadBatch = payloadBatch;
            }
1046
            // Dispatch showTip action
1047
            var dataIndex = payloadBatch[sampleSeriesIndex].dataIndexInside;
L
tweak  
lang 已提交
1048 1049
            api.dispatchAction({
                type: 'showTip',
1050 1051 1052
                dataIndexInside: dataIndex,
                // expose to user.
                dataIndex: seriesList[sampleSeriesIndex].getData().getRawIndex(dataIndex),
1053
                seriesIndex: payloadBatch[sampleSeriesIndex].seriesIndex,
L
tweak  
lang 已提交
1054 1055
                from: this.uid
            });
L
lang 已提交
1056

P
pah100 已提交
1057
            if (baseAxis && rootTooltipModel.get('showContent') && rootTooltipModel.get('show')) {
L
lang 已提交
1058
                var paramsList = zrUtil.map(seriesList, function (series, index) {
1059
                    return series.getDataParams(payloadBatch[index].dataIndexInside);
L
lang 已提交
1060 1061 1062
                });

                if (!contentNotChange) {
L
lang 已提交
1063
                    // Update html content
1064
                    var firstDataIndex = payloadBatch[sampleSeriesIndex].dataIndexInside;
L
lang 已提交
1065

L
lang 已提交
1066 1067 1068 1069 1070 1071
                    // 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 = baseAxis.type === 'time'
                        ? baseAxis.scale.getLabel(value[baseDimIndex])
1072
                        : seriesList[sampleSeriesIndex].getData().getName(firstDataIndex);
L
lang 已提交
1073 1074
                    var defaultHtml = (firstLine ? firstLine + '<br />' : '')
                        + zrUtil.map(seriesList, function (series, index) {
1075
                            return series.formatTooltip(payloadBatch[index].dataIndexInside, true);
L
lang 已提交
1076 1077 1078 1079 1080 1081
                        }).join('<br />');

                    var asyncTicket = 'axis_' + coordSys.name + '_' + firstDataIndex;

                    this._showTooltipContent(
                        rootTooltipModel, defaultHtml, paramsList, asyncTicket,
1082
                        point[0], point[1], positionExpr, null, api
L
lang 已提交
1083 1084 1085 1086
                    );
                }
                else {
                    updatePosition(
1
100pah 已提交
1087 1088 1089
                        positionExpr || rootTooltipModel.get('position'),
                        point[0], point[1],
                        rootTooltipModel.get('confine'),
L
lang 已提交
1090 1091
                        this._tooltipContent, paramsList, null, api
                    );
L
lang 已提交
1092 1093 1094 1095 1096 1097 1098 1099
                }
            }
        },

        /**
         * Show tooltip on item
         * @param {module:echarts/model/Series} seriesModel
         * @param {number} dataIndex
1100
         * @param {string} dataType
L
lang 已提交
1101 1102
         * @param {Object} e
         */
1103
        _showItemTooltipContent: function (seriesModel, dataIndex, dataType, e) {
L
lang 已提交
1104 1105
            // FIXME Graph data
            var api = this._api;
1106
            var data = seriesModel.getData(dataType);
L
lang 已提交
1107 1108
            var itemModel = data.getItemModel(dataIndex);

1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
            var tooltipOpt = itemModel.get('tooltip', true);
            if (typeof tooltipOpt === 'string') {
                // In each data item tooltip can be simply write:
                // {
                //  value: 10,
                //  tooltip: 'Something you need to know'
                // }
                var tooltipContent = tooltipOpt;
                tooltipOpt = {
                    formatter: tooltipContent
                };
L
lang 已提交
1120
            }
1121 1122 1123 1124 1125
            var rootTooltipModel = this._tooltipModel;
            var seriesTooltipModel = seriesModel.getModel(
                'tooltip', rootTooltipModel
            );
            var tooltipModel = new Model(tooltipOpt, seriesTooltipModel, seriesTooltipModel.ecModel);
L
lang 已提交
1126

L
lang 已提交
1127 1128 1129 1130 1131 1132 1133
            var params = seriesModel.getDataParams(dataIndex, dataType);
            var defaultHtml = seriesModel.formatTooltip(dataIndex, false, dataType);

            var asyncTicket = 'item_' + seriesModel.name + '_' + dataIndex;

            this._showTooltipContent(
                tooltipModel, defaultHtml, params, asyncTicket,
1134
                e.offsetX, e.offsetY, e.position, e.target, api
L
lang 已提交
1135 1136 1137 1138
            );
        },

        _showTooltipContent: function (
1139
            tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, target, api
L
lang 已提交
1140 1141 1142 1143
        ) {
            // Reset ticket
            this._ticket = '';

P
pah100 已提交
1144
            if (tooltipModel.get('showContent') && tooltipModel.get('show')) {
L
lang 已提交
1145
                var tooltipContent = this._tooltipContent;
1
100pah 已提交
1146
                var confine = tooltipModel.get('confine');
L
lang 已提交
1147

L
lang 已提交
1148
                var formatter = tooltipModel.get('formatter');
1149
                positionExpr = positionExpr || tooltipModel.get('position');
L
lang 已提交
1150 1151 1152
                var html = defaultHtml;

                if (formatter) {
L
lang 已提交
1153 1154 1155 1156 1157
                    if (typeof formatter === 'string') {
                        html = formatUtil.formatTpl(formatter, params);
                    }
                    else if (typeof formatter === 'function') {
                        var self = this;
L
lang 已提交
1158
                        var ticket = asyncTicket;
L
lang 已提交
1159 1160 1161 1162 1163
                        var callback = function (cbTicket, html) {
                            if (cbTicket === self._ticket) {
                                tooltipContent.setContent(html);

                                updatePosition(
1
100pah 已提交
1164
                                    positionExpr, x, y, confine,
L
lang 已提交
1165
                                    tooltipContent, params, target, api
L
lang 已提交
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
                                );
                            }
                        };
                        self._ticket = ticket;
                        html = formatter(params, ticket, callback);
                    }
                }

                tooltipContent.show(tooltipModel);
                tooltipContent.setContent(html);

                updatePosition(
1
100pah 已提交
1178
                    positionExpr, x, y, confine,
L
lang 已提交
1179
                    tooltipContent, params, target, api
L
lang 已提交
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
                );
            }
        },

        /**
         * Show axis pointer
         * @param {string} [coordSysName]
         */
        _showAxisPointer: function (coordSysName) {
            if (coordSysName) {
                var axisPointers = this._axisPointers[coordSysName];
                axisPointers && zrUtil.each(axisPointers, function (el) {
                    el.show();
                });
            }
            else {
                this.group.eachChild(function (child) {
                    child.show();
                });
                this.group.show();
            }
        },

        _resetLastHover: function () {
            var lastHover = this._lastHover;
            if (lastHover.payloadBatch) {
                this._api.dispatchAction({
                    type: 'downplay',
                    batch: lastHover.payloadBatch
                });
            }
            // Reset lastHover
            this._lastHover = {};
        },
        /**
         * Hide axis pointer
         * @param {string} [coordSysName]
         */
        _hideAxisPointer: function (coordSysName) {
            if (coordSysName) {
                var axisPointers = this._axisPointers[coordSysName];
                axisPointers && zrUtil.each(axisPointers, function (el) {
                    el.hide();
                });
            }
            else {
P
pah100 已提交
1226 1227 1228
                if (this.group.children().length) {
                    this.group.hide();
                }
L
lang 已提交
1229 1230 1231 1232
            }
        },

        _hide: function () {
L
lang 已提交
1233 1234
            clearTimeout(this._showTimeout);

L
lang 已提交
1235 1236 1237 1238 1239
            this._hideAxisPointer();
            this._resetLastHover();
            if (!this._alwaysShowContent) {
                this._tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
            }
1240 1241 1242 1243 1244

            this._api.dispatchAction({
                type: 'hideTip',
                from: this.uid
            });
L
lang 已提交
1245 1246

            this._lastX = this._lastY = null;
L
lang 已提交
1247 1248
        },

L
lang 已提交
1249
        dispose: function (ecModel, api) {
L
tweak  
lang 已提交
1250 1251 1252
            if (env.node) {
                return;
            }
L
lang 已提交
1253
            var zr = api.getZr();
1254
            this._tooltipContent.hide();
L
lang 已提交
1255

L
lang 已提交
1256
            zr.off('click', this._tryShow);
L
lang 已提交
1257
            zr.off('mousemove', this._mousemove);
L
lang 已提交
1258
            zr.off('mouseout', this._hide);
L
lang 已提交
1259
            zr.off('globalout', this._hide);
L
lang 已提交
1260

1261
            api.off('showTip', this._manuallyShowTip);
1262
            api.off('hideTip', this._manuallyHideTip);
L
lang 已提交
1263 1264 1265
        }
    });
});