echarts.js 57.2 KB
Newer Older
1

L
tweak  
lang 已提交
2
/*!
S
sushuang 已提交
3 4 5 6 7 8 9 10 11
 * ECharts, a javascript interactive chart library.
 *
 * Copyright (c) 2015, Baidu Inc.
 * All rights reserved.
 *
 * LICENSE
 * https://github.com/ecomfe/echarts/blob/master/LICENSE.txt
 */

S
sushuang 已提交
12
import {__DEV__} from './config';
S
sushuang 已提交
13 14 15 16 17 18
import * as zrender from 'zrender/src/zrender';
import * as zrUtil from 'zrender/src/core/util';
import * as colorTool from 'zrender/src/tool/color';
import env from 'zrender/src/core/env';
import timsort from 'zrender/src/core/timsort';
import Eventful from 'zrender/src/mixin/Eventful';
S
sushuang 已提交
19 20 21 22 23 24 25 26 27 28 29 30 31 32
import GlobalModel from './model/Global';
import ExtensionAPI from './ExtensionAPI';
import CoordinateSystemManager from './CoordinateSystem';
import OptionManager from './model/OptionManager';
import backwardCompat from './preprocessor/backwardCompat';
import ComponentModel from './model/Component';
import SeriesModel from './model/Series';
import ComponentView from './view/Component';
import ChartView from './view/Chart';
import * as graphic from './util/graphic';
import * as modelUtil from './util/model';
import {throttle} from './util/throttle';
import seriesColor from './visual/seriesColor';
import loadingDefault from './loading/default';
S
tweak  
sushuang 已提交
33
import Scheduler from './stream/Scheduler';
S
sushuang 已提交
34
import {getUID} from './util/component';
S
sushuang 已提交
35

S
sushuang 已提交
36
var assert = zrUtil.assert;
S
sushuang 已提交
37
var each = zrUtil.each;
S
sushuang 已提交
38 39 40
var createHashMap = zrUtil.createHashMap;
var isFunction = zrUtil.isFunction;
var isObject = zrUtil.isObject;
S
sushuang 已提交
41
var parseClassType = ComponentModel.parseClassType;
L
lang 已提交
42

S
sushuang 已提交
43
export var version = '3.8.5';
44

S
sushuang 已提交
45
export var dependencies = {
S
sushuang 已提交
46
    zrender: '3.7.4'
S
sushuang 已提交
47
};
48

S
sushuang 已提交
49 50
// ??? frame remain time in UI thread: 20ms? 16ms?
var TEST_FRAME_REMAIN_TIME = 1;
S
sushuang 已提交
51

S
sushuang 已提交
52 53 54 55 56 57 58 59 60 61 62
var PRIORITY_PROCESSOR_FILTER = 1000;
var PRIORITY_PROCESSOR_STATISTIC = 5000;

var PRIORITY_VISUAL_LAYOUT = 1000;
var PRIORITY_VISUAL_GLOBAL = 2000;
var PRIORITY_VISUAL_CHART = 3000;
var PRIORITY_VISUAL_COMPONENT = 4000;
// FIXME
// necessary?
var PRIORITY_VISUAL_BRUSH = 5000;

S
sushuang 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75
export var PRIORITY = {
    PROCESSOR: {
        FILTER: PRIORITY_PROCESSOR_FILTER,
        STATISTIC: PRIORITY_PROCESSOR_STATISTIC
    },
    VISUAL: {
        LAYOUT: PRIORITY_VISUAL_LAYOUT,
        GLOBAL: PRIORITY_VISUAL_GLOBAL,
        CHART: PRIORITY_VISUAL_CHART,
        COMPONENT: PRIORITY_VISUAL_COMPONENT,
        BRUSH: PRIORITY_VISUAL_BRUSH
    }
};
76

S
sushuang 已提交
77 78 79 80 81 82 83 84 85
// 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 = '__flagInMainProcess';
var HAS_GRADIENT_OR_PATTERN_BG = '__hasGradientOrPatternBg';
var OPTION_UPDATED = '__optionUpdated';
var ACTION_REG = /^[a-zA-Z0-9_]+$/;
L
lang 已提交
86

L
lang 已提交
87

S
sushuang 已提交
88 89 90 91 92 93 94
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 已提交
95

S
sushuang 已提交
96 97 98 99 100 101 102 103 104 105
/**
 * @module echarts~MessageCenter
 */
function MessageCenter() {
    Eventful.call(this);
}
MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on');
MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off');
MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one');
zrUtil.mixin(MessageCenter, Eventful);
106

S
sushuang 已提交
107 108 109 110 111
/**
 * @module echarts~ECharts
 */
