BrushController.js 30.3 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 {__DEV__} from '../../config';
S
sushuang 已提交
21 22
import * as zrUtil from 'zrender/src/core/util';
import Eventful from 'zrender/src/mixin/Eventful';
S
sushuang 已提交
23 24 25
import * as graphic from '../../util/graphic';
import * as interactionMutex from './interactionMutex';
import DataDiffer from '../../data/DataDiffer';
S
sushuang 已提交
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

var curry = zrUtil.curry;
var each = zrUtil.each;
var map = zrUtil.map;
var mathMin = Math.min;
var mathMax = Math.max;
var mathPow = Math.pow;

var COVER_Z = 10000;
var UNSELECT_THRESHOLD = 6;
var MIN_RESIZE_LINE_WIDTH = 6;
var MUTEX_RESOURCE_KEY = 'globalPan';

var DIRECTION_MAP = {
    w: [0, 0],
    e: [0, 1],
    n: [1, 0],
    s: [1, 1]
};
var CURSOR_MAP = {
    w: 'ew',
    e: 'ew',
    n: 'ns',
    s: 'ns',
    ne: 'nesw',
    sw: 'nesw',
    nw: 'nwse',
    se: 'nwse'
};
var DEFAULT_BRUSH_OPT = {
    brushStyle: {
        lineWidth: 2,
        stroke: 'rgba(0,0,0,0.3)',
        fill: 'rgba(0,0,0,0.1)'
    },
    transformable: true,
    brushMode: 'single',
    removeOnClick: false
};

var baseUID = 0;
P
pah100 已提交
67

S
sushuang 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
/**
 * @alias module:echarts/component/helper/BrushController
 * @constructor
 * @mixin {module:zrender/mixin/Eventful}
 * @event module:echarts/component/helper/BrushController#brush
 *        params:
 *            areas: Array.<Array>, coord relates to container group,
 *                                    If no container specified, to global.
 *            opt {
 *                isEnd: boolean,
 *                removeOnClick: boolean
 *            }
 *
 * @param {module:zrender/zrender~ZRender} zr
 */
function BrushController(zr) {
P
pah100 已提交
84

S
sushuang 已提交
85 86
    if (__DEV__) {
        zrUtil.assert(zr);
P
pah100 已提交
87 88
    }

S
sushuang 已提交
89
    Eventful.call(this);
P
pah100 已提交
90

S
sushuang 已提交
91 92 93 94 95
    /**
     * @type {module:zrender/zrender~ZRender}
     * @private
     */
    this._zr = zr;
P
pah100 已提交
96

S
sushuang 已提交
97 98 99 100 101
    /**
     * @type {module:zrender/container/Group}
     * @readOnly
     */
    this.group = new graphic.Group();
P
pah100 已提交
102

S
sushuang 已提交
103 104 105 106 107 108 109 110 111
    /**
     * Only for drawing (after enabledBrush).
     *     'line', 'rect', 'polygon' or false
     *     If passing false/null/undefined, disable brush.
     *     If passing 'auto', determined by panel.defaultBrushType
     * @private
     * @type {string}
     */
    this._brushType;
P
pah100 已提交
112

S
sushuang 已提交
113 114 115 116 117 118 119
    /**
     * Only for drawing (after enabledBrush).
     *
     * @private
     * @type {Object}
     */
    this._brushOption;
P
pah100 已提交
120

S
sushuang 已提交
121 122 123 124 125
    /**
     * @private
     * @type {Object}
     */
    this._panels;
P
pah100 已提交
126

S
sushuang 已提交
127 128 129 130 131
    /**
     * @private
     * @type {Array.<nubmer>}
     */
    this._track = [];
P
pah100 已提交
132

S
sushuang 已提交
133 134 135 136 137
    /**
     * @private
     * @type {boolean}
     */
    this._dragging;
P
pah100 已提交
138

139 140 141 142 143 144
    /**
     * @private
     * @type {Object}
     */
    this._lastMouseMovePoint = {};

S
sushuang 已提交
145 146 147 148 149
    /**
     * @private
     * @type {Array}
     */
    this._covers = [];
P
pah100 已提交
150

S
sushuang 已提交
151 152 153 154 155
    /**
     * @private
     * @type {moudule:zrender/container/Group}
     */
    this._creatingCover;
P
pah100 已提交
156

S
sushuang 已提交
157 158 159 160 161 162
    /**
     * `true` means global panel
     * @private
     * @type {module:zrender/container/Group|boolean}
     */
    this._creatingPanel;
P
pah100 已提交
163

S
sushuang 已提交
164 165 166 167 168
    /**
     * @private
     * @type {boolean}
     */
    this._enableGlobalPan;
P
pah100 已提交
169

S
sushuang 已提交
170 171 172 173 174 175 176
    /**
     * @private
     * @type {boolean}
     */
    if (__DEV__) {
        this._mounted;
    }
177

S
sushuang 已提交
178 179 180 181 182
    /**
     * @private
     * @type {string}
     */
    this._uid = 'brushController_' + baseUID++;
P
pah100 已提交
183

S
sushuang 已提交
184 185 186 187 188 189 190 191 192
    /**
     * @private
     * @type {Object}
     */
    this._handlers = {};
    each(mouseHandlers, function (handler, eventName) {
        this._handlers[eventName] = zrUtil.bind(handler, this);
    }, this);
}
P
pah100 已提交
193

