echarts.js 53.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Enable DEV mode when using source code without build. which has no __DEV__ variable
// In build process 'typeof __DEV__' will be replace with 'boolean'
// So this code will be removed or disabled anyway after built.
if (typeof __DEV__ === 'undefined') {
    // In browser
    if (typeof window !== 'undefined') {
        window.__DEV__ = true;
    }
    // In node
    else if (typeof global !== 'undefined') {
        global.__DEV__ = true;
    }
}

L
tweak  
lang 已提交
15 16 17 18 19 20 21 22 23 24
/*!
 * ECharts, a javascript interactive chart library.
 *
 * Copyright (c) 2015, Baidu Inc.
 * All rights reserved.
 *
 * LICENSE
 * https://github.com/ecomfe/echarts/blob/master/LICENSE.txt
 */

L
lang 已提交
25
/**
L
lang 已提交
26
 * @module echarts
L
lang 已提交
27
 */
L
lang 已提交
28 29
define(function (require) {

30 31
    var env = require('zrender/core/env');

L
lang 已提交
32
    var GlobalModel = require('./model/Global');
L
lang 已提交
33
    var ExtensionAPI = require('./ExtensionAPI');
L
lang 已提交
34
    var CoordinateSystemManager = require('./CoordinateSystem');
P
pah100 已提交
35
    var OptionManager = require('./model/OptionManager');
L
lang 已提交
36

L
Update  
lang 已提交
37 38 39 40 41
    var ComponentModel = require('./model/Component');
    var SeriesModel = require('./model/Series');

    var ComponentView = require('./view/Component');
    var ChartView = require('./view/Chart');
L
lang 已提交
42
    var graphic = require('./util/graphic');
43
    var modelUtil = require('./util/model');
L
Update  
lang 已提交
44

L
lang 已提交
45
    var zrender = require('zrender');
L
lang 已提交
46
    var zrUtil = require('zrender/core/util');
L
lang 已提交
47
    var colorTool = require('zrender/tool/color');
L
lang 已提交
48
    var Eventful = require('zrender/mixin/Eventful');
L
lang 已提交
49
    var timsort = require('zrender/core/timsort');
L
lang 已提交
50

51 52
    var each = zrUtil.each;

53 54
    var PRIORITY_PROCESSOR_FILTER = 1000;
    var PRIORITY_PROCESSOR_STATISTIC = 5000;
55

56 57 58 59 60

    var PRIORITY_VISUAL_LAYOUT = 1000;
    var PRIORITY_VISUAL_GLOBAL = 2000;
    var PRIORITY_VISUAL_CHART = 3000;
    var PRIORITY_VISUAL_COMPONENT = 4000;
P
pah100 已提交
61
    var PRIORITY_VISUAL_BRUSH = 5000;
L
lang 已提交
62

63 64 65 66 67 68
    // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
    // where they must not be invoked nestedly, except the only case: invoke
    // dispatchAction with updateMethod "none" in main process.
    // This flag is used to carry out this rule.
    // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
    var IN_MAIN_PROCESS = '__flag_in_main_process';
L
lang 已提交
69
    var HAS_GRADIENT_OR_PATTERN_BG = '_hasGradientOrPatternBg';
70

71 72 73

    var OPTION_UPDATED = '_optionUpdated';

74 75 76 77 78 79
    function createRegisterEventWithLowercaseName(method) {
        return function (eventName, handler, context) {
            // Event name is all lowercase
            eventName = eventName && eventName.toLowerCase();
            Eventful.prototype[method].call(this, eventName, handler, context);
        };
L
lang 已提交
80
    }
81

L
lang 已提交
82 83 84 85 86 87
    /**
     * @module echarts~MessageCenter
     */
    function MessageCenter() {
        Eventful.call(this);
    }
88 89 90
    MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on');
    MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off');
    MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one');
L
lang 已提交
91
    zrUtil.mixin(MessageCenter, Eventful);
92

L
lang 已提交
93 94 95
    /**
     * @module echarts~ECharts
     */
L
lang 已提交
96
    function ECharts (dom, theme, opts) {
L
lang 已提交
97
        opts = opts || {};
L
lang 已提交
98

L
lang 已提交
99 100 101 102 103
        // Get theme by name
        if (typeof theme === 'string') {
            theme = themeStorage[theme];
        }

L
lang 已提交
104 105 106 107 108 109 110 111 112
        /**
         * @type {string}
         */
        this.id;
        /**
         * Group id
         * @type {string}
         */
        this.group;
L
lang 已提交
113 114 115 116 117
        /**
         * @type {HTMLDomElement}
         * @private
         */
        this._dom = dom;
L
lang 已提交
118 119 120 121
        /**
         * @type {module:zrender/ZRender}
         * @private
         */
L
lang 已提交
122
        this._zr = zrender.init(dom, {
123
            renderer: opts.renderer || 'canvas',
124 125 126
            devicePixelRatio: opts.devicePixelRatio,
            width: opts.width,
            height: opts.height
L
lang 已提交
127
        });
L
lang 已提交
128

L
lang 已提交
129 130 131 132
        /**
         * @type {Object}
         * @private
         */
L
lang 已提交
133
        this._theme = zrUtil.clone(theme);
L
lang 已提交
134

L
lang 已提交
135 136 137 138
        /**
         * @type {Array.<module:echarts/view/Chart>}
         * @private
         */
L
lang 已提交
139
        this._chartsViews = [];
L
lang 已提交
140 141 142 143 144

        /**
         * @type {Object.<string, module:echarts/view/Chart>}
         * @private
         */
L
lang 已提交
145 146
        this._chartsMap = {};

L
lang 已提交
147 148 149 150
        /**
         * @type {Array.<module:echarts/view/Component>}
         * @private
         */
L
lang 已提交
151
        this._componentsViews = [];
L
lang 已提交
152 153 154 155 156

        /**
         * @type {Object.<string, module:echarts/view/Component>}
         * @private
         */
L
lang 已提交
157 158
        this._componentsMap = {};

L
lang 已提交
159
        /**
L
lang 已提交
160
         * @type {module:echarts/ExtensionAPI}
L
lang 已提交
161 162
         * @private
         */
163
        this._api = new ExtensionAPI(this);
L
lang 已提交
164

L
lang 已提交
165 166 167 168
        /**
         * @type {module:echarts/CoordinateSystem}
         * @private
         */
169
        this._coordSysMgr = new CoordinateSystemManager();
L
lang 已提交
170

L
lang 已提交
171 172
        Eventful.call(this);

L
lang 已提交
173 174 175 176 177 178
        /**
         * @type {module:echarts~MessageCenter}
         * @private
         */
        this._messageCenter = new MessageCenter();

L
lang 已提交
179 180
        // Init mouse events
        this._initEvents();
L
Resize  
lang 已提交
181 182 183

        // In case some people write `window.onresize = chart.resize`
        this.resize = zrUtil.bind(this.resize, this);
184

L
lang 已提交
185 186
        // Can't dispatch action during rendering procedure
        this._pendingActions = [];
187 188 189 190
        // Sort on demand
        function prioritySortFunc(a, b) {
            return a.prio - b.prio;
        }
L
lang 已提交
191 192
        timsort(visualFuncs, prioritySortFunc);
        timsort(dataProcessorFuncs, prioritySortFunc);
193 194

        this._zr.animation.on('frame', this._onframe, this);
L
lang 已提交
195
    }
L
lang 已提交
196

L
tweak  
lang 已提交
197
    var echartsProto = ECharts.prototype;
L
lang 已提交
198

199 200
    echartsProto._onframe = function () {
        // Lazy update
201
        if (this[OPTION_UPDATED]) {
202 203 204 205 206 207 208

            this[IN_MAIN_PROCESS] = true;

            updateMethods.prepareAndUpdate.call(this);

            this[IN_MAIN_PROCESS] = false;

209
            this[OPTION_UPDATED] = false;
210 211
        }
    };
212 213 214
    /**
     * @return {HTMLDomElement}
     */
L
tweak  
lang 已提交
215 216 217
    echartsProto.getDom = function () {
        return this._dom;
    };
L
lang 已提交
218

219 220 221
    /**
     * @return {module:zrender~ZRender}
     */
L
tweak  
lang 已提交
222 223 224
    echartsProto.getZr = function () {
        return this._zr;
    };
L
lang 已提交
225

226 227 228
    /**
     * @param {Object} option
     * @param {boolean} notMerge
229
     * @param {boolean} [lazyUpdate=false] Useful when setOption frequently.
230
     */
231
    echartsProto.setOption = function (option, notMerge, lazyUpdate) {
232 233 234 235
        if (__DEV__) {
            zrUtil.assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
        }

P
pah100 已提交
236
        this[IN_MAIN_PROCESS] = true;
237

P
pah100 已提交
238
        if (!this._model || notMerge) {
L
lang 已提交
239 240 241 242
            var optionManager = new OptionManager(this._api);
            var theme = this._theme;
            var ecModel = this._model = new GlobalModel(null, null, theme, optionManager);
            ecModel.init(null, null, theme, optionManager);
L
tweak  
lang 已提交
243
        }
L
lang 已提交
244

P
pah100 已提交
245
        this._model.setOption(option, optionPreprocessorFuncs);
P
pah100 已提交
246

247
        if (lazyUpdate) {
248
            this[OPTION_UPDATED] = true;
249 250 251 252
        }
        else {
            updateMethods.prepareAndUpdate.call(this);
            this._zr.refreshImmediately();
253
            this[OPTION_UPDATED] = false;
254
        }
P
pah100 已提交
255

P
pah100 已提交
256
        this[IN_MAIN_PROCESS] = false;
L
lang 已提交
257 258

        this._flushPendingActions();
P
pah100 已提交
259 260
    };

L
Tweak  
lang 已提交
261 262 263 264 265 266
    /**
     * @DEPRECATED
     */
    echartsProto.setTheme = function () {
        console.log('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
    };
P
pah100 已提交
267

L
tweak  
lang 已提交
268 269 270 271 272 273
    /**
     * @return {module:echarts/model/Global}
     */
    echartsProto.getModel = function () {
        return this._model;
    };
L
lang 已提交
274

L
lang 已提交
275 276 277 278
    /**
     * @return {Object}
     */
    echartsProto.getOption = function () {
279
        return this._model && this._model.getOption();
L
lang 已提交
280 281
    };

L
tweak  
lang 已提交
282 283 284 285 286 287
    /**
     * @return {number}
     */
    echartsProto.getWidth = function () {
        return this._zr.getWidth();
    };
L
lang 已提交
288

L
tweak  
lang 已提交
289 290 291 292 293 294
    /**
     * @return {number}
     */
    echartsProto.getHeight = function () {
        return this._zr.getHeight();
    };
L
lang 已提交
295

L
lang 已提交
296 297 298 299 300 301 302 303 304 305
    /**
     * Get canvas which has all thing rendered
     * @param {Object} opts
     * @param {string} [opts.backgroundColor]
     */
    echartsProto.getRenderedCanvas = function (opts) {
        if (!env.canvasSupported) {
            return;
        }
        opts = opts || {};
306
        opts.pixelRatio = opts.pixelRatio || 1;
L
lang 已提交
307
        opts.backgroundColor = opts.backgroundColor
308
            || this._model.get('backgroundColor');
L
lang 已提交
309 310 311 312 313 314 315 316 317 318 319 320
        var zr = this._zr;
        var list = zr.storage.getDisplayList();
        // Stop animations
        zrUtil.each(list, function (el) {
            el.stopAnimation(true);
        });
        return zr.painter.getRenderedCanvas(opts);
    };
    /**
     * @return {string}
     * @param {Object} opts
     * @param {string} [opts.type='png']
321
     * @param {string} [opts.pixelRatio=1]
L
lang 已提交
322 323 324
     * @param {string} [opts.backgroundColor]
     */
    echartsProto.getDataURL = function (opts) {
325 326
        opts = opts || {};
        var excludeComponents = opts.excludeComponents;
327 328 329
        var ecModel = this._model;
        var excludesComponentViews = [];
        var self = this;
330 331

        each(excludeComponents, function (componentType) {
332 333 334 335 336 337 338 339 340 341 342 343
            ecModel.eachComponent({
                mainType: componentType
            }, function (component) {
                var view = self._componentsMap[component.__viewId];
                if (!view.group.ignore) {
                    excludesComponentViews.push(view);
                    view.group.ignore = true;
                }
            });
        });

        var url = this.getRenderedCanvas(opts).toDataURL(
L
lang 已提交
344 345
            'image/' + (opts && opts.type || 'png')
        );
346 347 348 349 350

        each(excludesComponentViews, function (view) {
            view.group.ignore = false;
        });
        return url;
L
lang 已提交
351 352 353 354 355 356 357
    };


    /**
     * @return {string}
     * @param {Object} opts
     * @param {string} [opts.type='png']
358
     * @param {string} [opts.pixelRatio=1]
L
lang 已提交
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
     * @param {string} [opts.backgroundColor]
     */
    echartsProto.getConnectedDataURL = function (opts) {
        if (!env.canvasSupported) {
            return;
        }
        var groupId = this.group;
        var mathMin = Math.min;
        var mathMax = Math.max;
        var MAX_NUMBER = Infinity;
        if (connectedGroups[groupId]) {
            var left = MAX_NUMBER;
            var top = MAX_NUMBER;
            var right = -MAX_NUMBER;
            var bottom = -MAX_NUMBER;
            var canvasList = [];
375
            var dpr = (opts && opts.pixelRatio) || 1;
1
100pah 已提交
376 377

            zrUtil.each(instances, function (chart, id) {
L
lang 已提交
378
                if (chart.group === groupId) {
379 380 381
                    var canvas = chart.getRenderedCanvas(
                        zrUtil.clone(opts)
                    );
L
lang 已提交
382 383 384 385 386 387 388 389 390 391 392
                    var boundingRect = chart.getDom().getBoundingClientRect();
                    left = mathMin(boundingRect.left, left);
                    top = mathMin(boundingRect.top, top);
                    right = mathMax(boundingRect.right, right);
                    bottom = mathMax(boundingRect.bottom, bottom);
                    canvasList.push({
                        dom: canvas,
                        left: boundingRect.left,
                        top: boundingRect.top
                    });
                }
1
100pah 已提交
393
            });
L
lang 已提交
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

            left *= dpr;
            top *= dpr;
            right *= dpr;
            bottom *= dpr;
            var width = right - left;
            var height = bottom - top;
            var targetCanvas = zrUtil.createCanvas();
            targetCanvas.width = width;
            targetCanvas.height = height;
            var zr = zrender.init(targetCanvas);

            each(canvasList, function (item) {
                var img = new graphic.Image({
                    style: {
                        x: item.left * dpr - left,
                        y: item.top * dpr - top,
                        image: item.dom
                    }
                });
                zr.add(img);
            });
            zr.refreshImmediately();

            return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
        }
        else {
            return this.getDataURL(opts);
        }
    };
424

1
100pah 已提交
425
    /**
1
100pah 已提交
426
     * Convert from logical coordinate system to pixel coordinate system.
1
100pah 已提交
427 428
     * See CoordinateSystem#convertToPixel.
     * @param {string|Object} finder
1
100pah 已提交
429 430 431
     *        If string, e.g., 'geo', means {geoIndex: 0}.
     *        If Object, could contain some of these properties below:
     *        {
432 433 434 435 436 437
     *            seriesIndex / seriesId / seriesName,
     *            geoIndex / geoId, geoName,
     *            bmapIndex / bmapId / bmapName,
     *            xAxisIndex / xAxisId / xAxisName,
     *            yAxisIndex / yAxisId / yAxisName,
     *            gridIndex / gridId / gridName,
1
100pah 已提交
438 439
     *            ... (can be extended)
     *        }
1
100pah 已提交
440
     * @param {Array|number} value
1
100pah 已提交
441
     * @return {Array|number} result
1
100pah 已提交
442
     */
1
100pah 已提交
443
    echartsProto.convertToPixel = zrUtil.curry(doConvertPixel, 'convertToPixel');
1
100pah 已提交
444

1
100pah 已提交
445 446 447 448
    /**
     * Convert from pixel coordinate system to logical coordinate system.
     * See CoordinateSystem#convertFromPixel.
     * @param {string|Object} finder
1
100pah 已提交
449 450 451
     *        If string, e.g., 'geo', means {geoIndex: 0}.
     *        If Object, could contain some of these properties below:
     *        {
452 453 454 455 456 457
     *            seriesIndex / seriesId / seriesName,
     *            geoIndex / geoId / geoName,
     *            bmapIndex / bmapId / bmapName,
     *            xAxisIndex / xAxisId / xAxisName,
     *            yAxisIndex / yAxisId / yAxisName
     *            gridIndex / gridId / gridName,
1
100pah 已提交
458 459
     *            ... (can be extended)
     *        }
1
100pah 已提交
460 461 462
     * @param {Array|number} value
     * @return {Array|number} result
     */
1
100pah 已提交
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
    echartsProto.convertFromPixel = zrUtil.curry(doConvertPixel, 'convertFromPixel');

    function doConvertPixel(methodName, finder, value) {
        var ecModel = this._model;
        var coordSysList = this._coordSysMgr.getCoordinateSystems();
        var result;

        finder = modelUtil.parseFinder(ecModel, finder);

        for (var i = 0; i < coordSysList.length; i++) {
            var coordSys = coordSysList[i];
            if (coordSys[methodName]
                && (result = coordSys[methodName](ecModel, finder, value)) != null
            ) {
                return result;
            }
        }

        if (__DEV__) {
            console.warn(
                'No coordinate system that supports ' + methodName + ' found by the given finder.'
            );
        }
    }

    /**
     * Is the specified coordinate systems or components contain the given pixel point.
     * @param {string|Object} finder
     *        If string, e.g., 'geo', means {geoIndex: 0}.
     *        If Object, could contain some of these properties below:
     *        {
494 495 496 497 498 499
     *            seriesIndex / seriesId / seriesName,
     *            geoIndex / geoId / geoName,
     *            bmapIndex / bmapId / bmapName,
     *            xAxisIndex / xAxisId / xAxisName,
     *            yAxisIndex / yAxisId / yAxisName
     *            gridIndex / gridId / gridName,
1
100pah 已提交
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
     *            ... (can be extended)
     *        }
     * @param {Array|number} value
     * @return {boolean} result
     */
    echartsProto.containPixel = function (finder, value) {
        var ecModel = this._model;
        var result;

        finder = modelUtil.parseFinder(ecModel, finder);

        zrUtil.each(finder, function (models, key) {
            key.indexOf('Models') >= 0 && zrUtil.each(models, function (model) {
                var coordSys = model.coordinateSystem;
                if (coordSys && coordSys.containPoint) {
                    result |= !!coordSys.containPoint(value);
                }
                else if (key === 'seriesModels') {
                    var view = this._chartsMap[model.__viewId];
                    if (view && view.containPoint) {
                        result |= view.containPoint(value, model);
                    }
                    else {
                        if (__DEV__) {
                            console.warn(key + ': ' + (view
                                ? 'The found component do not support containPoint.'
                                : 'No view mapping to the found component.'
                            ));
                        }
                    }
                }
                else {
                    if (__DEV__) {
                        console.warn(key + ': containPoint is not supported');
                    }
                }
            }, this);
        }, this);

        return !!result;
1
100pah 已提交
540 541
    };

542 543 544 545 546 547 548 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
    /**
     * Get visual from series or data.
     * @param {string|Object} finder
     *        If string, e.g., 'series', means {seriesIndex: 0}.
     *        If Object, could contain some of these properties below:
     *        {
     *            seriesIndex / seriesId / seriesName,
     *            dataIndex / dataIndexInside
     *        }
     *        If dataIndex is not specified, series visual will be fetched,
     *        but not data item visual.
     *        If all of seriesIndex, seriesId, seriesName are not specified,
     *        visual will be fetched from first series.
     * @param {string} visualType 'color', 'symbol', 'symbolSize'
     */
    echartsProto.getVisual = function (finder, visualType) {
        var ecModel = this._model;

        finder = modelUtil.parseFinder(ecModel, finder, {defaultMainType: 'series'});

        var seriesModel = finder.seriesModel;

        if (__DEV__) {
            if (!seriesModel) {
                console.warn('There is no specified seires model');
            }
        }

        var data = seriesModel.getData();

        var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
            ? finder.dataIndexInside
            : finder.hasOwnProperty('dataIndex')
            ? data.indexOfRawIndex(finder.dataIndex)
            : null;

        return dataIndexInside != null
            ? data.getItemVisual(dataIndexInside, visualType)
            : data.getVisual(visualType);
    };

1
100pah 已提交
583

584
    var updateMethods = {
L
lang 已提交
585

586 587 588 589 590
        /**
         * @param {Object} payload
         * @private
         */
        update: function (payload) {
591
            // console.time && console.time('update');
L
lang 已提交
592

593
            var ecModel = this._model;
594 595
            var api = this._api;
            var coordSysMgr = this._coordSysMgr;
L
lang 已提交
596
            var zr = this._zr;
597 598 599 600
            // update before setOption
            if (!ecModel) {
                return;
            }
L
lang 已提交
601

602
            // Fixme First time update ?
603 604 605 606 607
            ecModel.restoreData();

            // TODO
            // Save total ecModel here for undo/redo (after restoring data and before processing data).
            // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
P
pah100 已提交
608

609 610 611 612 613
            // Create new coordinate system each update
            // In LineView may save the old coordinate system and use it to get the orignal point
            coordSysMgr.create(this._model, this._api);

            processData.call(this, ecModel, api);
L
lang 已提交
614

615
            stackSeriesData.call(this, ecModel);
L
lang 已提交
616

617
            coordSysMgr.update(ecModel, api);
L
lang 已提交
618

L
lang 已提交
619
            doVisualEncoding.call(this, ecModel, payload);
620

621
            doRender.call(this, ecModel, payload);
622

623
            // Set background
L
lang 已提交
624
            var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
625

L
lang 已提交
626
            var painter = zr.painter;
627
            // TODO all use clearColor ?
L
lang 已提交
628
            if (painter.isSingleCanvas && painter.isSingleCanvas()) {
L
lang 已提交
629
                zr.configLayer(0, {
L
lang 已提交
630 631 632 633
                    clearColor: backgroundColor
                });
            }
            else {
L
lang 已提交
634 635 636 637 638 639 640 641
                // In IE8
                if (!env.canvasSupported) {
                    var colorArr = colorTool.parse(backgroundColor);
                    backgroundColor = colorTool.stringify(colorArr, 'rgb');
                    if (colorArr[3] === 0) {
                        backgroundColor = 'transparent';
                    }
                }
L
lang 已提交
642
                if (backgroundColor.colorStops || backgroundColor.image) {
L
lang 已提交
643 644 645 646 647
                    // Gradient background
                    // FIXME Fixed layer?
                    zr.configLayer(0, {
                        clearColor: backgroundColor
                    });
L
lang 已提交
648 649 650
                    this[HAS_GRADIENT_OR_PATTERN_BG] = true;

                    this._dom.style.background = 'transparent';
L
lang 已提交
651 652
                }
                else {
L
lang 已提交
653
                    if (this[HAS_GRADIENT_OR_PATTERN_BG]) {
L
lang 已提交
654 655 656 657
                        zr.configLayer(0, {
                            clearColor: null
                        });
                    }
L
lang 已提交
658
                    this[HAS_GRADIENT_OR_PATTERN_BG] = false;
L
lang 已提交
659 660 661

                    this._dom.style.background = backgroundColor;
                }
L
lang 已提交
662
            }
L
lang 已提交
663

664
            // console.time && console.timeEnd('update');
665
        },
666

667 668 669 670 671 672 673
        // PENDING
        /**
         * @param {Object} payload
         * @private
         */
        updateView: function (payload) {
            var ecModel = this._model;
674

675 676 677 678 679
            // update before setOption
            if (!ecModel) {
                return;
            }

P
pah100 已提交
680 681 682 683
            ecModel.eachSeries(function (seriesModel) {
                seriesModel.getData().clearAllVisual();
            });

684
            doVisualEncoding.call(this, ecModel, payload);
685

686 687
            invokeUpdateMethod.call(this, 'updateView', ecModel, payload);
        },
688

689 690 691 692 693 694
        /**
         * @param {Object} payload
         * @private
         */
        updateVisual: function (payload) {
            var ecModel = this._model;
695

696 697 698 699 700
            // update before setOption
            if (!ecModel) {
                return;
            }

P
pah100 已提交
701 702 703 704
            ecModel.eachSeries(function (seriesModel) {
                seriesModel.getData().clearAllVisual();
            });

705
            doVisualEncoding.call(this, ecModel, payload);
706

707 708
            invokeUpdateMethod.call(this, 'updateVisual', ecModel, payload);
        },
709

710 711 712 713 714 715
        /**
         * @param {Object} payload
         * @private
         */
        updateLayout: function (payload) {
            var ecModel = this._model;
716

717 718 719 720 721
            // update before setOption
            if (!ecModel) {
                return;
            }

L
lang 已提交
722
            doLayout.call(this, ecModel, payload);
723

724 725
            invokeUpdateMethod.call(this, 'updateLayout', ecModel, payload);
        },
L
lang 已提交
726

727 728 729 730 731 732 733 734 735 736 737 738 739 740
        /**
         * @param {Object} payload
         * @private
         */
        highlight: function (payload) {
            toggleHighlight.call(this, 'highlight', payload);
        },

        /**
         * @param {Object} payload
         * @private
         */
        downplay: function (payload) {
            toggleHighlight.call(this, 'downplay', payload);
P
pah100 已提交
741 742 743 744
        },

        /**
         * @param {Object} payload
P
pah100 已提交
745
         * @private
P
pah100 已提交
746
         */
P
pah100 已提交
747
        prepareAndUpdate: function (payload) {
P
pah100 已提交
748
            var ecModel = this._model;
749

P
pah100 已提交
750 751 752
            prepareView.call(this, 'component', ecModel);

            prepareView.call(this, 'chart', ecModel);
P
pah100 已提交
753

P
pah100 已提交
754
            updateMethods.update.call(this, payload);
P
pah100 已提交
755
        }
756 757 758 759 760 761
    };

    /**
     * @param {Object} payload
     * @private
     */
762
    function toggleHighlight(method, payload) {
763
        var ecModel = this._model;
764

765 766 767 768 769
        // dispatchAction before setOption
        if (!ecModel) {
            return;
        }

770 771
        ecModel.eachComponent(
            {mainType: 'series', query: payload},
L
lang 已提交
772
            function (seriesModel, index) {
L
lang 已提交
773
                var chartView = this._chartsMap[seriesModel.__viewId];
L
lang 已提交
774
                if (chartView && chartView.__alive) {
P
pah100 已提交
775
                    chartView[method](
L
lang 已提交
776
                        seriesModel, ecModel, this._api, payload
P
pah100 已提交
777
                    );
778 779 780 781
                }
            },
            this
        );
782
    }
783

L
Resize  
lang 已提交
784 785
    /**
     * Resize the chart
786 787 788
     * @param {Object} opts
     * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
     * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
L
Resize  
lang 已提交
789
     */
790
    echartsProto.resize = function (opts) {
791 792 793 794
        if (__DEV__) {
            zrUtil.assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
        }

P
pah100 已提交
795
        this[IN_MAIN_PROCESS] = true;
P
pah100 已提交
796

797
        this._zr.resize(opts);
P
pah100 已提交
798

P
pah100 已提交
799 800
        var optionChanged = this._model && this._model.resetOption('media');
        updateMethods[optionChanged ? 'prepareAndUpdate' : 'update'].call(this);
L
lang 已提交
801 802 803

        // Resize loading effect
        this._loadingFX && this._loadingFX.resize();
804

P
pah100 已提交
805
        this[IN_MAIN_PROCESS] = false;
L
lang 已提交
806 807

        this._flushPendingActions();
L
lang 已提交
808 809 810 811 812 813 814 815 816 817
    };

    /**
     * Show loading effect
     * @param  {string} [name='default']
     * @param  {Object} [cfg]
     */
    echartsProto.showLoading = function (name, cfg) {
        if (zrUtil.isObject(name)) {
            cfg = name;
818
            name = '';
L
lang 已提交
819
        }
820 821
        name = name || 'default';

L
lang 已提交
822
        this.hideLoading();
L
lang 已提交
823 824 825 826 827 828 829
        if (!loadingEffects[name]) {
            if (__DEV__) {
                console.warn('Loading effects ' + name + ' not exists.');
            }
            return;
        }
        var el = loadingEffects[name](this._api, cfg);
L
lang 已提交
830
        var zr = this._zr;
L
lang 已提交
831
        this._loadingFX = el;
L
lang 已提交
832 833

        zr.add(el);
L
lang 已提交
834 835 836 837 838 839
    };

    /**
     * Hide loading effect
     */
    echartsProto.hideLoading = function () {
L
lang 已提交
840
        this._loadingFX && this._zr.remove(this._loadingFX);
L
lang 已提交
841
        this._loadingFX = null;
L
tweak  
lang 已提交
842
    };
P
pah100 已提交
843

L
lang 已提交
844
    /**
L
Resize  
lang 已提交
845 846
     * @param {Object} eventObj
     * @return {Object}
L
lang 已提交
847 848 849 850 851 852 853
     */
    echartsProto.makeActionFromEvent = function (eventObj) {
        var payload = zrUtil.extend({}, eventObj);
        payload.type = eventActionMap[eventObj.type];
        return payload;
    };

L
tweak  
lang 已提交
854 855 856 857
    /**
     * @pubilc
     * @param {Object} payload
     * @param {string} [payload.type] Action type
P
pah100 已提交
858
     * @param {boolean} [silent=false] Whether trigger event.
L
tweak  
lang 已提交
859
     */
L
lang 已提交
860
    echartsProto.dispatchAction = function (payload, silent) {
L
tweak  
lang 已提交
861
        var actionWrap = actions[payload.type];
862 863 864
        if (!actionWrap) {
            return;
        }
L
lang 已提交
865

866 867 868
        var actionInfo = actionWrap.actionInfo;
        var updateMethod = actionInfo.update || 'update';

L
lang 已提交
869 870 871 872 873 874 875 876 877 878 879 880
        // if (__DEV__) {
        //     zrUtil.assert(
        //         !this[IN_MAIN_PROCESS],
        //         '`dispatchAction` should not be called during main process.'
        //         + 'unless updateMathod is "none".'
        //     );
        // }

        // May dispatchAction in rendering procedure
        if (this[IN_MAIN_PROCESS]) {
            this._pendingActions.push(payload);
            return;
881 882
        }

883
        this[IN_MAIN_PROCESS] = true;
L
lang 已提交
884

885 886 887 888 889 890 891 892 893 894 895
        var payloads = [payload];
        var batched = false;
        // Batch action
        if (payload.batch) {
            batched = true;
            payloads = zrUtil.map(payload.batch, function (item) {
                item = zrUtil.defaults(zrUtil.extend({}, item), payload);
                item.batch = null;
                return item;
            });
        }
P
pah100 已提交
896

897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
        var eventObjBatch = [];
        var eventObj;
        var isHighlightOrDownplay = payload.type === 'highlight' || payload.type === 'downplay';
        for (var i = 0; i < payloads.length; i++) {
            var batchItem = payloads[i];
            // Action can specify the event by return it.
            eventObj = actionWrap.action(batchItem, this._model);
            // Emit event outside
            eventObj = eventObj || zrUtil.extend({}, batchItem);
            // Convert type to eventType
            eventObj.type = actionInfo.event || eventObj.type;
            eventObjBatch.push(eventObj);

            // Highlight and downplay are special.
            isHighlightOrDownplay && updateMethods[updateMethod].call(this, batchItem);
        }

914 915 916 917 918 919 920 921 922 923 924
        if (updateMethod !== 'none' && !isHighlightOrDownplay) {
            // Still dirty
            if (this[OPTION_UPDATED]) {
                // FIXME Pass payload ?
                updateMethods.prepareAndUpdate.call(this, payload);
                this[OPTION_UPDATED] = false;
            }
            else {
                updateMethods[updateMethod].call(this, payload);
            }
        }
925 926 927 928 929 930 931 932 933 934 935 936

        // Follow the rule of action batch
        if (batched) {
            eventObj = {
                type: actionInfo.event || payload.type,
                batch: eventObjBatch
            };
        }
        else {
            eventObj = eventObjBatch[0];
        }

937 938
        this[IN_MAIN_PROCESS] = false;

L
tweak  
lang 已提交
939 940
        !silent && this._messageCenter.trigger(eventObj.type, eventObj);

L
lang 已提交
941 942
        this._flushPendingActions();

L
tweak  
lang 已提交
943
    };
944

L
lang 已提交
945 946 947 948 949 950 951 952
    echartsProto._flushPendingActions = function () {
        var pendingActions = this._pendingActions;
        while (pendingActions.length) {
            var payload = pendingActions.shift();
            this.dispatchAction(payload);
        }
    };

L
lang 已提交
953 954 955 956
    /**
     * Register event
     * @method
     */
957 958 959
    echartsProto.on = createRegisterEventWithLowercaseName('on');
    echartsProto.off = createRegisterEventWithLowercaseName('off');
    echartsProto.one = createRegisterEventWithLowercaseName('one');
L
lang 已提交
960

L
tweak  
lang 已提交
961 962 963 964
    /**
     * @param {string} methodName
     * @private
     */
965
    function invokeUpdateMethod(methodName, ecModel, payload) {
966
        var api = this._api;
L
lang 已提交
967

L
tweak  
lang 已提交
968
        // Update all components
L
lang 已提交
969
        each(this._componentsViews, function (component) {
L
tweak  
lang 已提交
970 971
            var componentModel = component.__model;
            component[methodName](componentModel, ecModel, api, payload);
972

L
tweak  
lang 已提交
973 974
            updateZ(componentModel, component);
        }, this);
L
lang 已提交
975

L
tweak  
lang 已提交
976 977
        // Upate all charts
        ecModel.eachSeries(function (seriesModel, idx) {
L
lang 已提交
978
            var chart = this._chartsMap[seriesModel.__viewId];
L
tweak  
lang 已提交
979
            chart[methodName](seriesModel, ecModel, api, payload);
980

L
tweak  
lang 已提交
981
            updateZ(seriesModel, chart);
982 983

            updateProgressiveAndBlend(seriesModel, chart);
L
tweak  
lang 已提交
984
        }, this);
985

986 987
        // If use hover layer
        updateHoverLayerStatus(this._zr, ecModel);
988
    }
L
lang 已提交
989

L
lang 已提交
990
    /**
L
Tweak  
lang 已提交
991
     * Prepare view instances of charts and components
L
lang 已提交
992 993 994
     * @param  {module:echarts/model/Global} ecModel
     * @private
     */
995
    function prepareView(type, ecModel) {
L
Tweak  
lang 已提交
996
        var isComponent = type === 'component';
L
lang 已提交
997
        var viewList = isComponent ? this._componentsViews : this._chartsViews;
L
Tweak  
lang 已提交
998
        var viewMap = isComponent ? this._componentsMap : this._chartsMap;
L
tweak  
lang 已提交
999
        var zr = this._zr;
L
lang 已提交
1000

L
Tweak  
lang 已提交
1001
        for (var i = 0; i < viewList.length; i++) {
L
lang 已提交
1002
            viewList[i].__alive = false;
L
tweak  
lang 已提交
1003
        }
L
lang 已提交
1004

L
Tweak  
lang 已提交
1005 1006 1007 1008
        ecModel[isComponent ? 'eachComponent' : 'eachSeries'](function (componentType, model) {
            if (isComponent) {
                if (componentType === 'series') {
                    return;
L
lang 已提交
1009
                }
1010
            }
L
tweak  
lang 已提交
1011
            else {
L
Tweak  
lang 已提交
1012
                model = componentType;
L
tweak  
lang 已提交
1013 1014
            }

1015
            // Consider: id same and type changed.
L
lang 已提交
1016 1017
            var viewId = model.id + '_' + model.type;
            var view = viewMap[viewId];
L
Tweak  
lang 已提交
1018 1019 1020
            if (!view) {
                var classType = ComponentModel.parseClassType(model.type);
                var Clazz = isComponent
L
tweak  
lang 已提交
1021
                    ? ComponentView.getClass(classType.main, classType.sub)
L
Tweak  
lang 已提交
1022
                    : ChartView.getClass(classType.sub);
L
tweak  
lang 已提交
1023
                if (Clazz) {
L
Tweak  
lang 已提交
1024 1025
                    view = new Clazz();
                    view.init(ecModel, this._api);
L
lang 已提交
1026
                    viewMap[viewId] = view;
L
Tweak  
lang 已提交
1027 1028 1029 1030 1031
                    viewList.push(view);
                    zr.add(view.group);
                }
                else {
                    // Error
L
lang 已提交
1032
                    return;
L
lang 已提交
1033
                }
1034
            }
L
Tweak  
lang 已提交
1035

L
lang 已提交
1036
            model.__viewId = viewId;
L
lang 已提交
1037
            view.__alive = true;
L
lang 已提交
1038
            view.__id = viewId;
L
Tweak  
lang 已提交
1039
            view.__model = model;
L
tweak  
lang 已提交
1040 1041
        }, this);

L
Tweak  
lang 已提交
1042 1043
        for (var i = 0; i < viewList.length;) {
            var view = viewList[i];
L
lang 已提交
1044
            if (!view.__alive) {
L
Tweak  
lang 已提交
1045
                zr.remove(view.group);
L
lang 已提交
1046
                view.dispose(ecModel, this._api);
L
Tweak  
lang 已提交
1047 1048
                viewList.splice(i, 1);
                delete viewMap[view.__id];
L
tweak  
lang 已提交
1049 1050 1051 1052 1053
            }
            else {
                i++;
            }
        }
1054 1055
    }

L
tweak  
lang 已提交
1056 1057 1058 1059 1060 1061
    /**
     * Processor data in each series
     *
     * @param {module:echarts/model/Global} ecModel
     * @private
     */
1062
    function processData(ecModel, api) {
1063 1064
        each(dataProcessorFuncs, function (process) {
            process.func(ecModel, api);
L
tweak  
lang 已提交
1065
        });
1066
    }
L
lang 已提交
1067

L
tweak  
lang 已提交
1068 1069 1070
    /**
     * @private
     */
1071
    function stackSeriesData(ecModel) {
L
tweak  
lang 已提交
1072 1073 1074 1075 1076 1077 1078 1079
        var stackedDataMap = {};
        ecModel.eachSeries(function (series) {
            var stack = series.get('stack');
            var data = series.getData();
            if (stack && data.type === 'list') {
                var previousStack = stackedDataMap[stack];
                if (previousStack) {
                    data.stackedOn = previousStack;
L
lang 已提交
1080
                }
L
tweak  
lang 已提交
1081 1082 1083
                stackedDataMap[stack] = data;
            }
        });
1084
    }
L
lang 已提交
1085

L
tweak  
lang 已提交
1086
    /**
1087
     * Layout before each chart render there series, special visual encoding stage
L
tweak  
lang 已提交
1088 1089 1090 1091
     *
     * @param {module:echarts/model/Global} ecModel
     * @private
     */
L
lang 已提交
1092 1093
    function doLayout(ecModel, payload) {
        var api = this._api;
1094 1095 1096 1097
        each(visualFuncs, function (visual) {
            if (visual.isLayout) {
                visual.func(ecModel, api, payload);
            }
L
tweak  
lang 已提交
1098
        });
1099
    }
L
lang 已提交
1100

L
tweak  
lang 已提交
1101
    /**
1102
     * Encode visual infomation from data after data processing
L
tweak  
lang 已提交
1103 1104 1105 1106
     *
     * @param {module:echarts/model/Global} ecModel
     * @private
     */
L
lang 已提交
1107 1108
    function doVisualEncoding(ecModel, payload) {
        var api = this._api;
L
lang 已提交
1109 1110 1111 1112
        ecModel.clearColorPalette();
        ecModel.eachSeries(function (seriesModel) {
            seriesModel.clearColorPalette();
        });
1113 1114
        each(visualFuncs, function (visual) {
            visual.func(ecModel, api, payload);
L
tweak  
lang 已提交
1115
        });
1116
    }
L
lang 已提交
1117

L
tweak  
lang 已提交
1118 1119 1120 1121
    /**
     * Render each chart and component
     * @private
     */
1122
    function doRender(ecModel, payload) {
1123
        var api = this._api;
L
tweak  
lang 已提交
1124
        // Render all components
L
lang 已提交
1125 1126 1127
        each(this._componentsViews, function (componentView) {
            var componentModel = componentView.__model;
            componentView.render(componentModel, ecModel, api, payload);
L
tweak  
lang 已提交
1128

L
lang 已提交
1129
            updateZ(componentModel, componentView);
L
tweak  
lang 已提交
1130 1131
        }, this);

L
lang 已提交
1132
        each(this._chartsViews, function (chart) {
L
lang 已提交
1133
            chart.__alive = false;
L
tweak  
lang 已提交
1134 1135 1136 1137
        }, this);

        // Render all charts
        ecModel.eachSeries(function (seriesModel, idx) {
L
lang 已提交
1138
            var chartView = this._chartsMap[seriesModel.__viewId];
L
lang 已提交
1139
            chartView.__alive = true;
L
lang 已提交
1140
            chartView.render(seriesModel, ecModel, api, payload);
L
tweak  
lang 已提交
1141

L
lang 已提交
1142 1143
            chartView.group.silent = !!seriesModel.get('silent');

L
lang 已提交
1144
            updateZ(seriesModel, chartView);
1145

1146
            updateProgressiveAndBlend(seriesModel, chartView);
L
lang 已提交
1147

L
tweak  
lang 已提交
1148 1149
        }, this);

L
lang 已提交
1150
        // If use hover layer
1151 1152
        updateHoverLayerStatus(this._zr, ecModel);

L
lang 已提交
1153
        // Remove groups of unrendered charts
L
lang 已提交
1154
        each(this._chartsViews, function (chart) {
L
lang 已提交
1155
            if (!chart.__alive) {
L
tweak  
lang 已提交
1156 1157 1158
                chart.remove(ecModel, api);
            }
        }, this);
1159
    }
L
lang 已提交
1160

L
lang 已提交
1161
    var MOUSE_EVENT_NAMES = [
1
100pah 已提交
1162 1163
        'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
        'mousedown', 'mouseup', 'globalout', 'contextmenu'
L
lang 已提交
1164 1165 1166 1167 1168 1169
    ];
    /**
     * @private
     */
    echartsProto._initEvents = function () {
        each(MOUSE_EVENT_NAMES, function (eveName) {
1170
            this._zr.on(eveName, function (e) {
L
lang 已提交
1171 1172
                var ecModel = this.getModel();
                var el = e.target;
1
100pah 已提交
1173
                var params;
1
100pah 已提交
1174

1
100pah 已提交
1175
                // no e.target when 'globalout'.
1
100pah 已提交
1176
                if (eveName === 'globalout') {
1
100pah 已提交
1177
                    params = {};
1
100pah 已提交
1178 1179
                }
                else if (el && el.dataIndex != null) {
L
lang 已提交
1180
                    var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
1
100pah 已提交
1181
                    params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType) || {};
L
lang 已提交
1182
                }
L
lang 已提交
1183 1184
                // If element has custom eventData of components
                else if (el && el.eventData) {
1
100pah 已提交
1185
                    params = zrUtil.extend({}, el.eventData);
L
lang 已提交
1186
                }
1
100pah 已提交
1187 1188 1189 1190 1191 1192 1193

                if (params) {
                    params.event = e;
                    params.type = eveName;
                    this.trigger(eveName, params);
                }

L
lang 已提交
1194 1195
            }, this);
        }, this);
L
lang 已提交
1196

L
lang 已提交
1197
        each(eventActionMap, function (actionType, eventType) {
L
lang 已提交
1198 1199 1200 1201
            this._messageCenter.on(eventType, function (event) {
                this.trigger(eventType, event);
            }, this);
        }, this);
L
lang 已提交
1202 1203
    };

L
lang 已提交
1204
    /**
L
lang 已提交
1205
     * @return {boolean}
L
lang 已提交
1206 1207 1208 1209
     */
    echartsProto.isDisposed = function () {
        return this._disposed;
    };
L
lang 已提交
1210 1211 1212 1213 1214

    /**
     * Clear
     */
    echartsProto.clear = function () {
1215
        this.setOption({ series: [] }, true);
L
lang 已提交
1216
    };
L
lang 已提交
1217 1218 1219
    /**
     * Dispose instance
     */
L
tweak  
lang 已提交
1220
    echartsProto.dispose = function () {
1221 1222 1223 1224 1225 1226
        if (this._disposed) {
            if (__DEV__) {
                console.warn('Instance ' + this.id + ' has been disposed');
            }
            return;
        }
L
lang 已提交
1227
        this._disposed = true;
1228

L
lang 已提交
1229
        var api = this._api;
L
lang 已提交
1230
        var ecModel = this._model;
L
lang 已提交
1231

L
lang 已提交
1232
        each(this._componentsViews, function (component) {
L
lang 已提交
1233
            component.dispose(ecModel, api);
L
tweak  
lang 已提交
1234
        });
L
lang 已提交
1235
        each(this._chartsViews, function (chart) {
L
lang 已提交
1236
            chart.dispose(ecModel, api);
L
tweak  
lang 已提交
1237
        });
L
lang 已提交
1238

1239
        // Dispose after all views disposed
L
Tweak  
lang 已提交
1240
        this._zr.dispose();
L
lang 已提交
1241

L
lang 已提交
1242
        delete instances[this.id];
L
lang 已提交
1243 1244
    };

L
lang 已提交
1245 1246
    zrUtil.mixin(ECharts, Eventful);

1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
    function updateHoverLayerStatus(zr, ecModel) {
        var storage = zr.storage;
        var elCount = 0;
        storage.traverse(function (el) {
            if (!el.isGroup) {
                elCount++;
            }
        });
        if (elCount > ecModel.get('hoverLayerThreshold') && !env.node) {
            storage.traverse(function (el) {
                if (!el.isGroup) {
                    el.useHoverLayer = true;
                }
            });
        }
    }
    /**
     * Update chart progressive and blend.
     * @param {module:echarts/model/Series|module:echarts/model/Component} model
     * @param {module:echarts/view/Component|module:echarts/view/Chart} view
     */
    function updateProgressiveAndBlend(seriesModel, chartView) {
        // Progressive configuration
        var elCount = 0;
        chartView.group.traverse(function (el) {
            if (el.type !== 'group' && !el.ignore) {
                elCount++;
            }
        });
        var frameDrawNum = +seriesModel.get('progressive');
        var needProgressive = elCount > seriesModel.get('progressiveThreshold') && frameDrawNum && !env.node;
        if (needProgressive) {
            chartView.group.traverse(function (el) {
                // FIXME marker and other components
                if (!el.isGroup) {
                    el.progressive = needProgressive ?
                        Math.floor(elCount++ / frameDrawNum) : -1;
                    if (needProgressive) {
                        el.stopAnimation(true);
                    }
                }
            });
        }

        // Blend configration
        var blendMode = seriesModel.get('blendMode') || null;
        if (__DEV__) {
            if (!env.canvasSupported && blendMode && blendMode !== 'source-over') {
                console.warn('Only canvas support blendMode');
            }
        }
        chartView.group.traverse(function (el) {
            // FIXME marker and other components
            if (!el.isGroup) {
                el.setStyle('blend', blendMode);
            }
        });
    }
L
lang 已提交
1305 1306 1307 1308 1309 1310 1311 1312 1313
    /**
     * @param {module:echarts/model/Series|module:echarts/model/Component} model
     * @param {module:echarts/view/Component|module:echarts/view/Chart} view
     */
    function updateZ(model, view) {
        var z = model.get('z');
        var zlevel = model.get('zlevel');
        // Set z and zlevel
        view.group.traverse(function (el) {
1314 1315 1316 1317
            if (el.type !== 'group') {
                z != null && (el.z = z);
                zlevel != null && (el.zlevel = zlevel);
            }
L
lang 已提交
1318 1319
        });
    }
L
lang 已提交
1320 1321 1322 1323
    /**
     * @type {Array.<Function>}
     * @inner
     */
P
pah100 已提交
1324 1325
    var actions = [];

L
lang 已提交
1326
    /**
L
lang 已提交
1327
     * Map eventType to actionType
L
lang 已提交
1328 1329 1330 1331
     * @type {Object}
     */
    var eventActionMap = {};

L
lang 已提交
1332 1333 1334 1335 1336
    /**
     * Data processor functions of each stage
     * @type {Array.<Object.<string, Function>>}
     * @inner
     */
1337
    var dataProcessorFuncs = [];
L
lang 已提交
1338

1339 1340 1341 1342 1343 1344
    /**
     * @type {Array.<Function>}
     * @inner
     */
    var optionPreprocessorFuncs = [];

L
lang 已提交
1345
    /**
1346
     * Visual encoding functions of each stage
L
lang 已提交
1347 1348 1349
     * @type {Array.<Object.<string, Function>>}
     * @inner
     */
1350
    var visualFuncs = [];
L
lang 已提交
1351 1352 1353 1354 1355
    /**
     * Theme storage
     * @type {Object.<key, Object>}
     */
    var themeStorage = {};
L
lang 已提交
1356 1357 1358 1359
    /**
     * Loading effects
     */
    var loadingEffects = {};
L
lang 已提交
1360

L
lang 已提交
1361

L
lang 已提交
1362 1363 1364 1365 1366 1367
    var instances = {};
    var connectedGroups = {};

    var idBase = new Date() - 0;
    var groupIdBase = new Date() - 0;
    var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
L
lang 已提交
1368
    /**
L
lang 已提交
1369
     * @alias module:echarts
L
lang 已提交
1370
     */
L
lang 已提交
1371 1372 1373 1374
    var echarts = {
        /**
         * @type {number}
         */
1
100pah 已提交
1375
        version: '3.3.1',
L
lang 已提交
1376
        dependencies: {
1
100pah 已提交
1377
            zrender: '3.2.1'
L
lang 已提交
1378 1379
        }
    };
L
lang 已提交
1380

L
lang 已提交
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
    function enableConnect(chart) {

        var STATUS_PENDING = 0;
        var STATUS_UPDATING = 1;
        var STATUS_UPDATED = 2;
        var STATUS_KEY = '__connectUpdateStatus';
        function updateConnectedChartsStatus(charts, status) {
            for (var i = 0; i < charts.length; i++) {
                var otherChart = charts[i];
                otherChart[STATUS_KEY] = status;
            }
        }
        zrUtil.each(eventActionMap, function (actionType, eventType) {
            chart._messageCenter.on(eventType, function (event) {
                if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
                    var action = chart.makeActionFromEvent(event);
                    var otherCharts = [];
1
100pah 已提交
1398 1399

                    zrUtil.each(instances, function (otherChart) {
L
lang 已提交
1400 1401 1402
                        if (otherChart !== chart && otherChart.group === chart.group) {
                            otherCharts.push(otherChart);
                        }
1
100pah 已提交
1403 1404
                    });

L
lang 已提交
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
                    updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
                    each(otherCharts, function (otherChart) {
                        if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
                            otherChart.dispatchAction(action);
                        }
                    });
                    updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
                }
            });
        });

    }