function ECharts(dom, theme, opts) {
    opts = opts || {};
112

S
sushuang 已提交
113 114 115
    // Get theme by name
    if (typeof theme === 'string') {
        theme = themeStorage[theme];
L
lang 已提交
116
    }
L
lang 已提交
117

118
    /**
S
sushuang 已提交
119
     * @type {string}
120
     */
S
sushuang 已提交
121
    this.id;
S
sushuang 已提交
122

123
    /**
S
sushuang 已提交
124 125
     * Group id
     * @type {string}
126
     */
S
sushuang 已提交
127
    this.group;
S
sushuang 已提交
128

129
    /**
S
sushuang 已提交
130 131
     * @type {HTMLElement}
     * @private
132
     */
S
sushuang 已提交
133
    this._dom = dom;
S
sushuang 已提交
134 135 136 137

    var defaultRenderer = 'canvas';
    if (__DEV__) {
        defaultRenderer = (
P
pissang 已提交
138
            typeof window === 'undefined' ? global : window
S
sushuang 已提交
139 140 141
        ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
    }

L
Tweak  
lang 已提交
142
    /**
S
sushuang 已提交
143 144
     * @type {module:zrender/ZRender}
     * @private
L
Tweak  
lang 已提交
145
     */
S
sushuang 已提交
146
    var zr = this._zr = zrender.init(dom, {
S
sushuang 已提交
147
        renderer: opts.renderer || defaultRenderer,
S
sushuang 已提交
148 149 150 151
        devicePixelRatio: opts.devicePixelRatio,
        width: opts.width,
        height: opts.height
    });
P
pah100 已提交
152

L
tweak  
lang 已提交
153
    /**
S
sushuang 已提交
154 155 156
     * Expect 60 pfs.
     * @type {Function}
     * @private
L
tweak  
lang 已提交
157
     */
S
sushuang 已提交
158
    this._throttledZrFlush = throttle(zrUtil.bind(zr.flush, zr), 17);
L
lang 已提交
159

S
sushuang 已提交
160 161
    var theme = zrUtil.clone(theme);
    theme && backwardCompat(theme, true);
L
lang 已提交
162
    /**
S
sushuang 已提交
163 164
     * @type {Object}
     * @private
L
lang 已提交
165
     */
S
sushuang 已提交
166
    this._theme = theme;
L
lang 已提交
167

L
tweak  
lang 已提交
168
    /**
S
sushuang 已提交
169 170
     * @type {Array.<module:echarts/view/Chart>}
     * @private
L
tweak  
lang 已提交
171
     */
S
sushuang 已提交
172
    this._chartsViews = [];
L
lang 已提交
173

L
tweak  
lang 已提交
174
    /**
S
sushuang 已提交
175 176
     * @type {Object.<string, module:echarts/view/Chart>}
     * @private
L
tweak  
lang 已提交
177
     */
S
sushuang 已提交
178
    this._chartsMap = {};
L
lang 已提交
179

180
    /**
S
sushuang 已提交
181 182
     * @type {Array.<module:echarts/view/Component>}
     * @private
183
     */
S
sushuang 已提交
184
    this._componentsViews = [];
185

L
lang 已提交
186
    /**
S
sushuang 已提交
187 188
     * @type {Object.<string, module:echarts/view/Component>}
     * @private
L
lang 已提交
189
     */
S
sushuang 已提交
190 191
    this._componentsMap = {};

L
lang 已提交
192
    /**
S
sushuang 已提交
193 194
     * @type {module:echarts/CoordinateSystem}
     * @private
L
lang 已提交
195
     */
S
sushuang 已提交
196
    this._coordSysMgr = new CoordinateSystemManager();
L
lang 已提交
197 198

    /**
S
sushuang 已提交
199 200
     * @type {module:echarts/ExtensionAPI}
     * @private
L
lang 已提交
201
     */
S
sushuang 已提交
202
    var api = this._api = createExtensionAPI(this);
L
lang 已提交
203

S
sushuang 已提交
204
    /**
S
tweak  
sushuang 已提交
205
     * @type {module:echarts/stream/Scheduler}
S
sushuang 已提交
206
     */
S
sushuang 已提交
207
    this._scheduler = new Scheduler(this, api);
S
sushuang 已提交
208

S
sushuang 已提交
209
    Eventful.call(this);
210

1
100pah 已提交
211
    /**
S
sushuang 已提交
212 213
     * @type {module:echarts~MessageCenter}
     * @private
1
100pah 已提交
214
     */
S
sushuang 已提交
215
    this._messageCenter = new MessageCenter();
1
100pah 已提交
216

S
sushuang 已提交
217 218
    // this._scheduler = new Scheduler();

S
sushuang 已提交
219 220
    // Init mouse events
    this._initEvents();
1
100pah 已提交
221

S
sushuang 已提交
222 223
    // In case some people write `window.onresize = chart.resize`
    this.resize = zrUtil.bind(this.resize, this);
1
100pah 已提交
224

S
sushuang 已提交
225 226 227 228 229 230 231 232
    // Can't dispatch action during rendering procedure
    this._pendingActions = [];
    // Sort on demand
    function prioritySortFunc(a, b) {
        return a.prio - b.prio;
    }
    timsort(visualFuncs, prioritySortFunc);
    timsort(dataProcessorFuncs, prioritySortFunc);
1
100pah 已提交
233

S
sushuang 已提交
234
    zr.animation.on('frame', this._onframe, this);
1
100pah 已提交
235

S
sushuang 已提交
236 237 238
    // ECharts instance can be used as value.
    zrUtil.setAsPrimitive(this);
}
1
100pah 已提交
239

S
sushuang 已提交
240
var echartsProto = ECharts.prototype;
1
100pah 已提交
241

S
sushuang 已提交
242
echartsProto._onframe = function () {
S
tweak  
sushuang 已提交
243
    if (this._disposed) {
S
sushuang 已提交
244 245 246
        return;
    }

S
sushuang 已提交
247 248 249
    // Lazy update
    if (this[OPTION_UPDATED]) {
        var silent = this[OPTION_UPDATED].silent;
1
100pah 已提交
250

S
sushuang 已提交
251
        this[IN_MAIN_PROCESS] = true;
1
100pah 已提交
252

S
sushuang 已提交
253 254
        prepare(this);
        updateMethods.update.call(this);
1
100pah 已提交
255

S
sushuang 已提交
256
        this[IN_MAIN_PROCESS] = false;
257

S
sushuang 已提交
258
        this[OPTION_UPDATED] = false;
259

S
sushuang 已提交
260
        flushPendingActions.call(this, silent);
261

S
sushuang 已提交
262 263
        triggerUpdatedEvent.call(this, silent);
    }
S
sushuang 已提交
264

S
tweak  
sushuang 已提交
265
    // Stream progress.
S
sushuang 已提交
266
    var remainTime = TEST_FRAME_REMAIN_TIME;
S
tweak  
sushuang 已提交
267
    var scheduler = this._scheduler;
S
sushuang 已提交
268
    var ecModel = this._model;
S
sushuang 已提交
269

S
tweak  
sushuang 已提交
270 271 272 273 274
    if (scheduler.unfinished) {
        scheduler.unfinished = false;
        do {
            var startTime = +new Date();

S
sushuang 已提交
275
            scheduler.performSeriesTasks(ecModel);
S
tweak  
sushuang 已提交
276

S
sushuang 已提交
277 278 279 280
            scheduler.performStageTasks(dataProcessorFuncs, ecModel);

            // ???! coordSys create
            // this._coordSysMgr.update();
S
sushuang 已提交
281

S
sushuang 已提交
282
            // console.log('------------- ec frame visual -------------', remainTime);
S
sushuang 已提交
283
            scheduler.performStageTasks(visualFuncs, ecModel);
S
tweak  
sushuang 已提交
284

S
sushuang 已提交
285
            performRender(this, this._model, this._api);
S
sushuang 已提交
286

S
tweak  
sushuang 已提交
287 288 289
            remainTime -= (+new Date() - startTime);
        }
        while (remainTime > 0 && scheduler.unfinished);
S
sushuang 已提交
290
    }
S
tweak  
sushuang 已提交
291
};
S
sushuang 已提交
292 293


S
sushuang 已提交
294 295 296 297 298 299
/**
 * @return {HTMLElement}
 */
echartsProto.getDom = function () {
    return this._dom;
};
300

S
sushuang 已提交
301 302 303 304 305 306
/**
 * @return {module:zrender~ZRender}
 */
echartsProto.getZr = function () {
    return this._zr;
};
307

S
sushuang 已提交
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
/**
 * Usage:
 * chart.setOption(option, notMerge, lazyUpdate);
 * chart.setOption(option, {
 *     notMerge: ...,
 *     lazyUpdate: ...,
 *     silent: ...
 * });
 *
 * @param {Object} option
 * @param {Object|boolean} [opts] opts or notMerge.
 * @param {boolean} [opts.notMerge=false]
 * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
 */
echartsProto.setOption = function (option, notMerge, lazyUpdate) {
    if (__DEV__) {
S
sushuang 已提交
324
        assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
S
sushuang 已提交
325
    }
326

S
sushuang 已提交
327
    var silent;
S
sushuang 已提交
328
    if (isObject(notMerge)) {
S
sushuang 已提交
329 330 331 332
        lazyUpdate = notMerge.lazyUpdate;
        silent = notMerge.silent;
        notMerge = notMerge.notMerge;
    }
333

S
sushuang 已提交
334
    this[IN_MAIN_PROCESS] = true;
335

S
sushuang 已提交
336 337 338 339
    if (!this._model || notMerge) {
        var optionManager = new OptionManager(this._api);
        var theme = this._theme;
        var ecModel = this._model = new GlobalModel(null, null, theme, optionManager);
S
tweak  
sushuang 已提交
340
        ecModel.scheduler = this._scheduler;
S
sushuang 已提交
341 342
        ecModel.init(null, null, theme, optionManager);
    }
343

S
sushuang 已提交
344
    this._model.setOption(option, optionPreprocessorFuncs);
1
100pah 已提交
345

S
sushuang 已提交
346 347 348 349 350
    if (lazyUpdate) {
        this[OPTION_UPDATED] = {silent: silent};
        this[IN_MAIN_PROCESS] = false;
    }
    else {
S
sushuang 已提交
351 352 353 354
        prepare(this);

        updateMethods.update.call(this);

S
sushuang 已提交
355 356 357
        // Ensure zr refresh sychronously, and then pixel in canvas can be
        // fetched after `setOption`.
        this._zr.flush();
L
lang 已提交
358

S
sushuang 已提交
359 360
        this[OPTION_UPDATED] = false;
        this[IN_MAIN_PROCESS] = false;
L
lang 已提交
361

S
sushuang 已提交
362 363 364 365 366 367 368 369 370 371 372
        flushPendingActions.call(this, silent);
        triggerUpdatedEvent.call(this, silent);
    }
};

/**
 * @DEPRECATED
 */
echartsProto.setTheme = function () {
    console.log('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
};
L
lang 已提交
373

S
sushuang 已提交
374 375 376 377 378 379
/**
 * @return {module:echarts/model/Global}
 */
echartsProto.getModel = function () {
    return this._model;
};
380

S
sushuang 已提交
381 382 383 384 385 386
/**
 * @return {Object}
 */
echartsProto.getOption = function () {
    return this._model && this._model.getOption();
};
P
pah100 已提交
387

S
sushuang 已提交
388 389 390 391 392 393
/**
 * @return {number}
 */
echartsProto.getWidth = function () {
    return this._zr.getWidth();
};
394

S
sushuang 已提交
395 396 397 398 399 400
/**
 * @return {number}
 */
echartsProto.getHeight = function () {
    return this._zr.getHeight();
};
L
lang 已提交
401

S
sushuang 已提交
402 403 404 405 406 407
/**
 * @return {number}
 */
echartsProto.getDevicePixelRatio = function () {
    return this._zr.painter.dpr || window.devicePixelRatio || 1;
};
L
lang 已提交
408

S
sushuang 已提交
409 410 411 412
/**
 * Get canvas which has all thing rendered
 * @param {Object} opts
 * @param {string} [opts.backgroundColor]
S
sushuang 已提交
413
 * @return {string}
S
sushuang 已提交
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
 */
echartsProto.getRenderedCanvas = function (opts) {
    if (!env.canvasSupported) {
        return;
    }
    opts = opts || {};
    opts.pixelRatio = opts.pixelRatio || 1;
    opts.backgroundColor = opts.backgroundColor
        || this._model.get('backgroundColor');
    var zr = this._zr;
    var list = zr.storage.getDisplayList();
    // Stop animations
    zrUtil.each(list, function (el) {
        el.stopAnimation(true);
    });
    return zr.painter.getRenderedCanvas(opts);
};
O
Ovilia 已提交
431

S
sushuang 已提交
432 433 434 435 436 437 438 439
/**
 * Get svg data url
 * @return {string}
 */
echartsProto.getSvgDataUrl = function () {
    if (!env.svgSupported) {
        return;
    }
O
Ovilia 已提交
440

S
sushuang 已提交
441 442 443 444 445 446
    var zr = this._zr;
    var list = zr.storage.getDisplayList();
    // Stop animations
    zrUtil.each(list, function (el) {
        el.stopAnimation(true);
    });
447

S
sushuang 已提交
448 449
    return zr.painter.pathToSvg();
};
450

S
sushuang 已提交
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
/**
 * @return {string}
 * @param {Object} opts
 * @param {string} [opts.type='png']
 * @param {string} [opts.pixelRatio=1]
 * @param {string} [opts.backgroundColor]
 * @param {string} [opts.excludeComponents]
 */
echartsProto.getDataURL = function (opts) {
    opts = opts || {};
    var excludeComponents = opts.excludeComponents;
    var ecModel = this._model;
    var excludesComponentViews = [];
    var self = this;

    each(excludeComponents, function (componentType) {
        ecModel.eachComponent({
            mainType: componentType
        }, function (component) {
            var view = self._componentsMap[component.__viewId];
            if (!view.group.ignore) {
                excludesComponentViews.push(view);
                view.group.ignore = true;
            }
        });
    });
L
lang 已提交
477

S
sushuang 已提交
478 479 480 481 482
    var url = this._zr.painter.getType() === 'svg'
        ? this.getSvgDataUrl()
        : this.getRenderedCanvas(opts).toDataURL(
            'image/' + (opts && opts.type || 'png')
        );
483

S
sushuang 已提交
484 485 486
    each(excludesComponentViews, function (view) {
        view.group.ignore = false;
    });
L
lang 已提交
487

S
sushuang 已提交
488 489
    return url;
};
490

491

S
sushuang 已提交
492 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
/**
 * @return {string}
 * @param {Object} opts
 * @param {string} [opts.type='png']
 * @param {string} [opts.pixelRatio=1]
 * @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 = [];
        var dpr = (opts && opts.pixelRatio) || 1;

        zrUtil.each(instances, function (chart, id) {
            if (chart.group === groupId) {
                var canvas = chart.getRenderedCanvas(
                    zrUtil.clone(opts)
                );
                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
L
lang 已提交
529 530
                });
            }
S
sushuang 已提交
531
        });
L
lang 已提交
532

S
sushuang 已提交
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
        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
L
lang 已提交
550
                }
S
sushuang 已提交
551 552 553 554
            });
            zr.add(img);
        });
        zr.refreshImmediately();
L
lang 已提交
555

S
sushuang 已提交
556 557 558 559 560 561
        return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
    }
    else {
        return this.getDataURL(opts);
    }
};
L
lang 已提交
562

S
sushuang 已提交
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
/**
 * Convert from logical coordinate system to pixel coordinate system.
 * See CoordinateSystem#convertToPixel.
 * @param {string|Object} finder
 *        If string, e.g., 'geo', means {geoIndex: 0}.
 *        If Object, could contain some of these properties below:
 *        {
 *            seriesIndex / seriesId / seriesName,
 *            geoIndex / geoId, geoName,
 *            bmapIndex / bmapId / bmapName,
 *            xAxisIndex / xAxisId / xAxisName,
 *            yAxisIndex / yAxisId / yAxisName,
 *            gridIndex / gridId / gridName,
 *            ... (can be extended)
 *        }
 * @param {Array|number} value
 * @return {Array|number} result
 */
echartsProto.convertToPixel = zrUtil.curry(doConvertPixel, 'convertToPixel');
582

S
sushuang 已提交
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
/**
 * Convert from pixel coordinate system to logical coordinate system.
 * See CoordinateSystem#convertFromPixel.
 * @param {string|Object} finder
 *        If string, e.g., 'geo', means {geoIndex: 0}.
 *        If Object, could contain some of these properties below:
 *        {
 *            seriesIndex / seriesId / seriesName,
 *            geoIndex / geoId / geoName,
 *            bmapIndex / bmapId / bmapName,
 *            xAxisIndex / xAxisId / xAxisName,
 *            yAxisIndex / yAxisId / yAxisName
 *            gridIndex / gridId / gridName,
 *            ... (can be extended)
 *        }
 * @param {Array|number} value
 * @return {Array|number} result
 */
echartsProto.convertFromPixel = zrUtil.curry(doConvertPixel, 'convertFromPixel');
602

S
sushuang 已提交
603 604 605 606
function doConvertPixel(methodName, finder, value) {
    var ecModel = this._model;
    var coordSysList = this._coordSysMgr.getCoordinateSystems();
    var result;
607

S
sushuang 已提交
608
    finder = modelUtil.parseFinder(ecModel, finder);
609

S
sushuang 已提交
610 611 612 613 614 615 616 617
    for (var i = 0; i < coordSysList.length; i++) {
        var coordSys = coordSysList[i];
        if (coordSys[methodName]
            && (result = coordSys[methodName](ecModel, finder, value)) != null
        ) {
            return result;
        }
    }
P
pah100 已提交
618

S
sushuang 已提交
619 620 621 622 623 624
    if (__DEV__) {
        console.warn(
            'No coordinate system that supports ' + methodName + ' found by the given finder.'
        );
    }
}
625

S
sushuang 已提交
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
/**
 * 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:
 *        {
 *            seriesIndex / seriesId / seriesName,
 *            geoIndex / geoId / geoName,
 *            bmapIndex / bmapId / bmapName,
 *            xAxisIndex / xAxisId / xAxisName,
 *            yAxisIndex / yAxisId / yAxisName,
 *            gridIndex / gridId / gridName,
 *            ... (can be extended)
 *        }
 * @param {Array|number} value
 * @return {boolean} result
 */
echartsProto.containPixel = function (finder, value) {
    var ecModel = this._model;
    var result;
646

S
sushuang 已提交
647
    finder = modelUtil.parseFinder(ecModel, finder);
648

S
sushuang 已提交
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
    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.'
                        ));
                    }
                }