S
sushuang 已提交
194
BrushController.prototype = {
P
pah100 已提交
195

S
sushuang 已提交
196
    constructor: BrushController,
P
pah100 已提交
197

S
sushuang 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    /**
     * If set to null/undefined/false, select disabled.
     * @param {Object} brushOption
     * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
     *                          If passing false/null/undefined, disable brush.
     *                          If passing 'auto', determined by panel.defaultBrushType.
     *                              ('auto' can not be used in global panel)
     * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
     * @param {boolean} [brushOption.transformable=true]
     * @param {boolean} [brushOption.removeOnClick=false]
     * @param {Object} [brushOption.brushStyle]
     * @param {number} [brushOption.brushStyle.width]
     * @param {number} [brushOption.brushStyle.lineWidth]
     * @param {string} [brushOption.brushStyle.stroke]
     * @param {string} [brushOption.brushStyle.fill]
     * @param {number} [brushOption.z]
     */
    enableBrush: function (brushOption) {
        if (__DEV__) {
            zrUtil.assert(this._mounted);
P
pah100 已提交
218 219
        }

S
sushuang 已提交
220 221
        this._brushType && doDisableBrush(this);
        brushOption.brushType && doEnableBrush(this, brushOption);
P
pah100 已提交
222

S
sushuang 已提交
223 224
        return this;
    },
P
pah100 已提交
225

S
sushuang 已提交
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
    /**
     * @param {Array.<Object>} panelOpts If not pass, it is global brush.
     *        Each items: {
     *            panelId, // mandatory.
     *            clipPath, // mandatory. function.
     *            isTargetByCursor, // mandatory. function.
     *            defaultBrushType, // optional, only used when brushType is 'auto'.
     *            getLinearBrushOtherExtent, // optional. function.
     *        }
     */
    setPanels: function (panelOpts) {
        if (panelOpts && panelOpts.length) {
            var panels = this._panels = {};
            zrUtil.each(panelOpts, function (panelOpts) {
                panels[panelOpts.panelId] = zrUtil.clone(panelOpts);
            });
        }
        else {
            this._panels = null;
245
        }
S
sushuang 已提交
246 247
        return this;
    },
P
pah100 已提交
248

S
sushuang 已提交
249 250 251 252 253 254
    /**
     * @param {Object} [opt]
     * @return {boolean} [opt.enableGlobalPan=false]
     */
    mount: function (opt) {
        opt = opt || {};
P
pah100 已提交
255

S
sushuang 已提交
256 257 258
        if (__DEV__) {
            this._mounted = true; // should be at first.
        }
P
pah100 已提交
259

S
sushuang 已提交
260
        this._enableGlobalPan = opt.enableGlobalPan;
P
pah100 已提交
261

S
sushuang 已提交
262 263
        var thisGroup = this.group;
        this._zr.add(thisGroup);
P
pah100 已提交
264

S
sushuang 已提交
265 266 267 268
        thisGroup.attr({
            position: opt.position || [0, 0],
            rotation: opt.rotation || 0,
            scale: opt.scale || [1, 1]
P
pah100 已提交
269
        });
S
sushuang 已提交
270
        this._transform = thisGroup.getLocalTransform();
P
pah100 已提交
271

S
sushuang 已提交
272 273
        return this;
    },
P
pah100 已提交
274

S
sushuang 已提交
275 276 277
    eachCover: function (cb, context) {
        each(this._covers, cb, context);
    },
P
pah100 已提交
278

S
sushuang 已提交
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
    /**
     * Update covers.
     * @param {Array.<Object>} brushOptionList Like:
     *        [
     *            {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
     *            {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
     *            ...
     *        ]
     *        `brushType` is required in each cover info. (can not be 'auto')
     *        `id` is not mandatory.
     *        `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
     *        If brushOptionList is null/undefined, all covers removed.
     */
    updateCovers: function (brushOptionList) {
        if (__DEV__) {
            zrUtil.assert(this._mounted);
P
pah100 已提交
295 296
        }

S
sushuang 已提交
297 298
        brushOptionList = zrUtil.map(brushOptionList, function (brushOption) {
            return zrUtil.merge(zrUtil.clone(DEFAULT_BRUSH_OPT), brushOption, true);
P
pah100 已提交
299 300
        });

S
sushuang 已提交
301 302 303 304 305
        var tmpIdPrefix = '\0-brush-index-';
        var oldCovers = this._covers;
        var newCovers = this._covers = [];
        var controller = this;
        var creatingCover = this._creatingCover;
P
pah100 已提交
306

S
sushuang 已提交
307 308 309 310 311
        (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
            .add(addOrUpdate)
            .update(addOrUpdate)
            .remove(remove)
            .execute();
P
pah100 已提交
312

S
sushuang 已提交
313
        return this;
P
pah100 已提交
314

S
sushuang 已提交
315 316 317
        function getKey(brushOption, index) {
            return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
                + '-' + brushOption.brushType;
P
pah100 已提交
318 319
        }

S
sushuang 已提交
320 321
        function oldGetKey(cover, index) {
            return getKey(cover.__brushOption, index);
P
pah100 已提交
322 323
        }

S
sushuang 已提交
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
        function addOrUpdate(newIndex, oldIndex) {
            var newBrushOption = brushOptionList[newIndex];
            // Consider setOption in event listener of brushSelect,
            // where updating cover when creating should be forbiden.
            if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
                newCovers[newIndex] = oldCovers[oldIndex];
            }
            else {
                var cover = newCovers[newIndex] = oldIndex != null
                    ? (
                        oldCovers[oldIndex].__brushOption = newBrushOption,
                        oldCovers[oldIndex]
                    )
                    : endCreating(controller, createCover(controller, newBrushOption));
                updateCoverAfterCreation(controller, cover);
P
pah100 已提交
339 340 341
            }
        }

S
sushuang 已提交
342 343 344
        function remove(oldIndex) {
            if (oldCovers[oldIndex] !== creatingCover) {
                controller.group.remove(oldCovers[oldIndex]);
P
pah100 已提交
345
            }
S
sushuang 已提交
346 347
        }
    },
P
pah100 已提交
348

S
sushuang 已提交
349 350 351 352 353 354
    unmount: function () {
        if (__DEV__) {
            if (!this._mounted) {
                return;
            }
        }
P
pah100 已提交
355

S
sushuang 已提交
356
        this.enableBrush(false);
P
pah100 已提交
357

S
sushuang 已提交
358 359 360
        // container may 'removeAll' outside.
        clearCovers(this);
        this._zr.remove(this.group);
P
pah100 已提交
361

S
sushuang 已提交
362 363
        if (__DEV__) {
            this._mounted = false; // should be at last.
P
pah100 已提交
364 365
        }

S
sushuang 已提交
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
        return this;
    },

    dispose: function () {
        this.unmount();
        this.off();
    }
};