L
tweak  
lang 已提交
1417 1418 1419 1420
    /**
     * @param {HTMLDomElement} dom
     * @param {Object} [theme]
     * @param {Object} opts
1421 1422 1423 1424 1425 1426
     * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
     * @param {string} [opts.renderer] Currently only 'canvas' is supported.
     * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
     *                              Can be 'auto' (the same as null/undefined)
     * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
     *                               Can be 'auto' (the same as null/undefined)
L
tweak  
lang 已提交
1427 1428
     */
    echarts.init = function (dom, theme, opts) {
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
        if (__DEV__) {
            // Check version
            if ((zrender.version.replace('.', '') - 0) < (echarts.dependencies.zrender.replace('.', '') - 0)) {
                throw new Error(
                    'ZRender ' + zrender.version
                    + ' is too old for ECharts ' + echarts.version
                    + '. Current version need ZRender '
                    + echarts.dependencies.zrender + '+'
                );
            }
            if (!dom) {
                throw new Error('Initialize failed: invalid dom.');
            }
L
lang 已提交
1442
            if (zrUtil.isDom(dom) && dom.nodeName.toUpperCase() !== 'CANVAS' && (!dom.clientWidth || !dom.clientHeight)) {
L
lang 已提交
1443
                console.warn('Can\'t get dom width or height');
1444
            }
1445
        }
L
lang 已提交
1446 1447

        var chart = new ECharts(dom, theme, opts);
L
lang 已提交
1448
        chart.id = 'ec_' + idBase++;
L
lang 已提交
1449 1450
        instances[chart.id] = chart;

L
lang 已提交
1451 1452 1453
        dom.setAttribute &&
            dom.setAttribute(DOM_ATTRIBUTE_KEY, chart.id);

L
lang 已提交
1454
        enableConnect(chart);
L
lang 已提交
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472

        return chart;
    };

    /**
     * @return {string|Array.<module:echarts~ECharts>} groupId
     */
    echarts.connect = function (groupId) {
        // Is array of charts
        if (zrUtil.isArray(groupId)) {
            var charts = groupId;
            groupId = null;
            // If any chart has group
            zrUtil.each(charts, function (chart) {
                if (chart.group != null) {
                    groupId = chart.group;
                }
            });
L
lang 已提交
1473
            groupId = groupId || ('g_' + groupIdBase++);
L
lang 已提交
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
            zrUtil.each(charts, function (chart) {
                chart.group = groupId;
            });
        }
        connectedGroups[groupId] = true;
        return groupId;
    };

    /**
     * @return {string} groupId
     */
    echarts.disConnect = function (groupId) {
        connectedGroups[groupId] = false;
    };

    /**
     * Dispose a chart instance
     * @param  {module:echarts~ECharts|HTMLDomElement|string} chart
     */
    echarts.dispose = function (chart) {
        if (zrUtil.isDom(chart)) {
            chart = echarts.getInstanceByDom(chart);
        }
        else if (typeof chart === 'string') {
            chart = instances[chart];
        }
        if ((chart instanceof ECharts) && !chart.isDisposed()) {
            chart.dispose();
        }
    };

    /**
     * @param  {HTMLDomElement} dom
     * @return {echarts~ECharts}
     */
    echarts.getInstanceByDom = function (dom) {
        var key = dom.getAttribute(DOM_ATTRIBUTE_KEY);
        return instances[key];
    };
    /**
     * @param {string} key
     * @return {echarts~ECharts}
     */
    echarts.getInstanceById = function (key) {
        return instances[key];
L
tweak  
lang 已提交
1519
    };