668
            }
S
sushuang 已提交
669 670 671 672 673 674 675
            else {
                if (__DEV__) {
                    console.warn(key + ': containPoint is not supported');
                }
            }
        }, this);
    }, this);
676

S
sushuang 已提交
677 678
    return !!result;
};
P
pah100 已提交
679

S
sushuang 已提交
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
/**
 * 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;
697

S
sushuang 已提交
698
    finder = modelUtil.parseFinder(ecModel, finder, {defaultMainType: 'series'});
699

S
sushuang 已提交
700
    var seriesModel = finder.seriesModel;
701

S
sushuang 已提交
702 703 704 705 706
    if (__DEV__) {
        if (!seriesModel) {
            console.warn('There is no specified seires model');
        }
    }
707

S
sushuang 已提交
708
    var data = seriesModel.getData();
709

S
sushuang 已提交
710 711 712 713 714
    var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
        ? finder.dataIndexInside
        : finder.hasOwnProperty('dataIndex')
        ? data.indexOfRawIndex(finder.dataIndex)
        : null;
L
lang 已提交
715

S
sushuang 已提交
716 717 718 719
    return dataIndexInside != null
        ? data.getItemVisual(dataIndexInside, visualType)
        : data.getVisual(visualType);
};
720

S
sushuang 已提交
721 722 723 724 725 726 727 728
/**
 * Get view of corresponding component model
 * @param  {module:echarts/model/Component} componentModel
 * @return {module:echarts/view/Component}
 */
echartsProto.getViewOfComponentModel = function (componentModel) {
    return this._componentsMap[componentModel.__viewId];
};
P
pah100 已提交
729

S
sushuang 已提交
730 731 732 733 734 735 736 737
/**
 * Get view of corresponding series model
 * @param  {module:echarts/model/Series} seriesModel
 * @return {module:echarts/view/Chart}
 */
echartsProto.getViewOfSeriesModel = function (seriesModel) {
    return this._chartsMap[seriesModel.__viewId];
};
P
pah100 已提交
738