zrUtil.mixin(BrushController, Eventful);

function doEnableBrush(controller, brushOption) {
    var zr = controller._zr;

    // Consider roam, which takes globalPan too.
    if (!controller._enableGlobalPan) {
        interactionMutex.take(zr, MUTEX_RESOURCE_KEY, controller._uid);
    }

    each(controller._handlers, function (handler, eventName) {
        zr.on(eventName, handler);
    });

    controller._brushType = brushOption.brushType;
    controller._brushOption = zrUtil.merge(zrUtil.clone(DEFAULT_BRUSH_OPT), brushOption, true);
}

function doDisableBrush(controller) {
    var zr = controller._zr;

    interactionMutex.release(zr, MUTEX_RESOURCE_KEY, controller._uid);

    each(controller._handlers, function (handler, eventName) {
        zr.off(eventName, handler);
    });

    controller._brushType = controller._brushOption = null;
}

function createCover(controller, brushOption) {
    var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
    cover.__brushOption = brushOption;
    updateZ(cover, brushOption);
    controller.group.add(cover);
    return cover;
}

function endCreating(controller, creatingCover) {
    var coverRenderer = getCoverRenderer(creatingCover);
    if (coverRenderer.endCreating) {
        coverRenderer.endCreating(controller, creatingCover);
        updateZ(creatingCover, creatingCover.__brushOption);
    }
    return creatingCover;
}