L
lang 已提交
1520

L
lang 已提交
1521 1522 1523 1524 1525 1526 1527
    /**
     * Register theme
     */
    echarts.registerTheme = function (name, theme) {
        themeStorage[name] = theme;
    };

L
tweak  
lang 已提交
1528 1529 1530 1531 1532 1533 1534
    /**
     * Register option preprocessor
     * @param {Function} preprocessorFunc
     */
    echarts.registerPreprocessor = function (preprocessorFunc) {
        optionPreprocessorFuncs.push(preprocessorFunc);
    };
1535

L
tweak  
lang 已提交
1536
    /**
1537
     * @param {number} [priority=1000]
L
tweak  
lang 已提交
1538 1539
     * @param {Function} processorFunc
     */
1540 1541 1542 1543
    echarts.registerProcessor = function (priority, processorFunc) {
        if (typeof priority === 'function') {
            processorFunc = priority;
            priority = PRIORITY_PROCESSOR_FILTER;
L
tweak  
lang 已提交
1544
        }
1545 1546 1547 1548
        if (__DEV__) {
            if (isNaN(priority)) {
                throw new Error('Unkown processor priority');
            }
1549 1550 1551 1552 1553
        }
        dataProcessorFuncs.push({
            prio: priority,
            func: processorFunc
        });
L
tweak  
lang 已提交
1554
    };