S
sushuang 已提交
739
var updateMethods = {
740 741

    /**
S
sushuang 已提交
742
     * @param {Object} payload
743 744
     * @private
     */
S
sushuang 已提交
745 746
    update: function (payload) {
        // console.profile && console.profile('update');
P
pah100 已提交
747

S
sushuang 已提交
748 749 750
        var ecModel = this._model;
        var api = this._api;
        var zr = this._zr;
S
sushuang 已提交
751
        var coordSysMgr = this._coordSysMgr;
S
tweak  
sushuang 已提交
752 753
        var scheduler = this._scheduler;

S
sushuang 已提交
754 755
        // update before setOption
        if (!ecModel) {
P
pah100 已提交
756 757 758
            return;
        }

S
sushuang 已提交
759 760
        // Fixme First time update ?
        ecModel.restoreData();
S
sushuang 已提交
761
        scheduler.performSeriesTasks(ecModel);
762

S
sushuang 已提交
763 764 765
        // 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.
1
100pah 已提交
766

S
sushuang 已提交
767 768
        // Create new coordinate system each update
        // In LineView may save the old coordinate system and use it to get the orignal point
S
sushuang 已提交
769 770
        coordSysMgr.create(ecModel, api);
        // ??? coord data travel
P
pah100 已提交
771

S
tweak  
sushuang 已提交
772 773 774
        // ??? if some processor do not use task, it should also process in progress,
        // otherwise, consider data extent, both dependent.

S
sushuang 已提交
775
        scheduler.performStageTasks(dataProcessorFuncs, ecModel, payload);
776

S
sushuang 已提交
777
        stackSeriesData.call(this, ecModel);
778

S
sushuang 已提交
779
        // ??? coord data travel
S
sushuang 已提交
780
        coordSysMgr.update(ecModel, api);
P
pah100 已提交
781

S
sushuang 已提交
782 783
        clearColorPalette(ecModel);
        scheduler.performStageTasks(visualFuncs, ecModel, payload);
784

S
sushuang 已提交
785
        performRender(this, ecModel, api, payload, true);
S
tweak  
sushuang 已提交
786

S
sushuang 已提交
787 788
        // Set background
        var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
L
lang 已提交
789

S
sushuang 已提交
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
        var painter = zr.painter;
        // TODO all use clearColor ?
        if (painter.isSingleCanvas && painter.isSingleCanvas()) {
            zr.configLayer(0, {
                clearColor: backgroundColor
            });
        }
        else {
            // In IE8
            if (!env.canvasSupported) {
                var colorArr = colorTool.parse(backgroundColor);
                backgroundColor = colorTool.stringify(colorArr, 'rgb');
                if (colorArr[3] === 0) {
                    backgroundColor = 'transparent';
                }
            }
            if (backgroundColor.colorStops || backgroundColor.image) {
                // Gradient background
                // FIXME Fixed layer?
                zr.configLayer(0, {
                    clearColor: backgroundColor
                });
                this[HAS_GRADIENT_OR_PATTERN_BG] = true;
813

S
sushuang 已提交
814 815 816 817 818 819 820 821 822
                this._dom.style.background = 'transparent';
            }
            else {
                if (this[HAS_GRADIENT_OR_PATTERN_BG]) {
                    zr.configLayer(0, {
                        clearColor: null
                    });
                }
                this[HAS_GRADIENT_OR_PATTERN_BG] = false;
L
lang 已提交
823

S
sushuang 已提交
824 825 826
                this._dom.style.background = backgroundColor;
            }
        }
827

S
sushuang 已提交
828
        performPostUpdateFuncs(ecModel, api);
829

S
sushuang 已提交
830 831
        // console.profile && console.profileEnd('update');
    },
L
lang 已提交
832 833

    /**
S
sushuang 已提交
834 835
     * @param {Object} payload
     * @private
L
lang 已提交
836
     */
S
sushuang 已提交
837 838
    updateView: function (payload) {
        var ecModel = this._model;
839

S
sushuang 已提交
840 841
        // update before setOption
        if (!ecModel) {
L
lang 已提交
842 843
            return;
        }
L
lang 已提交
844

S
sushuang 已提交
845
        ChartView.markUpdateMethod(payload, 'updateView');
S
tweak  
sushuang 已提交
846

S
sushuang 已提交
847
        clearColorPalette(ecModel);
L
lang 已提交
848

S
tweak  
sushuang 已提交
849
        // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
S
sushuang 已提交
850
        this._scheduler.performStageTasks(visualFuncs, ecModel, payload, null, true);
P
pah100 已提交
851

S
sushuang 已提交
852
        performRender(this, this._model, this._api, payload, true);
S
tweak  
sushuang 已提交
853

S
sushuang 已提交
854
        performPostUpdateFuncs(ecModel, this._api);
S
sushuang 已提交
855
    },
L
lang 已提交
856

L
tweak  
lang 已提交
857 858
    /**
     * @param {Object} payload
S
sushuang 已提交
859
     * @private
L
tweak  
lang 已提交
860
     */
S
sushuang 已提交
861 862
    updateVisual: function (payload) {
        var ecModel = this._model;
863

S
sushuang 已提交
864 865
        // update before setOption
        if (!ecModel) {
866 867
            return;
        }
L
lang 已提交
868

S
sushuang 已提交
869
        ChartView.markUpdateMethod(payload, 'updateVisual');
S
tweak  
sushuang 已提交
870

S
sushuang 已提交
871
        clearColorPalette(ecModel);
872

S
tweak  
sushuang 已提交
873
        // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
S
sushuang 已提交
874
        this._scheduler.performStageTasks(visualFuncs, ecModel, payload, 'visual', true);
875

S
sushuang 已提交
876
        performRender(this, this._model, this._api, payload, true);
S
tweak  
sushuang 已提交
877

S
sushuang 已提交
878
        performPostUpdateFuncs(ecModel, this._api);
S
sushuang 已提交
879
    },
1
tweak  
100pah 已提交
880

S
sushuang 已提交
881 882 883 884 885 886 887 888 889 890
    /**
     * @param {Object} payload
     * @private
     */
    updateLayout: function (payload) {
        var ecModel = this._model;

        // update before setOption
        if (!ecModel) {
            return;
1
100pah 已提交
891
        }
892

S
sushuang 已提交
893
        ChartView.markUpdateMethod(payload, 'updateLayout');
S
tweak  
sushuang 已提交
894

S
tweak  
sushuang 已提交
895
        // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
S
sushuang 已提交
896 897
        // this._scheduler.performStageTasks(visualFuncs, ecModel, payload, 'layout', true);
        this._scheduler.performStageTasks(visualFuncs, ecModel, payload, null, true);
898

S
sushuang 已提交
899
        performRender(this, this._model, this._api, payload, true);
S
tweak  
sushuang 已提交
900

S
sushuang 已提交
901 902 903
        performPostUpdateFuncs(ecModel, this._api);
    }
};
S
sushuang 已提交
904

S
sushuang 已提交
905 906 907
function prepare(ecIns, payload, pipelineTails) {
    var ecModel = ecIns._model;
    var scheduler = ecIns._scheduler;
1
tweak  
100pah 已提交
908

S
sushuang 已提交
909 910 911 912
    var pipelineTails = createHashMap();
    ecModel.eachSeries(function (seriesModel) {
        pipelineTails.set(seriesModel.uid, seriesModel.dataRestoreTask);
    });
1
100pah 已提交
913

S
sushuang 已提交
914
    scheduler.prepareStageTasks(dataProcessorFuncs, pipelineTails);
1
tweak  
100pah 已提交
915

S
sushuang 已提交
916 917 918 919 920 921
    scheduler.prepareStageTasks(visualFuncs, pipelineTails);

    prepareView(ecIns, 'component', ecModel, pipelineTails);

    prepareView(ecIns, 'chart', ecModel, pipelineTails);
}
L
lang 已提交
922

S
sushuang 已提交
923 924 925 926 927
/**
 * @private
 */
function updateDirectly(ecIns, method, payload, mainType, subType) {
    var ecModel = ecIns._model;
P
pah100 已提交
928

S
sushuang 已提交
929 930 931 932 933
    // broadcast
    if (!mainType) {
        each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
        return;
    }
934

S
sushuang 已提交
935 936 937 938
    var query = {};
    query[mainType + 'Id'] = payload[mainType + 'Id'];
    query[mainType + 'Index'] = payload[mainType + 'Index'];
    query[mainType + 'Name'] = payload[mainType + 'Name'];
939

S
sushuang 已提交
940 941
    var condition = {mainType: mainType, query: query};
    subType && (condition.subType = subType); // subType may be '' by parseClassType;
942

S
sushuang 已提交
943 944 945 946 947 948
    // If dispatchAction before setOption, do nothing.
    ecModel && ecModel.eachComponent(condition, function (model, index) {
        callView(ecIns[
            mainType === 'series' ? '_chartsMap' : '_componentsMap'
        ][model.__viewId]);
    }, ecIns);
949

S
sushuang 已提交
950 951 952 953
    function callView(view) {
        view && view.__alive && view[method] && view[method](
            view.__model, ecModel, ecIns._api, payload
        );
1
tweak  
100pah 已提交
954
    }
S
sushuang 已提交
955
}
L
tweak  
lang 已提交
956

S
sushuang 已提交
957 958 959 960 961 962 963 964 965
/**
 * Resize the chart
 * @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)
 * @param {boolean} [opts.silent=false]
 */
echartsProto.resize = function (opts) {
    if (__DEV__) {
S
sushuang 已提交
966
        assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
1
tweak  
100pah 已提交
967
    }
L
lang 已提交
968

S
sushuang 已提交
969
    this._zr.resize(opts);
L
lang 已提交
970

S
sushuang 已提交
971 972 973 974 975 976 977 978 979 980
    var ecModel = this._model;

    var optionChanged = ecModel && ecModel.resetOption('media');

    optionChanged && ecModel.settingTask.dirty();

    ecModel.eachComponent(function (model, componentType) {
        optionChanged && model.settingTask.dirty();
        model.dataInitTask && model.dataInitTask.dirty();
    });
L
lang 已提交
981

S
sushuang 已提交
982
    refresh(this, optionChanged, opts && opts.silent);
S
sushuang 已提交
983 984
};

S
sushuang 已提交
985
function refresh(ecIns, needPrepare, silent) {
S
tweak  
sushuang 已提交
986
    ecIns[IN_MAIN_PROCESS] = true;
S
sushuang 已提交
987

S
sushuang 已提交
988 989
    needPrepare && prepare(ecIns);
    updateMethods.update.call(ecIns);
990

S
sushuang 已提交
991
    // Resize loading effect
S
tweak  
sushuang 已提交
992
    ecIns._loadingFX && ecIns._loadingFX.resize();
L
lang 已提交
993

S
tweak  
sushuang 已提交
994
    ecIns[IN_MAIN_PROCESS] = false;
995

S
tweak  
sushuang 已提交
996
    flushPendingActions.call(ecIns, silent);
997

S
tweak  
sushuang 已提交
998
    triggerUpdatedEvent.call(ecIns, silent);
S
sushuang 已提交
999
}
1000

S
sushuang 已提交
1001 1002 1003 1004 1005 1006
/**
 * Show loading effect
 * @param  {string} [name='default']
 * @param  {Object} [cfg]
 */
echartsProto.showLoading = function (name, cfg) {
S
sushuang 已提交
1007
    if (isObject(name)) {
S
sushuang 已提交
1008 1009
        cfg = name;
        name = '';
1010
    }
S
sushuang 已提交
1011
    name = name || 'default';
L
lang 已提交
1012

S
sushuang 已提交
1013 1014 1015 1016
    this.hideLoading();
    if (!loadingEffects[name]) {
        if (__DEV__) {
            console.warn('Loading effects ' + name + ' not exists.');
L
tweak  
lang 已提交
1017
        }
S
sushuang 已提交
1018 1019 1020 1021 1022
        return;
    }
    var el = loadingEffects[name](this._api, cfg);
    var zr = this._zr;
    this._loadingFX = el;
L
lang 已提交
1023

S
sushuang 已提交
1024 1025
    zr.add(el);
};
L
tweak  
lang 已提交
1026

S
sushuang 已提交
1027 1028 1029 1030 1031 1032 1033
/**
 * Hide loading effect
 */
echartsProto.hideLoading = function () {
    this._loadingFX && this._zr.remove(this._loadingFX);
    this._loadingFX = null;
};
L
Tweak  
lang 已提交
1034

S
sushuang 已提交
1035 1036 1037 1038 1039 1040 1041 1042 1043
/**
 * @param {Object} eventObj
 * @return {Object}
 */
