echarts.js 60.1 KB
Newer Older
1

L
tweak  
lang 已提交
2
/*!
T
tanzhongyibidu 已提交
3
 * ECharts, a free, powerful charting and visualization library.
S
sushuang 已提交
4
 *
T
tanzhongyibidu 已提交
5
 * Copyright (c) 2017, Baidu Inc.
S
sushuang 已提交
6 7 8 9 10 11
 * 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
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';
O
Ovilia 已提交
32
import aria from './visual/aria';
S
sushuang 已提交
33
import loadingDefault from './loading/default';
S
tweak  
sushuang 已提交
34
import Scheduler from './stream/Scheduler';
P
pissang 已提交
35 36
import lightTheme from './theme/light';
import darkTheme from './theme/dark';
S
sushuang 已提交
37

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

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

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

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

S
sushuang 已提交
53 54 55 56 57 58 59 60 61 62 63
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 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76
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
    }
};
77

S
sushuang 已提交
78 79 80 81 82 83 84 85 86
// 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 已提交
87

L
lang 已提交
88

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

S
sushuang 已提交
97 98 99 100 101 102 103 104 105 106
/**
 * @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);
107

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

S
sushuang 已提交
248 249
    var scheduler = this._scheduler;

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

S
sushuang 已提交
254
        this[IN_MAIN_PROCESS] = true;
1
100pah 已提交
255

S
sushuang 已提交
256 257
        prepare(this);
        updateMethods.update.call(this);
1
100pah 已提交
258

S
sushuang 已提交
259
        this[IN_MAIN_PROCESS] = false;
260

S
sushuang 已提交
261
        this[OPTION_UPDATED] = false;
262

S
sushuang 已提交
263
        flushPendingActions.call(this, silent);
264

S
sushuang 已提交
265 266
        triggerUpdatedEvent.call(this, silent);
    }
S
sushuang 已提交
267
    // Avoid do both lazy update and progress in one frame.
S
sushuang 已提交
268
    else if (scheduler.unfinished) {
S
sushuang 已提交
269 270 271
        // Stream progress.
        var remainTime = TEST_FRAME_REMAIN_TIME;
        var ecModel = this._model;
S
sushuang 已提交
272 273 274 275
        var api = this._api;
        scheduler.unfinished = false;
        do {
            var startTime = +new Date();
S
tweak  
sushuang 已提交
276

S
sushuang 已提交
277
            scheduler.performSeriesTasks(ecModel);
S
tweak  
sushuang 已提交
278

S
sushuang 已提交
279 280
            // Currently dataProcessorFuncs do not check threshold.
            scheduler.performDataProcessorTasks(dataProcessorFuncs, ecModel);
S
sushuang 已提交
281

S
sushuang 已提交
282
            updateStreamModes(this, ecModel);
S
sushuang 已提交
283

S
sushuang 已提交
284 285 286 287
            // Do not update coordinate system here. Because that coord system update in
            // each frame is not a good user experience. So we follow the rule that
            // the extent of the coordinate system is determin in the first frame (the
            // frame is executed immedietely after task reset.
S
sushuang 已提交
288
            // this._coordSysMgr.update(ecModel, api);
S
sushuang 已提交
289

S
sushuang 已提交
290 291
            // console.log('--- ec frame visual ---', remainTime);
            scheduler.performVisualTasks(visualFuncs, ecModel);
S
tweak  
sushuang 已提交
292

S
sushuang 已提交
293
            renderSeries(this, this._model, api, 'remain');
S
sushuang 已提交
294

S
sushuang 已提交
295 296 297
            remainTime -= (+new Date() - startTime);
        }
        while (remainTime > 0 && scheduler.unfinished);
S
sushuang 已提交
298

S
sushuang 已提交
299 300 301
        if (!scheduler.unfinished) {
            this._zr && this._zr.flush();
            this.trigger('finished');
S
tweak  
sushuang 已提交
302
        }
S
sushuang 已提交
303 304
        // Else, zr flushing be ensue within the same frame,
        // because zr flushing is after onframe event.
S
sushuang 已提交
305
    }
S
tweak  
sushuang 已提交
306
};
S
sushuang 已提交
307 308


S
sushuang 已提交
309 310 311 312 313 314
/**
 * @return {HTMLElement}
 */
echartsProto.getDom = function () {
    return this._dom;
};
315

S
sushuang 已提交
316 317 318 319 320 321
/**
 * @return {module:zrender~ZRender}
 */
echartsProto.getZr = function () {
    return this._zr;
};
322

S
sushuang 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
/**
 * 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 已提交
339
        assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
S
sushuang 已提交
340
    }
341

S
sushuang 已提交
342
    var silent;
S
sushuang 已提交
343
    if (isObject(notMerge)) {
S
sushuang 已提交
344 345 346 347
        lazyUpdate = notMerge.lazyUpdate;
        silent = notMerge.silent;
        notMerge = notMerge.notMerge;
    }
348

S
sushuang 已提交
349
    this[IN_MAIN_PROCESS] = true;
350

S
sushuang 已提交
351 352 353 354
    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 已提交
355
        ecModel.scheduler = this._scheduler;
S
sushuang 已提交
356 357
        ecModel.init(null, null, theme, optionManager);
    }
358

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

S
sushuang 已提交
361 362 363 364 365
    if (lazyUpdate) {
        this[OPTION_UPDATED] = {silent: silent};
        this[IN_MAIN_PROCESS] = false;
    }
    else {
S
sushuang 已提交
366 367 368 369
        prepare(this);

        updateMethods.update.call(this);

S
sushuang 已提交
370 371 372
        // Ensure zr refresh sychronously, and then pixel in canvas can be
        // fetched after `setOption`.
        this._zr.flush();
L
lang 已提交
373

S
sushuang 已提交
374 375
        this[OPTION_UPDATED] = false;
        this[IN_MAIN_PROCESS] = false;
L
lang 已提交
376

S
sushuang 已提交
377 378 379 380 381 382 383 384 385 386 387
        flushPendingActions.call(this, silent);
        triggerUpdatedEvent.call(this, silent);
    }
};

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

S
sushuang 已提交
389 390 391 392 393 394
/**
 * @return {module:echarts/model/Global}
 */
echartsProto.getModel = function () {
    return this._model;
};
395

S
sushuang 已提交
396 397 398 399 400 401
/**
 * @return {Object}
 */
echartsProto.getOption = function () {
    return this._model && this._model.getOption();
};
P
pah100 已提交
402

S
sushuang 已提交
403 404 405 406 407 408
/**
 * @return {number}
 */
echartsProto.getWidth = function () {
    return this._zr.getWidth();
};
409

S
sushuang 已提交
410 411 412 413 414 415
/**
 * @return {number}
 */