L
lang 已提交
1555

L
tweak  
lang 已提交
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
    /**
     * Usage:
     * registerAction('someAction', 'someEvent', function () { ... });
     * registerAction('someAction', function () { ... });
     * registerAction(
     *     {type: 'someAction', event: 'someEvent', update: 'updateView'},
     *     function () { ... }
     * );
     *
     * @param {(string|Object)} actionInfo
     * @param {string} actionInfo.type
L
lang 已提交
1567 1568 1569 1570
     * @param {string} [actionInfo.event]
     * @param {string} [actionInfo.update]
     * @param {string} [eventName]
     * @param {Function} action
L
tweak  
lang 已提交
1571
     */
L
lang 已提交
1572 1573 1574 1575 1576
    echarts.registerAction = function (actionInfo, eventName, action) {
        if (typeof eventName === 'function') {
            action = eventName;
            eventName = '';
        }
L
tweak  
lang 已提交
1577 1578
        var actionType = zrUtil.isObject(actionInfo)
            ? actionInfo.type
L
lang 已提交
1579 1580 1581
            : ([actionInfo, actionInfo = {
                event: eventName
            }][0]);
L
lang 已提交
1582

L
lang 已提交
1583 1584
        // Event name is all lowercase
        actionInfo.event = (actionInfo.event || actionType).toLowerCase();
L
lang 已提交
1585
        eventName = actionInfo.event;
1586

L
tweak  
lang 已提交
1587 1588 1589
        if (!actions[actionType]) {
            actions[actionType] = {action: action, actionInfo: actionInfo};
        }
L
lang 已提交
1590
        eventActionMap[eventName] = actionType;
L
tweak  
lang 已提交
1591
    };