echartsProto.makeActionFromEvent = function (eventObj) {
    var payload = zrUtil.extend({}, eventObj);
    payload.type = eventActionMap[eventObj.type];
    return payload;
};
L
tweak  
lang 已提交
1044

S
sushuang 已提交
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
/**
 * @pubilc
 * @param {Object} payload
 * @param {string} [payload.type] Action type
 * @param {Object|boolean} [opt] If pass boolean, means opt.silent
 * @param {boolean} [opt.silent=false] Whether trigger events.
 * @param {boolean} [opt.flush=undefined]
 *                  true: Flush immediately, and then pixel in canvas can be fetched
 *                      immediately. Caution: it might affect performance.
 *                  false: Not not flush.
 *                  undefined: Auto decide whether perform flush.
 */
echartsProto.dispatchAction = function (payload, opt) {
S
sushuang 已提交
1058
    if (!isObject(opt)) {
S
sushuang 已提交
1059
        opt = {silent: !!opt};
1060 1061
    }

S
sushuang 已提交
1062 1063
    if (!actions[payload.type]) {
        return;
1064
    }
L
lang 已提交
1065

S
sushuang 已提交
1066 1067 1068
    // Avoid dispatch action before setOption. Especially in `connect`.
    if (!this._model) {
        return;
1069
    }
L
lang 已提交
1070

S
sushuang 已提交
1071 1072 1073 1074
    // May dispatchAction in rendering procedure
    if (this[IN_MAIN_PROCESS]) {
        this._pendingActions.push(payload);
        return;
1075
    }
L
lang 已提交
1076

S
sushuang 已提交
1077
    doDispatchAction.call(this, payload, opt.silent);
L
lang 已提交
1078

S
sushuang 已提交
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
    if (opt.flush) {
        this._zr.flush(true);
    }
    else if (opt.flush !== false && env.browser.weChat) {
        // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
        // hang when sliding page (on touch event), which cause that zr does not
        // refresh util user interaction finished, which is not expected.
        // But `dispatchAction` may be called too frequently when pan on touch
        // screen, which impacts performance if do not throttle them.
        this._throttledZrFlush();
    }
L
tweak  
lang 已提交
1090

S
sushuang 已提交
1091
    flushPendingActions.call(this, opt.silent);
L
tweak  
lang 已提交
1092

S
sushuang 已提交
1093 1094
    triggerUpdatedEvent.call(this, opt.silent);
};
L
tweak  
lang 已提交
1095

S
sushuang 已提交
1096 1097 1098 1099 1100
function doDispatchAction(payload, silent) {
    var payloadType = payload.type;
    var escapeConnect = payload.escapeConnect;
    var actionWrap = actions[payloadType];
    var actionInfo = actionWrap.actionInfo;
L
tweak  
lang 已提交
1101

S
sushuang 已提交
1102 1103 1104
    var cptType = (actionInfo.update || 'update').split(':');
    var updateMethod = cptType.pop();
    cptType = cptType[0] != null && parseClassType(cptType[0]);
L
lang 已提交
1105

S
sushuang 已提交
1106
    this[IN_MAIN_PROCESS] = true;
1107

S
sushuang 已提交
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
    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;
        });
    }
L
lang 已提交
1119

S
sushuang 已提交
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
    var eventObjBatch = [];
    var eventObj;
    var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';

    each(payloads, function (batchItem) {
        // Action can specify the event by return it.
        eventObj = actionWrap.action(batchItem, this._model, this._api);
        // Emit event outside
        eventObj = eventObj || zrUtil.extend({}, batchItem);
        // Convert type to eventType
        eventObj.type = actionInfo.event || eventObj.type;
        eventObjBatch.push(eventObj);

        // light update does not perform data process, layout and visual.
        if (isHighDown) {
            // method, payload, mainType, subType
            updateDirectly(this, updateMethod, batchItem, 'series');
        }
        else if (cptType) {
            updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
        }
    }, this);
L
tweak  
lang 已提交
1142

S
sushuang 已提交
1143 1144 1145 1146
    if (updateMethod !== 'none' && !isHighDown && !cptType) {
        // Still dirty
        if (this[OPTION_UPDATED]) {
            // FIXME Pass payload ?
S
sushuang 已提交
1147 1148
            prepare(this);
            updateMethods.update.call(this, payload);
S
sushuang 已提交
1149 1150 1151 1152 1153 1154
            this[OPTION_UPDATED] = false;
        }
        else {
            updateMethods[updateMethod].call(this, payload);
        }
    }
1155

S
sushuang 已提交
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
    // Follow the rule of action batch
    if (batched) {
        eventObj = {
            type: actionInfo.event || payloadType,
            escapeConnect: escapeConnect,
            batch: eventObjBatch
        };
    }
    else {
        eventObj = eventObjBatch[0];
1166
    }
L
lang 已提交
1167

S
sushuang 已提交
1168
    this[IN_MAIN_PROCESS] = false;
1
100pah 已提交
1169

S
sushuang 已提交
1170 1171
    !silent && this._messageCenter.trigger(eventObj.type, eventObj);
}
1
100pah 已提交
1172

S
sushuang 已提交
1173 1174 1175 1176 1177 1178 1179
function flushPendingActions(silent) {
    var pendingActions = this._pendingActions;
    while (pendingActions.length) {
        var payload = pendingActions.shift();
        doDispatchAction.call(this, payload, silent);
    }
}
L
lang 已提交
1180

S
sushuang 已提交
1181 1182 1183
function triggerUpdatedEvent(silent) {
    !silent && this.trigger('updated');
}
L
lang 已提交
1184

S
tweak  
sushuang 已提交
1185 1186 1187 1188
// ???
echartsProto.addData = function (params) {
    var seriesIndex = params.seriesIndex;
    var ecModel = this.getModel();
S
sushuang 已提交
1189
    var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
S
sushuang 已提交
1190

S
tweak  
sushuang 已提交
1191
    if (__DEV__) {
S
sushuang 已提交
1192
        assert(params.data && seriesModel);
S
tweak  
sushuang 已提交
1193
    }
S
sushuang 已提交
1194

S
sushuang 已提交
1195 1196 1197 1198 1199
    var provider = seriesModel.getRawData().getProvider();
    // .provisionTask.changeInput(params.data);
    provider.addData(params.data);

    this._scheduler.unfinished = true;
S
tweak  
sushuang 已提交
1200
};
S
sushuang 已提交
1201

S
sushuang 已提交
1202 1203 1204 1205 1206 1207 1208
/**
 * Register event
 * @method
 */
echartsProto.on = createRegisterEventWithLowercaseName('on');
echartsProto.off = createRegisterEventWithLowercaseName('off');
echartsProto.one = createRegisterEventWithLowercaseName('one');
L
lang 已提交
1209

S
sushuang 已提交
1210 1211 1212 1213 1214
/**
 * Prepare view instances of charts and components
 * @param  {module:echarts/model/Global} ecModel
 * @private
 */
S
sushuang 已提交
1215
function prepareView(ecIns, type, ecModel, pipelineTails) {
S
sushuang 已提交
1216
    var isComponent = type === 'component';
S
sushuang 已提交
1217 1218 1219 1220
    var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
    var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
    var zr = ecIns._zr;
    var api = ecIns._api;
S
sushuang 已提交
1221 1222 1223

    for (var i = 0; i < viewList.length; i++) {
        viewList[i].__alive = false;
1224
    }
1225

S
sushuang 已提交
1226 1227 1228 1229 1230
    isComponent
        ? ecModel.eachComponent(function (componentType, model) {
            componentType !== 'series' && doPrepare(model);
        })
        : ecModel.eachSeries(doPrepare);
1231

S
sushuang 已提交
1232
    function doPrepare(model) {
S
sushuang 已提交
1233 1234 1235 1236 1237 1238 1239 1240
        // Consider: id same and type changed.
        var viewId = '_ec_' + model.id + '_' + model.type;
        var view = viewMap[viewId];
        if (!view) {
            var classType = parseClassType(model.type);
            var Clazz = isComponent
                ? ComponentView.getClass(classType.main, classType.sub)
                : ChartView.getClass(classType.sub);
S
sushuang 已提交
1241 1242

            if (__DEV__) {
S
sushuang 已提交
1243
                assert(Clazz, classType.sub + ' does not exist.');
1244
            }
S
sushuang 已提交
1245 1246

            view = new Clazz();
S
sushuang 已提交
1247
            view.init(ecModel, api);
S
sushuang 已提交
1248 1249 1250
            viewMap[viewId] = view;
            viewList.push(view);
            zr.add(view.group);
S
sushuang 已提交
1251
        }
1252

S
sushuang 已提交
1253 1254 1255 1256 1257 1258 1259
        model.__viewId = view.__id = viewId;
        view.__alive = true;
        view.__model = model;
        view.group.__ecComponentInfo = {
            mainType: model.mainType,
            index: model.componentIndex
        };
S
sushuang 已提交
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
        if (!isComponent) {
            var renderTask = view.renderTask;
            renderTask.context.model = model;
            renderTask.context.ecModel = ecModel;
            renderTask.context.api = api;
            var pipelineId = model.uid;
            pipelineTails.get(pipelineId).pipe(renderTask);
            pipelineTails.set(pipelineId, renderTask);
        }
    }
S
sushuang 已提交
1270 1271 1272 1273

    for (var i = 0; i < viewList.length;) {
        var view = viewList[i];
        if (!view.__alive) {
S
sushuang 已提交
1274
            view.renderTask.dispose();
S
sushuang 已提交
1275
            zr.remove(view.group);
S
sushuang 已提交
1276
            view.dispose(ecModel, api);
S
sushuang 已提交
1277 1278 1279 1280 1281 1282 1283
            viewList.splice(i, 1);
            delete viewMap[view.__id];
            view.__id = view.group.__ecComponentInfo = null;
        }
        else {
            i++;
        }
L
lang 已提交
1284
    }
S
sushuang 已提交
1285
}
1286