function updateCoverShape(controller, cover) {
    var brushOption = cover.__brushOption;
    getCoverRenderer(cover).updateCoverShape(
        controller, cover, brushOption.range, brushOption
    );
}

function updateZ(cover, brushOption) {
    var z = brushOption.z;
    z == null && (z = COVER_Z);
    cover.traverse(function (el) {
        el.z = z;
        el.z2 = z; // Consider in given container.
    });
}

function updateCoverAfterCreation(controller, cover) {
    getCoverRenderer(cover).updateCommon(controller, cover);
    updateCoverShape(controller, cover);
}

function getCoverRenderer(cover) {
    return coverRenderers[cover.__brushOption.brushType];
}

// return target panel or `true` (means global panel)
function getPanelByPoint(controller, e, localCursorPoint) {
    var panels = controller._panels;
    if (!panels) {
        return true; // Global panel
    }
    var panel;
    var transform = controller._transform;
    each(panels, function (pn) {
        pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
    });
    return panel;
}

// Return a panel or true
function getPanelByCover(controller, cover) {
    var panels = controller._panels;
    if (!panels) {
        return true; // Global panel
    }
    var panelId = cover.__brushOption.panelId;
    // User may give cover without coord sys info,
    // which is then treated as global panel.
    return panelId != null ? panels[panelId] : true;
}

function clearCovers(controller) {
    var covers = controller._covers;
    var originalLength = covers.length;
    each(covers, function (cover) {
        controller.group.remove(cover);
    }, controller);
    covers.length = 0;

    return !!originalLength;
}

function trigger(controller, opt) {
    var areas = map(controller._covers, function (cover) {
P
pah100 已提交
486
        var brushOption = cover.__brushOption;
S
sushuang 已提交
487
        var range = zrUtil.clone(brushOption.range);
P
pah100 已提交
488
        return {
S
sushuang 已提交
489 490 491
            brushType: brushOption.brushType,
            panelId: brushOption.panelId,
            range: range
P
pah100 已提交
492
        };
S
sushuang 已提交
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 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
    });

    controller.trigger('brush', areas, {
        isEnd: !!opt.isEnd,
        removeOnClick: !!opt.removeOnClick
    });
}

function shouldShowCover(controller) {
    var track = controller._track;

    if (!track.length) {
        return false;
    }

    var p2 = track[track.length - 1];
    var p1 = track[0];
    var dx = p2[0] - p1[0];
    var dy = p2[1] - p1[1];
    var dist = mathPow(dx * dx + dy * dy, 0.5);

    return dist > UNSELECT_THRESHOLD;
}

function getTrackEnds(track) {
    var tail = track.length - 1;
    tail < 0 && (tail = 0);
    return [track[0], track[tail]];
}