echartsProto.getHeight = function () {
    return this._zr.getHeight();
};
L
lang 已提交
416

S
sushuang 已提交
417 418 419 420 421 422
/**
 * @return {number}
 */
echartsProto.getDevicePixelRatio = function () {
    return this._zr.painter.dpr || window.devicePixelRatio || 1;
};
L
lang 已提交
423

S
sushuang 已提交
424 425 426 427
/**
 * Get canvas which has all thing rendered
 * @param {Object} opts
 * @param {string} [opts.backgroundColor]
S
sushuang 已提交
428
 * @return {string}
S
sushuang 已提交
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
 */
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 已提交
446

S
sushuang 已提交
447 448 449 450 451 452 453 454
/**
 * Get svg data url
 * @return {string}
 */
echartsProto.getSvgDataUrl = function () {
    if (!env.svgSupported) {
        return;
    }
O
Ovilia 已提交
455

S
sushuang 已提交
456 457 458 459 460 461
    var zr = this._zr;
    var list = zr.storage.getDisplayList();
    // Stop animations
    zrUtil.each(list, function (el) {
        el.stopAnimation(true);
    });
462

S
sushuang 已提交
463 464
    return zr.painter.pathToSvg();
};
465

S
sushuang 已提交
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
/**
 * @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 已提交
492

S
sushuang 已提交
493 494 495 496 497
    var url = this._zr.painter.getType() === 'svg'
        ? this.getSvgDataUrl()
        : this.getRenderedCanvas(opts).toDataURL(
            'image/' + (opts && opts.type || 'png')
        );
498

S
sushuang 已提交
499 500 501
    each(excludesComponentViews, function (view) {
        view.group.ignore = false;
    });
L
lang 已提交
502

S
sushuang 已提交
503 504
    return url;
};
505

506

S
sushuang 已提交
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
/**
 * @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 已提交
544 545
                });
            }
S
sushuang 已提交
546
        });
L
lang 已提交
547

S
sushuang 已提交
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
        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 已提交
565
                }
S
sushuang 已提交
566 567 568 569
            });
            zr.add(img);
        });
        zr.refreshImmediately();
L
lang 已提交
570

S
sushuang 已提交
571 572 573 574 575 576
        return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
    }
    else {
        return this.getDataURL(opts);
    }
};
L
lang 已提交
577

S
sushuang 已提交
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
/**
 * 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');
597

S
sushuang 已提交
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
/**
 * 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');
617

S
sushuang 已提交
618 619 620 621
function doConvertPixel(methodName, finder, value) {
    var ecModel = this._model;
    var coordSysList = this._coordSysMgr.getCoordinateSystems();
    var result;
622

S
sushuang 已提交
623
    finder = modelUtil.parseFinder(ecModel, finder);
624

S
sushuang 已提交
625 626 627 628 629 630 631 632
    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 已提交
633

S
sushuang 已提交
634 635 636 637 638 639
    if (__DEV__) {
        console.warn(
            'No coordinate system that supports ' + methodName + ' found by the given finder.'
        );
    }
}
640

S
sushuang 已提交
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
/**
 * 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;
661

S
sushuang 已提交
662
    finder = modelUtil.parseFinder(ecModel, finder);
663

S
sushuang 已提交
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
    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.'
                        ));
                    }
                }
683
            }
S
sushuang 已提交
684 685 686 687 688 689 690
            else {
                if (__DEV__) {
                    console.warn(key + ': containPoint is not supported');
                }
            }
        }, this);
    }, this);
691

S
sushuang 已提交
692 693
    return !!result;
};
P
pah100 已提交
694

S
sushuang 已提交
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
/**
 * 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;
712

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

S
sushuang 已提交
715
    var seriesModel = finder.seriesModel;
716

S
sushuang 已提交
717 718 719 720 721
    if (__DEV__) {
        if (!seriesModel) {
            console.warn('There is no specified seires model');
        }
    }
722

S
sushuang 已提交
723
    var data = seriesModel.getData();
724

S
sushuang 已提交
725 726 727 728 729
    var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
        ? finder.dataIndexInside
        : finder.hasOwnProperty('dataIndex')
        ? data.indexOfRawIndex(finder.dataIndex)
        : null;
L
lang 已提交
730

S
sushuang 已提交
731 732 733 734
    return dataIndexInside != null
        ? data.getItemVisual(dataIndexInside, visualType)
        : data.getVisual(visualType);
};
735

S
sushuang 已提交
736 737 738 739 740 741 742 743
/**
 * 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 已提交
744

S
sushuang 已提交
745 746 747 748 749 750 751 752
/**
 * 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 已提交
753

S
sushuang 已提交
754
var updateMethods = {
755

S
sushuang 已提交
756 757 758 759 760
    prepareAndUpdate: function (payload) {
        prepare(this);
        updateMethods.update.call(this, payload);
    },

761
    /**
S
sushuang 已提交
762
     * @param {Object} payload
763 764
     * @private
     */
S
sushuang 已提交
765 766
    update: function (payload) {
        // console.profile && console.profile('update');
P
pah100 已提交
767

S
sushuang 已提交
768 769 770
        var ecModel = this._model;
        var api = this._api;
        var zr = this._zr;
S
sushuang 已提交
771
        var coordSysMgr = this._coordSysMgr;
S
tweak  
sushuang 已提交
772 773
        var scheduler = this._scheduler;

S
sushuang 已提交
774 775
        // update before setOption
        if (!ecModel) {
P
pah100 已提交
776 777 778
            return;
        }

779
        ecModel.restoreData(payload);
S
sushuang 已提交
780

S
sushuang 已提交
781
        scheduler.performSeriesTasks(ecModel);
782

S
sushuang 已提交
783 784 785
        // 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 已提交
786

S
sushuang 已提交
787 788
        // Create new coordinate system each update
        // In LineView may save the old coordinate system and use it to get the orignal point
S
sushuang 已提交
789
        coordSysMgr.create(ecModel, api);
S
tweak  
sushuang 已提交
790

S
sushuang 已提交
791 792
        scheduler.performDataProcessorTasks(dataProcessorFuncs, ecModel, payload);

S
sushuang 已提交
793 794 795
        // Current stream render is not supported in data process. So we can update
        // stream modes after data processing, where the filtered data is used to
        // deteming whether use progressive rendering.
S
sushuang 已提交
796
        updateStreamModes(this, ecModel);
797

S
sushuang 已提交
798
        stackSeriesData(ecModel);
799

S
sushuang 已提交
800
        coordSysMgr.update(ecModel, api);
P
pah100 已提交
801

S
sushuang 已提交
802
        clearColorPalette(ecModel);
S
sushuang 已提交
803
        scheduler.performVisualTasks(visualFuncs, ecModel, payload);
804

S
sushuang 已提交
805
        render(this, ecModel, api, payload);
S
tweak  
sushuang 已提交
806

S
sushuang 已提交
807 808
        // Set background
        var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
L
lang 已提交
809

S
sushuang 已提交
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
        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;
833

S
sushuang 已提交
834 835 836 837 838 839 840 841 842
                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 已提交
843

S
sushuang 已提交
844 845 846
                this._dom.style.background = backgroundColor;
            }
        }