S
sushuang 已提交
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
/**
 * @private
 */
function stackSeriesData(ecModel) {
    var stackedDataMap = {};
    ecModel.eachSeries(function (series) {
        var stack = series.get('stack');
        var data = series.getData();
        if (stack && data.type === 'list') {
            var previousStack = stackedDataMap[stack];
            // Avoid conflict with Object.prototype
            if (stackedDataMap.hasOwnProperty(stack) && previousStack) {
                data.stackedOn = previousStack;
            }
            stackedDataMap[stack] = data;
        }
    });
}
P
pah100 已提交
1305

S
sushuang 已提交
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
// /**
//  * Encode visual infomation from data after data processing
//  *
//  * @param {module:echarts/model/Global} ecModel
//  * @param {object} layout
//  * @param {boolean} [layoutFilter] `true`: only layout,
//  *                                 `false`: only not layout,
//  *                                 `null`/`undefined`: all.
//  * @param {string} taskBaseTag
//  * @private
//  */
// function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
//     each(visualFuncs, function (visual, index) {
//         var isLayout = visual.isLayout;
//         if (layoutFilter == null
//             || (layoutFilter === false && !isLayout)
//             || (layoutFilter === true && isLayout)
//         ) {
//             visual.func(ecModel, api, payload);
//         }
//     });
// }

function clearColorPalette(ecModel) {
    ecModel.clearColorPalette();
    ecModel.eachSeries(function (seriesModel) {
        seriesModel.clearColorPalette();
S
sushuang 已提交
1333
    });
S
sushuang 已提交
1334 1335
}

S
sushuang 已提交
1336 1337 1338 1339
/**
 * Render each chart and component
 * @private
 */
S
sushuang 已提交
1340 1341 1342 1343 1344 1345
function performRender(ecIns, ecModel, api, payload, isReset) {
    if (isReset) {
        // Render all components
        each(ecIns._componentsViews, function (componentView) {
            var componentModel = componentView.__model;
            componentView.render(componentModel, ecModel, api, payload);
1346

S
sushuang 已提交
1347 1348
            updateZ(componentModel, componentView);
        });
1349

S
sushuang 已提交
1350 1351 1352 1353
        each(ecIns._chartsViews, function (chart) {
            chart.__alive = false;
        });
    }
S
sushuang 已提交
1354

S
sushuang 已提交
1355
    // Render all charts
S
sushuang 已提交
1356 1357 1358
    var scheduler = ecIns._scheduler;
    var step = scheduler.getStep();
    var unfinished;
S
tweak  
sushuang 已提交
1359
    ecModel.eachSeries(function (seriesModel) {
S
sushuang 已提交
1360
        var chartView = ecIns._chartsMap[seriesModel.__viewId];
S
sushuang 已提交
1361
        chartView.__alive = true;
L
lang 已提交
1362

S
sushuang 已提交
1363 1364
        unfinished |= chartView.renderTask.perform({step: step}, {payload: payload});
        // chartView.render(seriesModel, ecModel, api, payload);
L
lang 已提交
1365

S
sushuang 已提交
1366
        chartView.group.silent = !!seriesModel.get('silent');
P
pah100 已提交
1367

S
sushuang 已提交
1368
        updateZ(seriesModel, chartView);
S
sushuang 已提交
1369

S
sushuang 已提交
1370 1371
        // ??? updateProgressiveAndBlend(seriesModel, chartView);
    });
S
sushuang 已提交
1372
    scheduler.unfinished |= unfinished;
S
sushuang 已提交
1373 1374

    // If use hover layer
S
sushuang 已提交
1375
    // ??? updateHoverLayerStatus(this._zr, ecModel);
S
sushuang 已提交
1376

S
sushuang 已提交
1377 1378 1379 1380 1381 1382 1383 1384
    if (isReset) {
        // Remove groups of unrendered charts
        each(ecIns._chartsViews, function (chart) {
            if (!chart.__alive) {
                chart.remove(ecModel, api);
            }
        });
    }
S
sushuang 已提交
1385 1386
}

S
sushuang 已提交
1387 1388 1389
function performPostUpdateFuncs(ecModel, api) {
    each(postUpdateFuncs, function (func) {
        func(ecModel, api);
S
sushuang 已提交
1390
    });
S
tweak  
sushuang 已提交
1391 1392
}

S
sushuang 已提交
1393

S
sushuang 已提交
1394 1395 1396 1397
var MOUSE_EVENT_NAMES = [
    'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
    'mousedown', 'mouseup', 'globalout', 'contextmenu'
];
S
sushuang 已提交
1398

S
sushuang 已提交
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
/**
 * @private
 */
echartsProto._initEvents = function () {
    each(MOUSE_EVENT_NAMES, function (eveName) {
        this._zr.on(eveName, function (e) {
            var ecModel = this.getModel();
            var el = e.target;
            var params;

            // no e.target when 'globalout'.
            if (eveName === 'globalout') {
                params = {};
            }
            else if (el && el.dataIndex != null) {
                var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
                params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType) || {};
            }
            // If element has custom eventData of components
            else if (el && el.eventData) {
                params = zrUtil.extend({}, el.eventData);
            }
P
pah100 已提交
1421

S
sushuang 已提交
1422 1423 1424 1425
            if (params) {
                params.event = e;
                params.type = eveName;
                this.trigger(eveName, params);
L
lang 已提交
1426
            }
S
sushuang 已提交
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458

        }, this);
    }, this);

    each(eventActionMap, function (actionType, eventType) {
        this._messageCenter.on(eventType, function (event) {
            this.trigger(eventType, event);
        }, this);
    }, this);
};

/**
 * @return {boolean}
 */
echartsProto.isDisposed = function () {
    return this._disposed;
};

/**
 * Clear
 */
echartsProto.clear = function () {
    this.setOption({ series: [] }, true);
};

/**
 * Dispose instance
 */
echartsProto.dispose = function () {
    if (this._disposed) {
        if (__DEV__) {
            console.warn('Instance ' + this.id + ' has been disposed');
L
lang 已提交
1459
        }
S
sushuang 已提交
1460 1461 1462
        return;
    }
    this._disposed = true;
P
pah100 已提交
1463

S
sushuang 已提交
1464 1465
    modelUtil.setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');

S
sushuang 已提交
1466 1467
    var api = this._api;
    var ecModel = this._model;
P
pah100 已提交
1468

S
sushuang 已提交
1469 1470 1471 1472 1473 1474
    each(this._componentsViews, function (component) {
        component.dispose(ecModel, api);
    });
    each(this._chartsViews, function (chart) {
        chart.dispose(ecModel, api);
    });
1
100pah 已提交
1475

S
sushuang 已提交
1476 1477
    // Dispose after all views disposed
    this._zr.dispose();
1
100pah 已提交
1478

S
sushuang 已提交
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
    delete instances[this.id];
};

zrUtil.mixin(ECharts, Eventful);

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;
            }
L
lang 已提交
1497 1498
        });
    }
S
sushuang 已提交
1499
}
P
pah100 已提交
1500

S
sushuang 已提交
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
/**
 * 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);
                }
1525
            }
S
sushuang 已提交
1526 1527
        });
    }
P
pah100 已提交
1528

S
sushuang 已提交
1529
    // Blend configration
S
sushuang 已提交
1530
    // ???
S
sushuang 已提交
1531 1532 1533 1534
    var blendMode = seriesModel.get('blendMode') || null;
    if (__DEV__) {
        if (!env.canvasSupported && blendMode && blendMode !== 'source-over') {
            console.warn('Only canvas support blendMode');
P
pah100 已提交
1535
        }
S
sushuang 已提交
1536 1537 1538 1539 1540 1541 1542 1543
    }
    chartView.group.traverse(function (el) {
        // FIXME marker and other components
        if (!el.isGroup) {
            el.setStyle('blend', blendMode);
        }
    });
}
P
pah100 已提交
1544

S
sushuang 已提交
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
/**
 * @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) {
        if (el.type !== 'group') {
            z != null && (el.z = z);
            zlevel != null && (el.zlevel = zlevel);
P
pah100 已提交
1557
        }
S
sushuang 已提交
1558 1559
    });
}
P
pah100 已提交
1560

S
sushuang 已提交
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
function createExtensionAPI(ecInstance) {
    var coordSysMgr = ecInstance._coordSysMgr;
    return zrUtil.extend(new ExtensionAPI(ecInstance), {
        // Inject methods
        getCoordinateSystems: zrUtil.bind(
            coordSysMgr.getCoordinateSystems, coordSysMgr
        ),
        getComponentByElement: function (el) {
            while (el) {
                var modelInfo = el.__ecComponentInfo;
                if (modelInfo != null) {
                    return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
                }
                el = el.parent;
1575
            }
1576
        }
S
sushuang 已提交
1577 1578
    });
}
L
lang 已提交
1579

S
sushuang 已提交
1580 1581 1582 1583 1584
/**
 * @type {Object} key: actionType.
 * @inner
 */
var actions = {};
L
lang 已提交
1585

S
sushuang 已提交
1586 1587 1588 1589 1590
/**
 * Map eventType to actionType
 * @type {Object}
 */
var eventActionMap = {};
L
lang 已提交
1591