function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
    var cover = new graphic.Group();

    cover.add(new graphic.Rect({
        name: 'main',
        style: makeStyle(brushOption),
        silent: true,
        draggable: true,
        cursor: 'move',
        drift: curry(doDrift, controller, cover, 'nswe'),
        ondragend: curry(trigger, controller, {isEnd: true})
    }));

    each(
        edgeNames,
        function (name) {
            cover.add(new graphic.Rect({
                name: name,
                style: {opacity: 0},
                draggable: true,
                silent: true,
                invisible: true,
                drift: curry(doDrift, controller, cover, name),
                ondragend: curry(trigger, controller, {isEnd: true})
            }));
548
        }
S
sushuang 已提交
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 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 633 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 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 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 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
    );

    return cover;
}

function updateBaseRect(controller, cover, localRange, brushOption) {
    var lineWidth = brushOption.brushStyle.lineWidth || 0;
    var handleSize = mathMax(lineWidth, MIN_RESIZE_LINE_WIDTH);
    var x = localRange[0][0];
    var y = localRange[1][0];
    var xa = x - lineWidth / 2;
    var ya = y - lineWidth / 2;
    var x2 = localRange[0][1];
    var y2 = localRange[1][1];
    var x2a = x2 - handleSize + lineWidth / 2;
    var y2a = y2 - handleSize + lineWidth / 2;
    var width = x2 - x;
    var height = y2 - y;
    var widtha = width + lineWidth;
    var heighta = height + lineWidth;

    updateRectShape(controller, cover, 'main', x, y, width, height);

    if (brushOption.transformable) {
        updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
        updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
        updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
        updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);

        updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
        updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
        updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
        updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
    }
}

function updateCommon(controller, cover) {
    var brushOption = cover.__brushOption;
    var transformable = brushOption.transformable;

    var mainEl = cover.childAt(0);
    mainEl.useStyle(makeStyle(brushOption));
    mainEl.attr({
        silent: !transformable,
        cursor: transformable ? 'move' : 'default'
    });

    each(
        ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
        function (name) {
            var el = cover.childOfName(name);
            var globalDir = getGlobalDirection(controller, name);

            el && el.attr({
                silent: !transformable,
                invisible: !transformable,
                cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
            });
        }
    );
}

function updateRectShape(controller, cover, name, x, y, w, h) {
    var el = cover.childOfName(name);
    el && el.setShape(pointsToRect(
        clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
    ));
}

function makeStyle(brushOption) {
    return zrUtil.defaults({strokeNoScale: true}, brushOption.brushStyle);
}

function formatRectRange(x, y, x2, y2) {
    var min = [mathMin(x, x2), mathMin(y, y2)];
    var max = [mathMax(x, x2), mathMax(y, y2)];

    return [
        [min[0], max[0]], // x range
        [min[1], max[1]] // y range
    ];
}

function getTransform(controller) {
    return graphic.getTransform(controller.group);
}

function getGlobalDirection(controller, localDirection) {
    if (localDirection.length > 1) {
        localDirection = localDirection.split('');
        var globalDir = [
            getGlobalDirection(controller, localDirection[0]),
            getGlobalDirection(controller, localDirection[1])
        ];
        (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
        return globalDir.join('');
    }
    else {
        var map = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
        var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
        var globalDir = graphic.transformDirection(
            map[localDirection], getTransform(controller)
        );
        return inverseMap[globalDir];
    }
}

function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
    var brushOption = cover.__brushOption;
    var rectRange = toRectRange(brushOption.range);
    var localDelta = toLocalDelta(controller, dx, dy);

    each(name.split(''), function (namePart) {
        var ind = DIRECTION_MAP[namePart];
        rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
    });

    brushOption.range = fromRectRange(formatRectRange(
        rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
    ));

    updateCoverAfterCreation(controller, cover);
    trigger(controller, {isEnd: false});
}

function driftPolygon(controller, cover, dx, dy, e) {
    var range = cover.__brushOption.range;
    var localDelta = toLocalDelta(controller, dx, dy);

    each(range, function (point) {
        point[0] += localDelta[0];
        point[1] += localDelta[1];
    });

    updateCoverAfterCreation(controller, cover);
    trigger(controller, {isEnd: false});
}