847

S
sushuang 已提交
848
        performPostUpdateFuncs(ecModel, api);
849

S
sushuang 已提交
850 851
        // console.profile && console.profileEnd('update');
    },
L
lang 已提交
852

S
sushuang 已提交
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
    /**
     * @param {Object} payload
     * @private
     */
    updateTransform: function (payload) {
        var ecModel = this._model;
        var ecIns = this;
        var api = this._api;

        // update before setOption
        if (!ecModel) {
            return;
        }

        ChartView.markUpdateMethod(payload, 'updateTransform');

S
sushuang 已提交
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
        var componentDirtyList = [];
        ecModel.eachComponent(function (componentType, componentModel) {
            var componentView = ecIns.getViewOfComponentModel(componentModel);
            if (componentView && componentView.__alive) {
                if (componentView.updateTransform) {
                    var result = componentView.updateTransform(componentModel, ecModel, api, payload);
                    result && result.update && componentDirtyList.push(componentView);
                }
                else {
                    componentDirtyList.push(componentView);
                }
            }
        });

        var seriesDirtyMap = zrUtil.createHashMap();
S
sushuang 已提交
884 885 886
        ecModel.eachSeries(function (seriesModel) {
            var chartView = ecIns._chartsMap[seriesModel.__viewId];
            if (chartView.updateTransform) {
S
sushuang 已提交
887 888
                var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
                result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
S
sushuang 已提交
889 890
            }
            else {
S
sushuang 已提交
891
                seriesDirtyMap.set(seriesModel.uid, 1);
S
sushuang 已提交
892 893 894
            }
        });

S
sushuang 已提交
895
        clearColorPalette(ecModel);
S
sushuang 已提交
896
        // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
S
sushuang 已提交
897 898
        // this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, 'layout', true);
        this._scheduler.performVisualTasks(
S
sushuang 已提交
899
            visualFuncs, ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
S
sushuang 已提交
900 901
        );

S
sushuang 已提交
902 903
        renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
        renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
S
sushuang 已提交
904 905 906 907

        performPostUpdateFuncs(ecModel, this._api);
    },

L
lang 已提交
908
    /**
S
sushuang 已提交
909 910
     * @param {Object} payload
     * @private
L
lang 已提交
911
     */
S
sushuang 已提交
912 913
    updateView: function (payload) {
        var ecModel = this._model;
914

S
sushuang 已提交
915 916
        // update before setOption
        if (!ecModel) {
L
lang 已提交
917 918
            return;
        }
L
lang 已提交
919

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

S
sushuang 已提交
922
        clearColorPalette(ecModel);
L
lang 已提交
923

S
tweak  
sushuang 已提交
924
        // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
S
sushuang 已提交
925
        this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, {setDirty: true});
P
pah100 已提交
926

S
sushuang 已提交
927
        render(this, this._model, this._api, payload);
S
tweak  
sushuang 已提交
928

S
sushuang 已提交
929
        performPostUpdateFuncs(ecModel, this._api);
S
sushuang 已提交
930
    },
L
lang 已提交
931

L
tweak  
lang 已提交
932 933
    /**
     * @param {Object} payload
S
sushuang 已提交
934
     * @private
L
tweak  
lang 已提交
935
     */
S
sushuang 已提交
936
    updateVisual: function (payload) {
937
        updateMethods.update.call(this, payload);
938

939
        // var ecModel = this._model;
L
lang 已提交
940

941 942 943 944
        // // update before setOption
        // if (!ecModel) {
        //     return;
        // }
S
tweak  
sushuang 已提交
945

946
        // ChartView.markUpdateMethod(payload, 'updateVisual');
947

948
        // clearColorPalette(ecModel);
949

950 951
        // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
        // this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, {visualType: 'visual', setDirty: true});
S
tweak  
sushuang 已提交
952

953 954 955
        // render(this, this._model, this._api, payload);

        // performPostUpdateFuncs(ecModel, this._api);
S
sushuang 已提交
956
    },
1
tweak  
100pah 已提交
957

S
sushuang 已提交
958 959 960 961 962
    /**
     * @param {Object} payload
     * @private
     */
    updateLayout: function (payload) {
963
        updateMethods.update.call(this, payload);
S
sushuang 已提交
964

965
        // var ecModel = this._model;
966

967 968 969 970
        // // update before setOption
        // if (!ecModel) {
        //     return;
        // }
S
tweak  
sushuang 已提交
971

972
        // ChartView.markUpdateMethod(payload, 'updateLayout');
973

974 975 976
        // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
        // // this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, 'layout', true);
        // this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, {setDirty: true});
S
tweak  
sushuang 已提交
977

978 979 980
        // render(this, this._model, this._api, payload);

        // performPostUpdateFuncs(ecModel, this._api);
S
sushuang 已提交
981 982
    }
};
S
sushuang 已提交
983

S
sushuang 已提交
984
function prepare(ecIns) {
S
sushuang 已提交
985 986
    var ecModel = ecIns._model;
    var scheduler = ecIns._scheduler;
1
tweak  
100pah 已提交
987

S
sushuang 已提交
988 989 990
    scheduler.restorePipelines(ecModel);

    scheduler.prepareStageTasks(dataProcessorFuncs);
1
100pah 已提交
991

S
sushuang 已提交
992
    scheduler.prepareStageTasks(visualFuncs);
1
tweak  
100pah 已提交
993

S
sushuang 已提交
994
    prepareView(ecIns, 'component', ecModel, scheduler);
S
sushuang 已提交
995

S
sushuang 已提交
996
    prepareView(ecIns, 'chart', ecModel, scheduler);
S
sushuang 已提交
997

S
sushuang 已提交
998
    scheduler.plan();
S
sushuang 已提交
999
}
L
lang 已提交
1000

S
sushuang 已提交
1001 1002 1003 1004 1005
/**
 * @private
 */