P
pah100 已提交
1592

L
tweak  
lang 已提交
1593 1594 1595 1596 1597 1598 1599
    /**
     * @param {string} type
     * @param {*} CoordinateSystem
     */
    echarts.registerCoordinateSystem = function (type, CoordinateSystem) {
        CoordinateSystemManager.register(type, CoordinateSystem);
    };
L
lang 已提交
1600

L
tweak  
lang 已提交
1601
    /**
1602 1603 1604 1605
     * Layout is a special stage of visual encoding
     * Most visual encoding like color are common for different chart
     * But each chart has it's own layout algorithm
     *
L
lang 已提交
1606
     * @param {number} [priority=1000]
1607
     * @param {Function} layoutFunc
L
tweak  
lang 已提交
1608
     */
1609 1610 1611 1612 1613
    echarts.registerLayout = function (priority, layoutFunc) {
        if (typeof priority === 'function') {
            layoutFunc = priority;
            priority = PRIORITY_VISUAL_LAYOUT;
        }
1614 1615 1616 1617
        if (__DEV__) {
            if (isNaN(priority)) {
                throw new Error('Unkown layout priority');
            }
L
tweak  
lang 已提交
1618
        }
1619 1620 1621 1622 1623
        visualFuncs.push({
            prio: priority,
            func: layoutFunc,
            isLayout: true
        });
L
tweak  
lang 已提交
1624
    };