function toLocalDelta(controller, dx, dy) {
    var thisGroup = controller.group;
    var localD = thisGroup.transformCoordToLocal(dx, dy);
    var localZero = thisGroup.transformCoordToLocal(0, 0);

    return [localD[0] - localZero[0], localD[1] - localZero[1]];
}

function clipByPanel(controller, cover, data) {
    var panel = getPanelByCover(controller, cover);

    return (panel && panel !== true)
        ? panel.clipPath(data, controller._transform)
        : zrUtil.clone(data);
}

function pointsToRect(points) {
    var xmin = mathMin(points[0][0], points[1][0]);
    var ymin = mathMin(points[0][1], points[1][1]);
    var xmax = mathMax(points[0][0], points[1][0]);
    var ymax = mathMax(points[0][1], points[1][1]);

    return {
        x: xmin,
        y: ymin,
        width: xmax - xmin,
        height: ymax - ymin
    };
}

function resetCursor(controller, e, localCursorPoint) {
    // Check active
    if (!controller._brushType) {
        return;
    }

    var zr = controller._zr;
    var covers = controller._covers;
    var currPanel = getPanelByPoint(controller, e, localCursorPoint);

    // Check whether in covers.
    if (!controller._dragging) {
        for (var i = 0; i < covers.length; i++) {
            var brushOption = covers[i].__brushOption;
            if (currPanel
                && (currPanel === true || brushOption.panelId === currPanel.panelId)
                && coverRenderers[brushOption.brushType].contain(
                    covers[i], localCursorPoint[0], localCursorPoint[1]
                )
            ) {
                // Use cursor style set on cover.
                return;
P
pah100 已提交
739 740 741 742
            }
        }
    }

S
sushuang 已提交
743 744
    currPanel && zr.setCursorStyle('crosshair');
}
P
pah100 已提交
745

S
sushuang 已提交
746 747 748 749
function preventDefault(e) {
    var rawE = e.event;
    rawE.preventDefault && rawE.preventDefault();
}
P
pah100 已提交
750

S
sushuang 已提交
751 752 753
function mainShapeContain(cover, x, y) {
    return cover.childOfName('main').contain(x, y);
}
P
pah100 已提交
754

S
sushuang 已提交
755 756 757 758 759
function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
    var creatingCover = controller._creatingCover;
    var panel = controller._creatingPanel;
    var thisBrushOption = controller._brushOption;
    var eventParams;
P
pah100 已提交
760

S
sushuang 已提交
761
    controller._track.push(localCursorPoint.slice());
P
pah100 已提交
762

S
sushuang 已提交
763
    if (shouldShowCover(controller) || creatingCover) {
P
pah100 已提交
764

S
sushuang 已提交
765 766 767 768 769 770 771 772
        if (panel && !creatingCover) {
            thisBrushOption.brushMode === 'single' && clearCovers(controller);
            var brushOption = zrUtil.clone(thisBrushOption);
            brushOption.brushType = determineBrushType(brushOption.brushType, panel);
            brushOption.panelId = panel === true ? null : panel.panelId;
            creatingCover = controller._creatingCover = createCover(controller, brushOption);
            controller._covers.push(creatingCover);
        }
P
pah100 已提交
773

S
sushuang 已提交
774 775 776
        if (creatingCover) {
            var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
            var coverBrushOption = creatingCover.__brushOption;
P
pah100 已提交
777

S
sushuang 已提交
778 779 780
            coverBrushOption.range = coverRenderer.getCreatingRange(
                clipByPanel(controller, creatingCover, controller._track)
            );
P
pah100 已提交
781

S
sushuang 已提交
782 783 784
            if (isEnd) {
                endCreating(controller, creatingCover);
                coverRenderer.updateCommon(controller, creatingCover);
P
pah100 已提交
785
            }
S
sushuang 已提交
786 787 788 789

            updateCoverShape(controller, creatingCover);

            eventParams = {isEnd: isEnd};
P
pah100 已提交
790
        }
S
sushuang 已提交
791 792 793 794 795 796 797 798 799 800 801 802 803
    }
    else if (
        isEnd
        && thisBrushOption.brushMode === 'single'
        && thisBrushOption.removeOnClick
    ) {
        // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
        // But a single click do not clear covers, because user may have casual
        // clicks (for example, click on other component and do not expect covers
        // disappear).
        // Only some cover removed, trigger action, but not every click trigger action.
        if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
            eventParams = {isEnd: isEnd, removeOnClick: true};
P
pah100 已提交
804 805 806
        }
    }