function updateDirectly(ecIns, method, payload, mainType, subType) {
    var ecModel = ecIns._model;
P
pah100 已提交
1006

S
sushuang 已提交
1007 1008 1009 1010 1011
    // broadcast
    if (!mainType) {
        each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
        return;
    }
1012

S
sushuang 已提交
1013 1014 1015 1016
    var query = {};
    query[mainType + 'Id'] = payload[mainType + 'Id'];
    query[mainType + 'Index'] = payload[mainType + 'Index'];
    query[mainType + 'Name'] = payload[mainType + 'Name'];
1017

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

S
sushuang 已提交
1021 1022 1023 1024 1025 1026
    // If dispatchAction before setOption, do nothing.
    ecModel && ecModel.eachComponent(condition, function (model, index) {
        callView(ecIns[
            mainType === 'series' ? '_chartsMap' : '_componentsMap'
        ][model.__viewId]);
    }, ecIns);
1027

S
sushuang 已提交
1028 1029 1030 1031
    function callView(view) {
        view && view.__alive && view[method] && view[method](
            view.__model, ecModel, ecIns._api, payload
        );
1
tweak  
100pah 已提交
1032
    }
S
sushuang 已提交
1033
}
L
tweak  
lang 已提交
1034

S
sushuang 已提交
1035 1036 1037 1038 1039 1040 1041 1042 1043
/**
 * 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 已提交
1044
        assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
1
tweak  
100pah 已提交
1045
    }
L
lang 已提交
1046

S
sushuang 已提交
1047
    this._zr.resize(opts);
L
lang 已提交
1048

S
sushuang 已提交
1049 1050
    var ecModel = this._model;

P
pissang 已提交
1051 1052 1053 1054 1055 1056 1057 1058
    // Resize loading effect
    this._loadingFX && this._loadingFX.resize();

    if (!ecModel) {
        return;
    }

    var optionChanged = ecModel.resetOption('media');
S
sushuang 已提交
1059 1060 1061

    optionChanged && ecModel.settingTask.dirty();

S
sushuang 已提交
1062 1063 1064
    // ???
    // can not visual???

S
sushuang 已提交
1065 1066 1067 1068
    ecModel.eachComponent(function (model, componentType) {
        optionChanged && model.settingTask.dirty();
        model.dataInitTask && model.dataInitTask.dirty();
    });
L
lang 已提交
1069

S
sushuang 已提交
1070
    refresh(this, optionChanged, opts && opts.silent);
S
sushuang 已提交
1071 1072
};

S
sushuang 已提交
1073
function refresh(ecIns, needPrepare, silent) {
S
tweak  
sushuang 已提交
1074
    ecIns[IN_MAIN_PROCESS] = true;
S
sushuang 已提交
1075

S
sushuang 已提交
1076 1077
    needPrepare && prepare(ecIns);
    updateMethods.update.call(ecIns);
1078

S
tweak  
sushuang 已提交
1079
    ecIns[IN_MAIN_PROCESS] = false;
1080

S
tweak  
sushuang 已提交
1081
    flushPendingActions.call(ecIns, silent);
1082

S
tweak  
sushuang 已提交
1083
    triggerUpdatedEvent.call(ecIns, silent);
S
sushuang 已提交
1084
}
1085

S
sushuang 已提交
1086 1087 1088 1089 1090 1091 1092 1093
function updateStreamModes(ecIns, ecModel) {
    var chartsMap = ecIns._chartsMap;
    var scheduler = ecIns._scheduler;
    ecModel.eachSeries(function (seriesModel) {
        scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
    });
}

S
sushuang 已提交
1094 1095 1096 1097 1098 1099
/**
 * Show loading effect
 * @param  {string} [name='default']
 * @param  {Object} [cfg]
 */
echartsProto.showLoading = function (name, cfg) {
S
sushuang 已提交
1100
    if (isObject(name)) {
S
sushuang 已提交
1101 1102
        cfg = name;
        name = '';
1103
    }
S
sushuang 已提交
1104
    name = name || 'default';
L
lang 已提交
1105

S
sushuang 已提交
1106 1107 1108 1109
    this.hideLoading();
    if (!loadingEffects[name]) {
        if (__DEV__) {
            console.warn('Loading effects ' + name + ' not exists.');
L
tweak  
lang 已提交
1110
        }
S
sushuang 已提交
1111 1112 1113 1114 1115
        return;
    }
    var el = loadingEffects[name](this._api, cfg);
    var zr = this._zr;
    this._loadingFX = el;
L
lang 已提交
1116

S
sushuang 已提交
1117 1118
    zr.add(el);
};
L
tweak  
lang 已提交
1119

S
sushuang 已提交
1120 1121 1122 1123 1124 1125 1126
/**
 * Hide loading effect
 */
echartsProto.hideLoading = function () {
    this._loadingFX && this._zr.remove(this._loadingFX);
    this._loadingFX = null;
};
L
Tweak  
lang 已提交
1127

S
sushuang 已提交
1128 1129 1130 1131 1132 1133 1134 1135 1136
/**
 * @param {Object} eventObj
 * @return {Object}
 */
echartsProto.makeActionFromEvent = function (eventObj) {
    var payload = zrUtil.extend({}, eventObj);
    payload.type = eventActionMap[eventObj.type];
    return payload;
};
L
tweak  
lang 已提交
1137

S
sushuang 已提交
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
/**
 * @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 已提交
1151
    if (!isObject(opt)) {
S
sushuang 已提交
1152
        opt = {silent: !!opt};
1153 1154
    }

S
sushuang 已提交
1155 1156
    if (!actions[payload.type]) {
        return;
1157
    }
L
lang 已提交
1158

S
sushuang 已提交
1159 1160 1161
    // Avoid dispatch action before setOption. Especially in `connect`.
    if (!this._model) {
        return;
1162
    }
L
lang 已提交
1163

S
sushuang 已提交
1164 1165 1166 1167
    // May dispatchAction in rendering procedure
    if (this[IN_MAIN_PROCESS]) {
        this._pendingActions.push(payload);
        return;
1168
    }
L
lang 已提交
1169

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

S
sushuang 已提交
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
    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 已提交
1183

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

S
sushuang 已提交
1186 1187
    triggerUpdatedEvent.call(this, opt.silent);
};
L
tweak  
lang 已提交
1188

S
sushuang 已提交
1189 1190 1191 1192 1193
function doDispatchAction(payload, silent) {
    var payloadType = payload.type;
    var escapeConnect = payload.escapeConnect;
    var actionWrap = actions[payloadType];
    var actionInfo = actionWrap.actionInfo;
L
tweak  
lang 已提交
1194

S
sushuang 已提交
1195 1196 1197
    var cptType = (actionInfo.update || 'update').split(':');
    var updateMethod = cptType.pop();
    cptType = cptType[0] != null && parseClassType(cptType[0]);
L
lang 已提交
1198

S
sushuang 已提交
1199
    this[IN_MAIN_PROCESS] = true;
1200

S
sushuang 已提交
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
    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 已提交
1212

S
sushuang 已提交
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
    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 已提交
1235

S
sushuang 已提交
1236 1237 1238 1239
    if (updateMethod !== 'none' && !isHighDown && !cptType) {
        // Still dirty
        if (this[OPTION_UPDATED]) {
            // FIXME Pass payload ?
S
sushuang 已提交
1240 1241
            prepare(this);
            updateMethods.update.call(this, payload);
S
sushuang 已提交
1242 1243 1244 1245 1246 1247
            this[OPTION_UPDATED] = false;
        }
        else {
            updateMethods[updateMethod].call(this, payload);
        }
    }
1248

S
sushuang 已提交
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
    // Follow the rule of action batch
    if (batched) {
        eventObj = {
            type: actionInfo.event || payloadType,
            escapeConnect: escapeConnect,
            batch: eventObjBatch
        };
    }
    else {
        eventObj = eventObjBatch[0];
1259
    }
L
lang 已提交
1260

S
sushuang 已提交
1261
    this[IN_MAIN_PROCESS] = false;
1
100pah 已提交
1262

S
sushuang 已提交
1263 1264
    !silent && this._messageCenter.trigger(eventObj.type, eventObj);
}
1
100pah 已提交
1265

S
sushuang 已提交
1266 1267 1268 1269 1270 1271 1272
function flushPendingActions(silent) {
    var pendingActions = this._pendingActions;
    while (pendingActions.length) {
        var payload = pendingActions.shift();
        doDispatchAction.call(this, payload, silent);
    }
}
L
lang 已提交
1273

S
sushuang 已提交
1274 1275 1276
function triggerUpdatedEvent(silent) {
    !silent && this.trigger('updated');
}
L
lang 已提交
1277

S
sushuang 已提交
1278 1279 1280 1281 1282 1283
/**
 * @param {Object} params
 * @param {number} params.seriesIndex
 * @param {Array|TypedArray} params.data
 */