S
sushuang 已提交
1592 1593 1594 1595 1596 1597
/**
 * Data processor functions of each stage
 * @type {Array.<Object.<string, Function>>}
 * @inner
 */
var dataProcessorFuncs = [];
L
lang 已提交
1598

S
sushuang 已提交
1599 1600 1601 1602 1603
/**
 * @type {Array.<Function>}
 * @inner
 */
var optionPreprocessorFuncs = [];
L
lang 已提交
1604

S
sushuang 已提交
1605 1606 1607 1608 1609
/**
 * @type {Array.<Function>}
 * @inner
 */
var postUpdateFuncs = [];
L
lang 已提交
1610

S
sushuang 已提交
1611 1612 1613 1614 1615
/**
 * Visual encoding functions of each stage
 * @type {Array.<Object.<string, Function>>}
 */
var visualFuncs = [];
S
sushuang 已提交
1616

S
sushuang 已提交
1617 1618 1619 1620 1621 1622 1623 1624 1625
/**
 * Theme storage
 * @type {Object.<key, Object>}
 */
var themeStorage = {};
/**
 * Loading effects
 */
var loadingEffects = {};
L
lang 已提交
1626

S
sushuang 已提交
1627 1628 1629 1630 1631 1632 1633
var instances = {};
var connectedGroups = {};

var idBase = new Date() - 0;
var groupIdBase = new Date() - 0;
var DOM_ATTRIBUTE_KEY = '_echarts_instance_';

S
sushuang 已提交
1634 1635
var mapDataStores = {};

S
sushuang 已提交
1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
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;
L
lang 已提交
1646
        }
S
sushuang 已提交
1647 1648
    }

S
sushuang 已提交
1649
    each(eventActionMap, function (actionType, eventType) {
S
sushuang 已提交
1650 1651 1652 1653 1654 1655 1656 1657 1658
        chart._messageCenter.on(eventType, function (event) {
            if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
                if (event && event.escapeConnect) {
                    return;
                }

                var action = chart.makeActionFromEvent(event);
                var otherCharts = [];

S
sushuang 已提交
1659
                each(instances, function (otherChart) {
S
sushuang 已提交
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
                    if (otherChart !== chart && otherChart.group === chart.group) {
                        otherCharts.push(otherChart);
                    }
                });

                updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
                each(otherCharts, function (otherChart) {
                    if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
                        otherChart.dispatchAction(action);
                    }
                });
                updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
            }
        });
    });
}

/**
 * @param {HTMLElement} dom
 * @param {Object} [theme]
 * @param {Object} opts
 * @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)
 */
S
sushuang 已提交
1688
export function init(dom, theme, opts) {
S
sushuang 已提交
1689 1690
    if (__DEV__) {
        // Check version
S
sushuang 已提交
1691
        if ((zrender.version.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
S
sushuang 已提交
1692
            throw new Error(
S
sushuang 已提交
1693
                'zrender/src ' + zrender.version
S
sushuang 已提交
1694
                + ' is too old for ECharts ' + version
S
sushuang 已提交
1695
                + '. Current version need ZRender '
S
sushuang 已提交
1696
                + dependencies.zrender + '+'
S
sushuang 已提交
1697
            );
P
pissang 已提交
1698
        }
S
sushuang 已提交
1699 1700 1701

        if (!dom) {
            throw new Error('Initialize failed: invalid dom.');
L
lang 已提交
1702
        }
S
sushuang 已提交
1703
    }
L
lang 已提交
1704

S
sushuang 已提交
1705
    var existInstance = getInstanceByDom(dom);
S
sushuang 已提交
1706 1707 1708
    if (existInstance) {
        if (__DEV__) {
            console.warn('There is a chart instance already initialized on the dom.');
P
pissang 已提交
1709
        }
S
sushuang 已提交
1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
        return existInstance;
    }

    if (__DEV__) {
        if (zrUtil.isDom(dom)
            && dom.nodeName.toUpperCase() !== 'CANVAS'
            && (
                (!dom.clientWidth && (!opts || opts.width == null))
                || (!dom.clientHeight && (!opts || opts.height == null))
            )
        ) {
            console.warn('Can\'t get dom width or height');
P
pissang 已提交
1722
        }
S
sushuang 已提交
1723
    }
P
pah100 已提交
1724

S
sushuang 已提交
1725 1726 1727
    var chart = new ECharts(dom, theme, opts);
    chart.id = 'ec_' + idBase++;
    instances[chart.id] = chart;
L
lang 已提交
1728

S
sushuang 已提交
1729
    modelUtil.setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
L
lang 已提交
1730

S
sushuang 已提交
1731
    enableConnect(chart);
1732

S
sushuang 已提交
1733
    return chart;
S
sushuang 已提交
1734
}
S
sushuang 已提交
1735 1736 1737 1738

/**
 * @return {string|Array.<module:echarts~ECharts>} groupId
 */
S
sushuang 已提交
1739
export function connect(groupId) {
S
sushuang 已提交
1740 1741 1742 1743 1744
    // Is array of charts
    if (zrUtil.isArray(groupId)) {
        var charts = groupId;
        groupId = null;
        // If any chart has group
S
sushuang 已提交
1745
        each(charts, function (chart) {
S
sushuang 已提交
1746 1747
            if (chart.group != null) {
                groupId = chart.group;
1748
            }
1749
        });
S
sushuang 已提交
1750
        groupId = groupId || ('g_' + groupIdBase++);
S
sushuang 已提交
1751
        each(charts, function (chart) {
S
sushuang 已提交
1752 1753 1754 1755 1756
            chart.group = groupId;
        });
    }
    connectedGroups[groupId] = true;
    return groupId;
S
sushuang 已提交
1757
}
L
lang 已提交
1758

S
sushuang 已提交
1759 1760 1761 1762
/**
 * @DEPRECATED
 * @return {string} groupId
 */
S
sushuang 已提交
1763
export function disConnect(groupId) {
S
sushuang 已提交
1764
    connectedGroups[groupId] = false;
S
sushuang 已提交
1765
}
1766

S
sushuang 已提交
1767 1768 1769
/**
 * @return {string} groupId
 */
S
sushuang 已提交
1770
export var disconnect = disConnect;
L
lang 已提交
1771

S
sushuang 已提交
1772 1773 1774 1775
/**
 * Dispose a chart instance
 * @param  {module:echarts~ECharts|HTMLDomElement|string} chart
 */
S
sushuang 已提交
1776
export function dispose(chart) {
S
sushuang 已提交
1777 1778 1779 1780 1781
    if (typeof chart === 'string') {
        chart = instances[chart];
    }
    else if (!(chart instanceof ECharts)){
        // Try to treat as dom
S
sushuang 已提交
1782
        chart = getInstanceByDom(chart);
S
sushuang 已提交
1783 1784 1785 1786
    }
    if ((chart instanceof ECharts) && !chart.isDisposed()) {
        chart.dispose();
    }
S
sushuang 已提交
1787
}
1788

S
sushuang 已提交
1789 1790 1791 1792
/**
 * @param  {HTMLElement} dom
 * @return {echarts~ECharts}
 */
S
sushuang 已提交
1793
export function getInstanceByDom(dom) {
S
sushuang 已提交
1794
    return instances[modelUtil.getAttribute(dom, DOM_ATTRIBUTE_KEY)];
S
sushuang 已提交
1795
}
1
100pah 已提交
1796

S
sushuang 已提交
1797 1798 1799 1800
/**
 * @param {string} key
 * @return {echarts~ECharts}
 */
S
sushuang 已提交
1801
export function getInstanceById(key) {
S
sushuang 已提交
1802
    return instances[key];
S
sushuang 已提交
1803
}
P
pah100 已提交
1804

S
sushuang 已提交
1805 1806 1807
/**
 * Register theme
 */
S
sushuang 已提交
1808
export function registerTheme(name, theme) {
S
sushuang 已提交
1809
    themeStorage[name] = theme;
S
sushuang 已提交
1810
}
L
lang 已提交
1811

S
sushuang 已提交
1812 1813 1814 1815
/**
 * Register option preprocessor
 * @param {Function} preprocessorFunc
 */
S
sushuang 已提交
1816
export function registerPreprocessor(preprocessorFunc) {
S
sushuang 已提交
1817
    optionPreprocessorFuncs.push(preprocessorFunc);
S
sushuang 已提交
1818
}
1819

S
sushuang 已提交
1820 1821
/**
 * @param {number} [priority=1000]
S
sushuang 已提交
1822
 * @param {Object|Function} processor
S
sushuang 已提交
1823
 */
S
sushuang 已提交
1824 1825
export function registerProcessor(priority, processor) {
    normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
S
sushuang 已提交
1826
}
L
lang 已提交
1827

S
sushuang 已提交
1828 1829 1830 1831
/**
 * Register postUpdater
 * @param {Function} postUpdateFunc
 */
S
sushuang 已提交
1832
export function registerPostUpdate(postUpdateFunc) {
S
sushuang 已提交
1833
    postUpdateFuncs.push(postUpdateFunc);
S
sushuang 已提交
1834
}
L
Update  
lang 已提交
1835

S
sushuang 已提交
1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
/**
 * Usage:
 * registerAction('someAction', 'someEvent', function () { ... });
 * registerAction('someAction', function () { ... });
 * registerAction(
 *     {type: 'someAction', event: 'someEvent', update: 'updateView'},
 *     function () { ... }
 * );
 *
 * @param {(string|Object)} actionInfo
 * @param {string} actionInfo.type
 * @param {string} [actionInfo.event]
 * @param {string} [actionInfo.update]
 * @param {string} [eventName]
 * @param {Function} action
 */
S
sushuang 已提交
1852
export function registerAction(actionInfo, eventName, action) {
S
sushuang 已提交
1853 1854 1855 1856
    if (typeof eventName === 'function') {
        action = eventName;
        eventName = '';
    }
S
sushuang 已提交
1857
    var actionType = isObject(actionInfo)
S
sushuang 已提交
1858 1859 1860 1861
        ? actionInfo.type
        : ([actionInfo, actionInfo = {
            event: eventName
        }][0]);
L
lang 已提交
1862

S
sushuang 已提交
1863 1864 1865
    // Event name is all lowercase
    actionInfo.event = (actionInfo.event || actionType).toLowerCase();
    eventName = actionInfo.event;
L
Update  
lang 已提交
1866

S
sushuang 已提交
1867
    // Validate action type and event name.
S
sushuang 已提交
1868
    assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
L
Update  
lang 已提交
1869

S
sushuang 已提交
1870 1871 1872 1873
    if (!actions[actionType]) {
        actions[actionType] = {action: action, actionInfo: actionInfo};
    }
    eventActionMap[eventName] = actionType;
S
sushuang 已提交
1874
}
P
pah100 已提交
1875

S
sushuang 已提交
1876 1877 1878 1879
/**
 * @param {string} type
 * @param {*} CoordinateSystem
 */
S
sushuang 已提交
1880
export function registerCoordinateSystem(type, CoordinateSystem) {
S
sushuang 已提交
1881
    CoordinateSystemManager.register(type, CoordinateSystem);
S
sushuang 已提交
1882
}
L
lang 已提交
1883

S
sushuang 已提交
1884 1885 1886 1887 1888
/**
 * Get dimensions of specified coordinate system.
 * @param {string} type
 * @return {Array.<string|Object>}
 */
S
sushuang 已提交
1889
export function getCoordinateSystemDimensions(type) {
S
sushuang 已提交
1890 1891 1892 1893 1894 1895
    var coordSysCreator = CoordinateSystemManager.get(type);
    if (coordSysCreator) {
        return coordSysCreator.getDimensionsInfo
                ? coordSysCreator.getDimensionsInfo()
                : coordSysCreator.dimensions.slice();
    }
S
sushuang 已提交
1896
}
1897

S
sushuang 已提交
1898 1899 1900 1901 1902 1903
/**
 * 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
 *
 * @param {number} [priority=1000]
S
sushuang 已提交
1904
 * @param {Function} layoutTask
S
sushuang 已提交
1905
 */
S
sushuang 已提交
1906 1907
export function registerLayout(priority, layoutTask) {
    var wrap = normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT);
S
sushuang 已提交
1908
    wrap.visualType = 'layout';
S
sushuang 已提交
1909
}
P
pah100 已提交
1910