L
lang 已提交
1625

L
tweak  
lang 已提交
1626
    /**
L
lang 已提交
1627
     * @param {number} [priority=3000]
1628
     * @param {Function} visualFunc
L
tweak  
lang 已提交
1629
     */
1630 1631 1632 1633
    echarts.registerVisual = function (priority, visualFunc) {
        if (typeof priority === 'function') {
            visualFunc = priority;
            priority = PRIORITY_VISUAL_CHART;
L
tweak  
lang 已提交
1634
        }
1635 1636 1637 1638
        if (__DEV__) {
            if (isNaN(priority)) {
                throw new Error('Unkown visual priority');
            }
1639 1640 1641 1642 1643
        }
        visualFuncs.push({
            prio: priority,
            func: visualFunc
        });
L
tweak  
lang 已提交
1644
    };
L
Update  
lang 已提交
1645

L
lang 已提交
1646 1647 1648 1649 1650 1651 1652 1653
    /**
     * @param {string} name
     */
    echarts.registerLoading = function (name, loadingFx) {
        loadingEffects[name] = loadingFx;
    };


L
lang 已提交
1654
    var parseClassType = ComponentModel.parseClassType;
L
tweak  
lang 已提交
1655 1656
    /**
     * @param {Object} opts
L
lang 已提交
1657
     * @param {string} [superClass]
L
tweak  
lang 已提交
1658
     */