S
sushuang 已提交
807 808 809 810 811 812 813 814 815 816
    return eventParams;
}

function determineBrushType(brushType, panel) {
    if (brushType === 'auto') {
        if (__DEV__) {
            zrUtil.assert(
                panel && panel.defaultBrushType,
                'MUST have defaultBrushType when brushType is "atuo"'
            );
817
        }
S
sushuang 已提交
818
        return panel.defaultBrushType;
819
    }
S
sushuang 已提交
820 821
    return brushType;
}
822

S
sushuang 已提交
823
var mouseHandlers = {
P
pah100 已提交
824

S
sushuang 已提交
825 826 827 828
    mousedown: function (e) {
        if (this._dragging) {
            // In case some browser do not support globalOut,
            // and release mose out side the browser.
829
            handleDragEnd(this, e);
S
sushuang 已提交
830 831
        }
        else if (!e.target || !e.target.draggable) {
P
pah100 已提交
832

S
sushuang 已提交
833
            preventDefault(e);
P
pah100 已提交
834

S
sushuang 已提交
835
            var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
P
pah100 已提交
836

S
sushuang 已提交
837 838
            this._creatingCover = null;
            var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
P
pah100 已提交
839

S
sushuang 已提交
840 841 842
            if (panel) {
                this._dragging = true;
                this._track = [localCursorPoint.slice()];
P
pah100 已提交
843
            }
S
sushuang 已提交
844 845
        }
    },
P
pah100 已提交
846

S
sushuang 已提交
847
    mousemove: function (e) {
848 849 850 851 852
        var lastPoint = this._lastMouseMovePoint;
        lastPoint.x = e.offsetX;
        lastPoint.y = e.offsetY;

        var localCursorPoint = this.group.transformCoordToLocal(lastPoint.x, lastPoint.y);
853

S
sushuang 已提交
854
        resetCursor(this, e, localCursorPoint);
P
pah100 已提交
855

S
sushuang 已提交
856
        if (this._dragging) {
P
pah100 已提交
857

S
sushuang 已提交
858
            preventDefault(e);
P
pah100 已提交
859

S
sushuang 已提交
860
            var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
P
tweak  
pah100 已提交
861

S
sushuang 已提交
862 863 864
            eventParams && trigger(this, eventParams);
        }
    },
P
pah100 已提交
865

866 867 868
    mouseup: function (e) {
        handleDragEnd(this, e);
    },
P
pah100 已提交
869

870 871 872
    globalout: function (e) {
        handleDragEnd(this, e, true);
    }
S
sushuang 已提交
873
};
P
pah100 已提交
874

875 876
function handleDragEnd(controller, e, isGlobalOut) {
    if (controller._dragging) {
P
pah100 已提交
877

878 879 880 881 882 883 884 885 886 887 888
        // Just be worried about bring some side effect to the world
        // out of echarts, we do not `preventDefault` for globalout.
        !isGlobalOut && preventDefault(e);

        var pointerX = e.offsetX;
        var pointerY = e.offsetY;
        var lastPoint = controller._lastMouseMovePoint;
        if (isGlobalOut) {
            pointerX = lastPoint.x;
            pointerY = lastPoint.y;
        }
P
pah100 已提交
889

890 891 892 893 894 895 896 897 898
        var localCursorPoint = controller.group.transformCoordToLocal(pointerX, pointerY);
        // FIXME
        // Here `e` is used only in `onIrrelevantElement` finally. And it's OK
        // that pass the `e` of `globalout` to `onIrrelevantElement`. But it is
        // not a good design of these interfaces. However, we do not refactor
        // these code now because the implementation of `onIrrelevantElement`
        // need to be discussed and probably be changed in future, becuase it
        // slows down the performance of zrender in some cases.
        var eventParams = updateCoverByMouse(controller, e, localCursorPoint, true);
P
pah100 已提交
899

900 901 902
        controller._dragging = false;
        controller._track = [];
        controller._creatingCover = null;
P
tweak  
pah100 已提交
903

S
sushuang 已提交
904
        // trigger event shoule be at final, after procedure will be nested.
905
        eventParams && trigger(controller, eventParams);
P
pah100 已提交
906
    }
S
sushuang 已提交
907
}
P
pah100 已提交
908