echartsProto.appendData = function (params) {
S
tweak  
sushuang 已提交
1284 1285
    var seriesIndex = params.seriesIndex;
    var ecModel = this.getModel();
S
sushuang 已提交
1286
    var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
S
sushuang 已提交
1287

S
tweak  
sushuang 已提交
1288
    if (__DEV__) {
S
sushuang 已提交
1289
        assert(params.data && seriesModel);
S
tweak  
sushuang 已提交
1290
    }
S
sushuang 已提交
1291

P
pissang 已提交
1292
    seriesModel.appendData(params);
S
sushuang 已提交
1293 1294

    this._scheduler.unfinished = true;
S
tweak  
sushuang 已提交
1295
};
S
sushuang 已提交
1296

S
sushuang 已提交
1297 1298 1299 1300 1301 1302 1303
/**
 * Register event
 * @method
 */
echartsProto.on = createRegisterEventWithLowercaseName('on');
echartsProto.off = createRegisterEventWithLowercaseName('off');
echartsProto.one = createRegisterEventWithLowercaseName('one');
L
lang 已提交
1304

S
sushuang 已提交
1305 1306 1307 1308 1309
/**
 * Prepare view instances of charts and components
 * @param  {module:echarts/model/Global} ecModel
 * @private
 */
S
sushuang 已提交
1310
function prepareView(ecIns, type, ecModel, scheduler) {
S
sushuang 已提交
1311
    var isComponent = type === 'component';
S
sushuang 已提交
1312 1313 1314 1315
    var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
    var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
    var zr = ecIns._zr;
    var api = ecIns._api;
S
sushuang 已提交
1316 1317 1318

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

S
sushuang 已提交
1321 1322 1323 1324 1325
    isComponent
        ? ecModel.eachComponent(function (componentType, model) {
            componentType !== 'series' && doPrepare(model);
        })
        : ecModel.eachSeries(doPrepare);
1326

S
sushuang 已提交
1327
    function doPrepare(model) {
S
sushuang 已提交
1328 1329 1330 1331 1332 1333 1334 1335
        // 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 已提交
1336 1337

            if (__DEV__) {
S
sushuang 已提交
1338
                assert(Clazz, classType.sub + ' does not exist.');
1339
            }
S
sushuang 已提交
1340 1341

            view = new Clazz();
S
sushuang 已提交
1342
            view.init(ecModel, api);
S
sushuang 已提交
1343 1344 1345
            viewMap[viewId] = view;
            viewList.push(view);
            zr.add(view.group);
S
sushuang 已提交
1346
        }
1347

S
sushuang 已提交
1348 1349 1350 1351 1352 1353 1354
        model.__viewId = view.__id = viewId;
        view.__alive = true;
        view.__model = model;
        view.group.__ecComponentInfo = {
            mainType: model.mainType,
            index: model.componentIndex
        };
S
sushuang 已提交
1355
        !isComponent && scheduler.prepareView(view, model, ecModel, api);
S
sushuang 已提交
1356
    }
S
sushuang 已提交
1357 1358 1359 1360

    for (var i = 0; i < viewList.length;) {
        var view = viewList[i];
        if (!view.__alive) {
S
sushuang 已提交
1361
            view.renderTask.dispose();
S
sushuang 已提交
1362
            zr.remove(view.group);
S
sushuang 已提交
1363
            view.dispose(ecModel, api);
S
sushuang 已提交
1364 1365 1366 1367 1368 1369 1370
            viewList.splice(i, 1);
            delete viewMap[view.__id];
            view.__id = view.group.__ecComponentInfo = null;
        }
        else {
            i++;
        }
L
lang 已提交
1371
    }
S
sushuang 已提交
1372
}
1373

S
sushuang 已提交
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
/**
 * @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 已提交
1392

S
sushuang 已提交
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
// /**
//  * 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 已提交
1420
    });
S
sushuang 已提交
1421 1422
}

S
sushuang 已提交
1423 1424
function render(ecIns, ecModel, api, payload) {

S
sushuang 已提交
1425
    renderComponents(ecIns, ecModel, api, payload);
S
sushuang 已提交
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440

    each(ecIns._chartsViews, function (chart) {
        chart.__alive = false;
    });

    renderSeries(ecIns, ecModel, api, payload);

    // Remove groups of unrendered charts
    each(ecIns._chartsViews, function (chart) {
        if (!chart.__alive) {
            chart.remove(ecModel, api);
        }
    });
}

S
sushuang 已提交
1441 1442 1443 1444 1445 1446 1447 1448 1449
function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
    each(dirtyList || ecIns._componentsViews, function (componentView) {
        var componentModel = componentView.__model;
        componentView.render(componentModel, ecModel, api, payload);

        updateZ(componentModel, componentView);
    });
}

S
sushuang 已提交
1450 1451 1452 1453
/**
 * Render each chart and component
 * @private
 */
1454
function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
S
sushuang 已提交
1455
    // Render all charts
S
sushuang 已提交
1456 1457
    var scheduler = ecIns._scheduler;
    var unfinished;