L
lang 已提交
1659 1660 1661 1662 1663 1664 1665
    echarts.extendComponentModel = function (opts, superClass) {
        var Clazz = ComponentModel;
        if (superClass) {
            var classType = parseClassType(superClass);
            Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
        }
        return Clazz.extend(opts);
L
tweak  
lang 已提交
1666
    };
L
Update  
lang 已提交
1667

L
tweak  
lang 已提交
1668 1669
    /**
     * @param {Object} opts
L
lang 已提交
1670
     * @param {string} [superClass]
L
tweak  
lang 已提交
1671
     */
L
lang 已提交
1672 1673 1674 1675 1676 1677 1678
    echarts.extendComponentView = function (opts, superClass) {
        var Clazz = ComponentView;
        if (superClass) {
            var classType = parseClassType(superClass);
            Clazz = ComponentView.getClass(classType.main, classType.sub, true);
        }
        return Clazz.extend(opts);
L
tweak  
lang 已提交
1679
    };
L
Update  
lang 已提交
1680

L
tweak  
lang 已提交
1681 1682
    /**
     * @param {Object} opts
L
lang 已提交
1683
     * @param {string} [superClass]
L
tweak  
lang 已提交
1684
     */
L
lang 已提交
1685 1686 1687 1688 1689
    echarts.extendSeriesModel = function (opts, superClass) {
        var Clazz = SeriesModel;
        if (superClass) {
            superClass = 'series.' + superClass.replace('series.', '');
            var classType = parseClassType(superClass);
1
100pah 已提交
1690
            Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
L
lang 已提交
1691 1692
        }
        return Clazz.extend(opts);
L
tweak  
lang 已提交
1693
    };