S
sushuang 已提交
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
/**
 * key: brushType
 * @type {Object}
 */
var coverRenderers = {

    lineX: getLineRenderer(0),

    lineY: getLineRenderer(1),

    rect: {
        createCover: function (controller, brushOption) {
            return createBaseRectCover(
                curry(
                    driftRect,
                    function (range) {
                        return range;
                    },
                    function (range) {
                        return range;
                    }
                ),
                controller,
                brushOption,
                ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
            );
P
pah100 已提交
935
        },
S
sushuang 已提交
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 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
        getCreatingRange: function (localTrack) {
            var ends = getTrackEnds(localTrack);
            return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
        },
        updateCoverShape: function (controller, cover, localRange, brushOption) {
            updateBaseRect(controller, cover, localRange, brushOption);
        },
        updateCommon: updateCommon,
        contain: mainShapeContain
    },

    polygon: {
        createCover: function (controller, brushOption) {
            var cover = new graphic.Group();

            // Do not use graphic.Polygon because graphic.Polyline do not close the
            // border of the shape when drawing, which is a better experience for user.
            cover.add(new graphic.Polyline({
                name: 'main',
                style: makeStyle(brushOption),
                silent: true
            }));

            return cover;
        },
        getCreatingRange: function (localTrack) {
            return localTrack;
        },
        endCreating: function (controller, cover) {
            cover.remove(cover.childAt(0));
            // Use graphic.Polygon close the shape.
            cover.add(new graphic.Polygon({
                name: 'main',
                draggable: true,
                drift: curry(driftPolygon, controller, cover),
                ondragend: curry(trigger, controller, {isEnd: true})
            }));
        },
        updateCoverShape: function (controller, cover, localRange, brushOption) {
            cover.childAt(0).setShape({
                points: clipByPanel(controller, cover, localRange)
            });
        },
        updateCommon: updateCommon,
        contain: mainShapeContain
    }
};

function getLineRenderer(xyIndex) {
    return {
        createCover: function (controller, brushOption) {
            return createBaseRectCover(
                curry(
                    driftRect,
                    function (range) {
                        var rectRange = [range, [0, 100]];
                        xyIndex && rectRange.reverse();
                        return rectRange;
                    },
                    function (rectRange) {
                        return rectRange[xyIndex];
                    }
                ),
                controller,
                brushOption,
                [['w', 'e'], ['n', 's']][xyIndex]
            );
        },
        getCreatingRange: function (localTrack) {
            var ends = getTrackEnds(localTrack);
            var min = mathMin(ends[0][xyIndex], ends[1][xyIndex]);
            var max = mathMax(ends[0][xyIndex], ends[1][xyIndex]);
P
pah100 已提交
1008

S
sushuang 已提交
1009 1010 1011 1012 1013 1014 1015 1016 1017
            return [min, max];
        },
        updateCoverShape: function (controller, cover, localRange, brushOption) {
            var otherExtent;
            // If brushWidth not specified, fit the panel.
            var panel = getPanelByCover(controller, cover);
            if (panel !== true && panel.getLinearBrushOtherExtent) {
                otherExtent = panel.getLinearBrushOtherExtent(
                    xyIndex, controller._transform
P
pah100 已提交
1018
                );
S
sushuang 已提交
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
            }
            else {
                var zr = controller._zr;
                otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
            }
            var rectRange = [localRange, otherExtent];
            xyIndex && rectRange.reverse();

            updateBaseRect(controller, cover, rectRange, brushOption);
        },
        updateCommon: updateCommon,
        contain: mainShapeContain
    };
}
P
pah100 已提交
1033

S
sushuang 已提交
1034
export default BrushController;