1458
    ecModel.eachSeries(function (seriesModel) {
S
sushuang 已提交
1459
        var chartView = ecIns._chartsMap[seriesModel.__viewId];
S
sushuang 已提交
1460
        chartView.__alive = true;
L
lang 已提交
1461

S
sushuang 已提交
1462
        var renderTask = chartView.renderTask;
S
sushuang 已提交
1463
        scheduler.updatePayload(renderTask, payload);
1464 1465 1466 1467 1468

        if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
            renderTask.dirty();
        }

S
sushuang 已提交
1469
        unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
L
lang 已提交
1470

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

S
sushuang 已提交
1473
        updateZ(seriesModel, chartView);
S
sushuang 已提交
1474

P
pissang 已提交
1475
        updateBlend(seriesModel, chartView);
1476
    });
S
sushuang 已提交
1477
    scheduler.unfinished |= unfinished;
S
sushuang 已提交
1478 1479

    // If use hover layer
P
pissang 已提交
1480
    updateHoverLayerStatus(ecIns._zr, ecModel);
O
Ovilia 已提交
1481 1482

    // Add aria
1483
    aria(ecIns._zr.dom, ecModel);
S
sushuang 已提交
1484 1485
}

S
sushuang 已提交
1486 1487 1488
function performPostUpdateFuncs(ecModel, api) {
    each(postUpdateFuncs, function (func) {
        func(ecModel, api);
S
sushuang 已提交
1489
    });
S
tweak  
sushuang 已提交
1490 1491
}

S
sushuang 已提交
1492

S
sushuang 已提交
1493 1494 1495 1496
var MOUSE_EVENT_NAMES = [
    'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
    'mousedown', 'mouseup', 'globalout', 'contextmenu'
];
S
sushuang 已提交
1497

S
sushuang 已提交
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
/**
 * @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 已提交
1520

S
sushuang 已提交
1521 1522 1523 1524
            if (params) {
                params.event = e;
                params.type = eveName;
                this.trigger(eveName, params);
L
lang 已提交
1525
            }
S
sushuang 已提交
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557

        }, 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 已提交
1558
        }
S
sushuang 已提交
1559 1560 1561
        return;
    }
    this._disposed = true;
P
pah100 已提交
1562

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

S
sushuang 已提交
1565 1566
    var api = this._api;
    var ecModel = this._model;
P
pah100 已提交
1567

S
sushuang 已提交
1568 1569 1570 1571 1572 1573
    each(this._componentsViews, function (component) {
        component.dispose(ecModel, api);
    });
    each(this._chartsViews, function (chart) {
        chart.dispose(ecModel, api);
    });
1
100pah 已提交
1574

S
sushuang 已提交
1575 1576
    // Dispose after all views disposed
    this._zr.dispose();
1
100pah 已提交
1577

S
sushuang 已提交
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
    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) {
P
pissang 已提交
1594
                // Don't switch back.
S
sushuang 已提交
1595 1596
                el.useHoverLayer = true;
            }
L
lang 已提交
1597 1598
        });
    }
S
sushuang 已提交
1599
}
P
pah100 已提交
1600

S
sushuang 已提交
1601 1602 1603 1604 1605
/**
 * 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
 */
P
pissang 已提交
1606
function updateBlend(seriesModel, chartView) {
S
sushuang 已提交
1607
    // Blend configration
S
sushuang 已提交
1608
    // ???
S
sushuang 已提交
1609 1610 1611 1612
    var blendMode = seriesModel.get('blendMode') || null;
    if (__DEV__) {
        if (!env.canvasSupported && blendMode && blendMode !== 'source-over') {
            console.warn('Only canvas support blendMode');
P
pah100 已提交
1613
        }
S
sushuang 已提交
1614 1615 1616 1617
    }
    chartView.group.traverse(function (el) {
        // FIXME marker and other components
        if (!el.isGroup) {
1618 1619 1620 1621
            // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
            if (el.style.blend !== blendMode) {
                el.setStyle('blend', blendMode);
            }
S
sushuang 已提交
1622
        }
P
pissang 已提交
1623 1624
        if (el.eachPendingDisplayable) {
            el.eachPendingDisplayable(function (displayable) {
P
pissang 已提交
1625
                displayable.setStyle('blend', blendMode);
P
pissang 已提交
1626 1627
            });
        }
S
sushuang 已提交
1628 1629
    });
}
P
pah100 已提交
1630

S
sushuang 已提交
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
/**
 * @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 已提交
1643
        }
S
sushuang 已提交
1644 1645
    });
}
P
pah100 已提交
1646

S
sushuang 已提交
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
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;
1661
            }
1662
        }
S
sushuang 已提交
1663 1664
    });
}
L
lang 已提交
1665

S
sushuang 已提交
1666 1667 1668 1669 1670
/**
 * @type {Object} key: actionType.
 * @inner
 */
var actions = {};
L
lang 已提交
1671

S
sushuang 已提交
1672 1673 1674 1675 1676
/**
 * Map eventType to actionType
 * @type {Object}
 */
var eventActionMap = {};
L
lang 已提交
1677

S
sushuang 已提交
1678 1679 1680 1681 1682 1683
/**
 * Data processor functions of each stage
 * @type {Array.<Object.<string, Function>>}
 * @inner
 */
var dataProcessorFuncs = [];
L
lang 已提交
1684

S
sushuang 已提交
1685 1686 1687 1688 1689
/**
 * @type {Array.<Function>}
 * @inner
 */
var optionPreprocessorFuncs = [];
L
lang 已提交
1690

S
sushuang 已提交
1691 1692 1693 1694 1695
/**
 * @type {Array.<Function>}
 * @inner
 */
var postUpdateFuncs = [];
L
lang 已提交
1696

S
sushuang 已提交
1697 1698 1699 1700 1701
/**
 * Visual encoding functions of each stage
 * @type {Array.<Object.<string, Function>>}
 */
var visualFuncs = [];
S
sushuang 已提交
1702

S
sushuang 已提交
1703 1704 1705 1706 1707 1708 1709 1710 1711
/**
 * Theme storage
 * @type {Object.<key, Object>}
 */
var themeStorage = {};
/**
 * Loading effects
 */
var loadingEffects = {};
L
lang 已提交
1712

S
sushuang 已提交
1713 1714 1715 1716 1717 1718 1719
var instances = {};
var connectedGroups = {};

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

S
sushuang 已提交
1720 1721
var mapDataStores = {};

S
sushuang 已提交
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
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 已提交
1732
        }
S
sushuang 已提交
1733 1734
    }