P
pah100 已提交
1694

L
tweak  
lang 已提交
1695 1696
    /**
     * @param {Object} opts
L
lang 已提交
1697
     * @param {string} [superClass]
L
tweak  
lang 已提交
1698
     */
L
lang 已提交
1699 1700 1701 1702 1703 1704 1705
    echarts.extendChartView = function (opts, superClass) {
        var Clazz = ChartView;
        if (superClass) {
            superClass.replace('series.', '');
            var classType = parseClassType(superClass);
            Clazz = ChartView.getClass(classType.main, true);
        }
L
Typo  
lang 已提交
1706
        return Clazz.extend(opts);
L
lang 已提交
1707 1708
    };

1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
    /**
     * ZRender need a canvas context to do measureText.
     * But in node environment canvas may be created by node-canvas.
     * So we need to specify how to create a canvas instead of using document.createElement('canvas')
     *
     * Be careful of using it in the browser.
     *
     * @param {Function} creator
     * @example
     *     var Canvas = require('canvas');
     *     var echarts = require('echarts');
     *     echarts.setCanvasCreator(function () {
     *         // Small size is enough.
     *         return new Canvas(32, 32);
     *     });
     */
    echarts.setCanvasCreator = function (creator) {
        zrUtil.createCanvas = creator;
    };

L
lang 已提交
1729
    echarts.registerVisual(PRIORITY_VISUAL_GLOBAL, require('./visual/seriesColor'));
1730
    echarts.registerPreprocessor(require('./preprocessor/backwardCompat'));
L
lang 已提交
1731
    echarts.registerLoading('default', require('./loading/default'));
1732

1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
    // Default action
    echarts.registerAction({
        type: 'highlight',
        event: 'highlight',
        update: 'highlight'
    }, zrUtil.noop);
    echarts.registerAction({
        type: 'downplay',
        event: 'downplay',
        update: 'downplay'
    }, zrUtil.noop);

P
pah100 已提交
1745 1746 1747 1748

    // --------
    // Exports
    // --------
L
lang 已提交
1749 1750 1751
    //
    echarts.List = require('./data/List');
    echarts.Model = require('./model/Model');
P
pah100 已提交
1752

L
lang 已提交
1753 1754 1755
    echarts.graphic = require('./util/graphic');
    echarts.number = require('./util/number');
    echarts.format = require('./util/format');
L
lang 已提交
1756 1757
    echarts.matrix = require('zrender/core/matrix');
    echarts.vector = require('zrender/core/vector');
L
lang 已提交
1758
    echarts.color = require('zrender/tool/color');
P
pah100 已提交
1759 1760 1761 1762 1763

    echarts.util = {};
    each([
            'map', 'each', 'filter', 'indexOf', 'inherits',
            'reduce', 'filter', 'bind', 'curry', 'isArray',
L
lang 已提交
1764
            'isString', 'isObject', 'isFunction', 'extend', 'defaults'
P
pah100 已提交
1765 1766 1767 1768 1769 1770
        ],
        function (name) {
            echarts.util[name] = zrUtil[name];
        }
    );

1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
    // PRIORITY
    echarts.PRIORITY = {
        PROCESSOR: {
            FILTER: PRIORITY_PROCESSOR_FILTER,
            STATISTIC: PRIORITY_PROCESSOR_STATISTIC
        },
        VISUAL: {
            LAYOUT: PRIORITY_VISUAL_LAYOUT,
            GLOBAL: PRIORITY_VISUAL_GLOBAL,
            CHART: PRIORITY_VISUAL_CHART,
P
pah100 已提交
1781
            COMPONENT: PRIORITY_VISUAL_COMPONENT,
P
pah100 已提交
1782
            BRUSH: PRIORITY_VISUAL_BRUSH
1783 1784 1785
        }
    };

L
lang 已提交
1786 1787
    return echarts;
});