S
sushuang 已提交
1911 1912
/**
 * @param {number} [priority=3000]
S
sushuang 已提交
1913
 * @param {module:echarts/stream/Task} visualTask
S
sushuang 已提交
1914
 */
S
sushuang 已提交
1915
export function registerVisual(priority, visualTask) {
S
sushuang 已提交
1916 1917
    var wrap = normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART);
    wrap.visualType = 'visual';
S
sushuang 已提交
1918 1919
}

S
sushuang 已提交
1920 1921 1922
/**
 * @param {Object|Function} fn: {seriesType, allSeries, processRawSeries, reset}
 */
S
sushuang 已提交
1923
function normalizeRegister(targetList, priority, fn, defaultPriority) {
S
sushuang 已提交
1924
    if (isFunction(priority) || isObject(priority)) {
S
sushuang 已提交
1925 1926
        fn = priority;
        priority = defaultPriority;
S
sushuang 已提交
1927
    }
S
sushuang 已提交
1928

S
sushuang 已提交
1929
    if (__DEV__) {
S
sushuang 已提交
1930 1931
        if (isNaN(priority) || priority == null) {
            throw new Error('Illegal priority');
1932
        }
S
sushuang 已提交
1933
        // Check duplicate
S
sushuang 已提交
1934 1935
        each(targetList, function (wrap) {
            assert(wrap.raw !== fn);
S
sushuang 已提交
1936
        });
S
sushuang 已提交
1937
    }
S
sushuang 已提交
1938 1939 1940
    var stageHandler = isFunction(fn) ? {legacyFunc: fn} : fn;
    stageHandler.uid = getUID('stageHandler');
    stageHandler.prio = priority;
S
sushuang 已提交
1941

S
sushuang 已提交
1942
    targetList.push(stageHandler);
S
sushuang 已提交
1943

S
sushuang 已提交
1944
    return stageHandler;
S
sushuang 已提交
1945
}
S
sushuang 已提交
1946 1947 1948 1949

/**
 * @param {string} name
 */
S
sushuang 已提交
1950
export function registerLoading(name, loadingFx) {
S
sushuang 已提交
1951
    loadingEffects[name] = loadingFx;
S
sushuang 已提交
1952
}
S
sushuang 已提交
1953 1954 1955 1956 1957

/**
 * @param {Object} opts
 * @param {string} [superClass]
 */
S
sushuang 已提交
1958
export function extendComponentModel(opts/*, superClass*/) {
S
sushuang 已提交
1959 1960 1961 1962 1963 1964
    // var Clazz = ComponentModel;
    // if (superClass) {
    //     var classType = parseClassType(superClass);
    //     Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
    // }
    return ComponentModel.extend(opts);
S
sushuang 已提交
1965
}
S
sushuang 已提交
1966 1967 1968 1969 1970

/**
 * @param {Object} opts
 * @param {string} [superClass]
 */
S
sushuang 已提交
1971
export function extendComponentView(opts/*, superClass*/) {
S
sushuang 已提交
1972 1973 1974 1975 1976 1977
    // var Clazz = ComponentView;
    // if (superClass) {
    //     var classType = parseClassType(superClass);
    //     Clazz = ComponentView.getClass(classType.main, classType.sub, true);
    // }
    return ComponentView.extend(opts);
S
sushuang 已提交
1978
}
S
sushuang 已提交
1979 1980 1981 1982 1983

/**
 * @param {Object} opts
 * @param {string} [superClass]
 */
S
sushuang 已提交
1984
export function extendSeriesModel(opts/*, superClass*/) {
S
sushuang 已提交
1985 1986 1987 1988 1989 1990 1991
    // var Clazz = SeriesModel;
    // if (superClass) {
    //     superClass = 'series.' + superClass.replace('series.', '');
    //     var classType = parseClassType(superClass);
    //     Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
    // }
    return SeriesModel.extend(opts);
S
sushuang 已提交
1992
}
S
sushuang 已提交
1993 1994 1995 1996 1997

/**
 * @param {Object} opts
 * @param {string} [superClass]
 */
S
sushuang 已提交
1998
export function extendChartView(opts/*, superClass*/) {
S
sushuang 已提交
1999 2000 2001 2002 2003 2004 2005
    // var Clazz = ChartView;
    // if (superClass) {
    //     superClass = superClass.replace('series.', '');
    //     var classType = parseClassType(superClass);
    //     Clazz = ChartView.getClass(classType.main, true);
    // }
    return ChartView.extend(opts);
S
sushuang 已提交
2006
}
S
sushuang 已提交
2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023

/**
 * 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);
 *     });
 */
S
sushuang 已提交
2024
export function setCanvasCreator(creator) {
S
sushuang 已提交
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063
    zrUtil.$override('createCanvas', creator);
}

/**
 * @param {string} mapName
 * @param {Object|string} geoJson
 * @param {Object} [specialAreas]
 *
 * @example
 *     $.get('USA.json', function (geoJson) {
 *         echarts.registerMap('USA', geoJson);
 *         // Or
 *         echarts.registerMap('USA', {
 *             geoJson: geoJson,
 *             specialAreas: {}
 *         })
 *     });
 */
export function registerMap(mapName, geoJson, specialAreas) {
    if (geoJson.geoJson && !geoJson.features) {
        specialAreas = geoJson.specialAreas;
        geoJson = geoJson.geoJson;
    }
    if (typeof geoJson === 'string') {
        geoJson = (typeof JSON !== 'undefined' && JSON.parse)
            ? JSON.parse(geoJson) : (new Function('return (' + geoJson + ');'))();
    }
    mapDataStores[mapName] = {
        geoJson: geoJson,
        specialAreas: specialAreas
    };
}

/**
 * @param {string} mapName
 * @return {Object}
 */
export function getMap(mapName) {
    return mapDataStores[mapName];
S
sushuang 已提交
2064
}
S
sushuang 已提交
2065

S
sushuang 已提交
2066 2067 2068
registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
registerPreprocessor(backwardCompat);
registerLoading('default', loadingDefault);
S
sushuang 已提交
2069

S
sushuang 已提交
2070 2071
// Default actions

S
sushuang 已提交
2072
registerAction({
S
sushuang 已提交
2073 2074 2075 2076
    type: 'highlight',
    event: 'highlight',
    update: 'highlight'
}, zrUtil.noop);
S
sushuang 已提交
2077

S
sushuang 已提交
2078
registerAction({
S
sushuang 已提交
2079 2080 2081 2082 2083
    type: 'downplay',
    event: 'downplay',
    update: 'downplay'
}, zrUtil.noop);

S
sushuang 已提交
2084

S
sushuang 已提交
2085 2086 2087
// For backward compatibility, where the namespace `dataTool` will
// be mounted on `echarts` is the extension `dataTool` is imported.
export var dataTool = {};