S
sushuang 已提交
1735
    each(eventActionMap, function (actionType, eventType) {
S
sushuang 已提交
1736 1737 1738 1739 1740 1741 1742 1743 1744
        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 已提交
1745
                each(instances, function (otherChart) {
S
sushuang 已提交
1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
                    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 已提交
1774
export function init(dom, theme, opts) {
S
sushuang 已提交
1775 1776
    if (__DEV__) {
        // Check version
S
sushuang 已提交
1777
        if ((zrender.version.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
S
sushuang 已提交
1778
            throw new Error(
S
sushuang 已提交
1779
                'zrender/src ' + zrender.version
S
sushuang 已提交
1780
                + ' is too old for ECharts ' + version
S
sushuang 已提交
1781
                + '. Current version need ZRender '
S
sushuang 已提交
1782
                + dependencies.zrender + '+'
S
sushuang 已提交
1783
            );
P
pissang 已提交
1784
        }
S
sushuang 已提交
1785 1786 1787

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

S
sushuang 已提交
1791
    var existInstance = getInstanceByDom(dom);
S
sushuang 已提交
1792 1793 1794
    if (existInstance) {
        if (__DEV__) {
            console.warn('There is a chart instance already initialized on the dom.');
P
pissang 已提交
1795
        }
S
sushuang 已提交
1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
        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 已提交
1808
        }
S
sushuang 已提交
1809
    }
P
pah100 已提交
1810

S
sushuang 已提交
1811 1812 1813
    var chart = new ECharts(dom, theme, opts);
    chart.id = 'ec_' + idBase++;
    instances[chart.id] = chart;
L
lang 已提交
1814

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

S
sushuang 已提交
1817
    enableConnect(chart);
1818

S
sushuang 已提交
1819
    return chart;
S
sushuang 已提交
1820
}
S
sushuang 已提交
1821 1822 1823 1824

/**
 * @return {string|Array.<module:echarts~ECharts>} groupId
 */
S
sushuang 已提交
1825
export function connect(groupId) {
S
sushuang 已提交
1826 1827 1828 1829 1830
    // Is array of charts
    if (zrUtil.isArray(groupId)) {
        var charts = groupId;
        groupId = null;
        // If any chart has group
S
sushuang 已提交
1831
        each(charts, function (chart) {
S
sushuang 已提交
1832 1833
            if (chart.group != null) {
                groupId = chart.group;
1834
            }
1835
        });
S
sushuang 已提交
1836
        groupId = groupId || ('g_' + groupIdBase++);
S
sushuang 已提交
1837
        each(charts, function (chart) {
S
sushuang 已提交
1838 1839 1840 1841 1842
            chart.group = groupId;
        });
    }
    connectedGroups[groupId] = true;
    return groupId;
S
sushuang 已提交
1843
}
L
lang 已提交
1844

S
sushuang 已提交
1845 1846 1847 1848
/**
 * @DEPRECATED
 * @return {string} groupId
 */
S
sushuang 已提交
1849
export function disConnect(groupId) {
S
sushuang 已提交
1850
    connectedGroups[groupId] = false;
S
sushuang 已提交
1851
}
1852

S
sushuang 已提交
1853 1854 1855
/**
 * @return {string} groupId
 */
S
sushuang 已提交
1856
export var disconnect = disConnect;
L
lang 已提交
1857

S
sushuang 已提交
1858 1859 1860 1861
/**
 * Dispose a chart instance
 * @param  {module:echarts~ECharts|HTMLDomElement|string} chart
 */
S
sushuang 已提交
1862
export function dispose(chart) {
S
sushuang 已提交
1863 1864 1865 1866 1867
    if (typeof chart === 'string') {
        chart = instances[chart];
    }
    else if (!(chart instanceof ECharts)){
        // Try to treat as dom
S
sushuang 已提交
1868
        chart = getInstanceByDom(chart);
S
sushuang 已提交
1869 1870 1871 1872
    }
    if ((chart instanceof ECharts) && !chart.isDisposed()) {
        chart.dispose();
    }
S
sushuang 已提交
1873
}
1874

S
sushuang 已提交
1875 1876 1877 1878
/**
 * @param  {HTMLElement} dom
 * @return {echarts~ECharts}
 */
S
sushuang 已提交
1879
export function getInstanceByDom(dom) {
S
sushuang 已提交
1880
    return instances[modelUtil.getAttribute(dom, DOM_ATTRIBUTE_KEY)];
S
sushuang 已提交
1881
}
1
100pah 已提交
1882

S
sushuang 已提交
1883 1884 1885 1886
/**
 * @param {string} key
 * @return {echarts~ECharts}
 */
S
sushuang 已提交
1887
export function getInstanceById(key) {
S
sushuang 已提交
1888
    return instances[key];
S
sushuang 已提交
1889
}
P
pah100 已提交
1890

S
sushuang 已提交
1891 1892 1893
/**
 * Register theme
 */
S
sushuang 已提交
1894
export function registerTheme(name, theme) {
S
sushuang 已提交
1895
    themeStorage[name] = theme;
S
sushuang 已提交
1896
}
L
lang 已提交
1897

S
sushuang 已提交
1898 1899 1900 1901
/**
 * Register option preprocessor
 * @param {Function} preprocessorFunc
 */
S
sushuang 已提交
1902
export function registerPreprocessor(preprocessorFunc) {
S
sushuang 已提交
1903
    optionPreprocessorFuncs.push(preprocessorFunc);
S
sushuang 已提交
1904
}
1905

S
sushuang 已提交
1906 1907
/**
 * @param {number} [priority=1000]
S
sushuang 已提交
1908
 * @param {Object|Function} processor
S
sushuang 已提交
1909
 */
S
sushuang 已提交
1910 1911
export function registerProcessor(priority, processor) {
    normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
S
sushuang 已提交
1912
}
L
lang 已提交
1913

S
sushuang 已提交
1914 1915 1916 1917
/**
 * Register postUpdater
 * @param {Function} postUpdateFunc
 */
S
sushuang 已提交
1918
export function registerPostUpdate(postUpdateFunc) {
S
sushuang 已提交
1919
    postUpdateFuncs.push(postUpdateFunc);
S
sushuang 已提交
1920
}
L
Update  
lang 已提交
1921

S
sushuang 已提交
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937
/**
 * 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 已提交
1938
export function registerAction(actionInfo, eventName, action) {
S
sushuang 已提交
1939 1940 1941 1942
    if (typeof eventName === 'function') {
        action = eventName;
        eventName = '';
    }
S
sushuang 已提交
1943
    var actionType = isObject(actionInfo)
S
sushuang 已提交
1944 1945 1946 1947
        ? actionInfo.type
        : ([actionInfo, actionInfo = {
            event: eventName
        }][0]);
L
lang 已提交
1948

S
sushuang 已提交
1949 1950 1951
    // Event name is all lowercase
    actionInfo.event = (actionInfo.event || actionType).toLowerCase();
    eventName = actionInfo.event;
L
Update  
lang 已提交
1952

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

S
sushuang 已提交
1956 1957 1958 1959
    if (!actions[actionType]) {
        actions[actionType] = {action: action, actionInfo: actionInfo};
    }
    eventActionMap[eventName] = actionType;
S
sushuang 已提交
1960
}
P
pah100 已提交
1961

S
sushuang 已提交
1962 1963 1964 1965
/**
 * @param {string} type
 * @param {*} CoordinateSystem
 */
S
sushuang 已提交
1966
export function registerCoordinateSystem(type, CoordinateSystem) {
S
sushuang 已提交
1967
    CoordinateSystemManager.register(type, CoordinateSystem);
S
sushuang 已提交
1968
}
L
lang 已提交
1969

S
sushuang 已提交
1970 1971 1972 1973 1974
/**
 * Get dimensions of specified coordinate system.
 * @param {string} type
 * @return {Array.<string|Object>}
 */
S
sushuang 已提交
1975
export function getCoordinateSystemDimensions(type) {
S
sushuang 已提交
1976 1977 1978 1979 1980 1981
    var coordSysCreator = CoordinateSystemManager.get(type);
    if (coordSysCreator) {
        return coordSysCreator.getDimensionsInfo
                ? coordSysCreator.getDimensionsInfo()
                : coordSysCreator.dimensions.slice();
    }
S
sushuang 已提交
1982
}
1983

S
sushuang 已提交
1984 1985 1986 1987 1988 1989
/**
 * 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 已提交
1990
 * @param {Function} layoutTask
S
sushuang 已提交
1991
 */
S
sushuang 已提交
1992
export function registerLayout(priority, layoutTask) {
S
sushuang 已提交
1993
    normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
S
sushuang 已提交
1994
}
P
pah100 已提交
1995

S
sushuang 已提交
1996 1997
/**
 * @param {number} [priority=3000]
S
sushuang 已提交
1998
 * @param {module:echarts/stream/Task} visualTask
S
sushuang 已提交
1999
 */
S
sushuang 已提交
2000
export function registerVisual(priority, visualTask) {
S
sushuang 已提交
2001
    normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
S
sushuang 已提交
2002 2003
}

S
sushuang 已提交
2004
/**
2005
 * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
S
sushuang 已提交
2006
 */
S
sushuang 已提交
2007
function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
S
sushuang 已提交
2008
    if (isFunction(priority) || isObject(priority)) {
S
sushuang 已提交
2009 2010
        fn = priority;
        priority = defaultPriority;
S
sushuang 已提交
2011
    }
S
sushuang 已提交
2012

S
sushuang 已提交
2013
    if (__DEV__) {
S
sushuang 已提交
2014 2015
        if (isNaN(priority) || priority == null) {
            throw new Error('Illegal priority');
2016
        }
S
sushuang 已提交
2017
        // Check duplicate
S
sushuang 已提交
2018
        each(targetList, function (wrap) {
S
sushuang 已提交
2019
            assert(wrap.__raw !== fn);
S
sushuang 已提交
2020
        });
S
sushuang 已提交
2021
    }
S
sushuang 已提交
2022

S
sushuang 已提交
2023 2024 2025 2026
    var stageHandler = Scheduler.wrapStageHandler(fn, visualType);

    stageHandler.__prio = priority;
    stageHandler.__raw = fn;
S
sushuang 已提交
2027
    targetList.push(stageHandler);
S
sushuang 已提交
2028

S
sushuang 已提交
2029
    return stageHandler;
S
sushuang 已提交
2030
}
S
sushuang 已提交
2031 2032 2033 2034

/**
 * @param {string} name
 */
S
sushuang 已提交
2035
export function registerLoading(name, loadingFx) {
S
sushuang 已提交
2036
    loadingEffects[name] = loadingFx;
S
sushuang 已提交
2037
}
S
sushuang 已提交
2038 2039 2040 2041 2042

/**
 * @param {Object} opts
 * @param {string} [superClass]
 */
S
sushuang 已提交
2043
export function extendComponentModel(opts/*, superClass*/) {
S
sushuang 已提交
2044 2045 2046 2047 2048 2049
    // var Clazz = ComponentModel;
    // if (superClass) {
    //     var classType = parseClassType(superClass);
    //     Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
    // }
    return ComponentModel.extend(opts);
S
sushuang 已提交
2050
}
S
sushuang 已提交
2051 2052 2053 2054 2055

/**
 * @param {Object} opts
 * @param {string} [superClass]
 */
S
sushuang 已提交
2056
export function extendComponentView(opts/*, superClass*/) {
S
sushuang 已提交
2057 2058 2059 2060 2061 2062
    // var Clazz = ComponentView;
    // if (superClass) {
    //     var classType = parseClassType(superClass);
    //     Clazz = ComponentView.getClass(classType.main, classType.sub, true);
    // }
    return ComponentView.extend(opts);
S
sushuang 已提交
2063
}
S
sushuang 已提交
2064 2065 2066 2067 2068

/**
 * @param {Object} opts
 * @param {string} [superClass]
 */
S
sushuang 已提交
2069
export function extendSeriesModel(opts/*, superClass*/) {
S
sushuang 已提交
2070 2071 2072 2073 2074 2075 2076
    // 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 已提交
2077
}
S
sushuang 已提交
2078 2079 2080 2081 2082

/**
 * @param {Object} opts
 * @param {string} [superClass]
 */
S
sushuang 已提交
2083
export function extendChartView(opts/*, superClass*/) {
S
sushuang 已提交
2084 2085 2086 2087 2088 2089 2090
    // 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 已提交
2091
}
S
sushuang 已提交
2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108

/**
 * 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 已提交
2109
export function setCanvasCreator(creator) {
S
sushuang 已提交
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148
    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 已提交
2149
}
S
sushuang 已提交
2150

S
sushuang 已提交
2151 2152 2153
registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
registerPreprocessor(backwardCompat);
registerLoading('default', loadingDefault);
S
sushuang 已提交
2154

S
sushuang 已提交
2155 2156
// Default actions

S
sushuang 已提交
2157
registerAction({
S
sushuang 已提交
2158 2159 2160 2161
    type: 'highlight',
    event: 'highlight',
    update: 'highlight'
}, zrUtil.noop);
S
sushuang 已提交
2162

S
sushuang 已提交
2163
registerAction({
S
sushuang 已提交
2164 2165 2166 2167 2168
    type: 'downplay',
    event: 'downplay',
    update: 'downplay'
}, zrUtil.noop);

P
pissang 已提交
2169 2170 2171
// Default theme
registerTheme('light', lightTheme);
registerTheme('dark', darkTheme);
S
sushuang 已提交
2172

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