echarts.js 57.9 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

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

S
sushuang 已提交
41
export var version = '3.8.5';
42

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

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

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

S
sushuang 已提交
75 76 77 78 79 80 81 82 83
// 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 已提交
84

L
lang 已提交
85

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

S
sushuang 已提交
207
    Eventful.call(this);
208

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

S
sushuang 已提交
215 216
    // this._scheduler = new Scheduler();

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

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

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

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

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

S
sushuang 已提交
238
var echartsProto = ECharts.prototype;
1
100pah 已提交
239

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

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

S
sushuang 已提交
249
        this[IN_MAIN_PROCESS] = true;
1
100pah 已提交
250

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

S
sushuang 已提交
254
        this[IN_MAIN_PROCESS] = false;
255

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

S
sushuang 已提交
258
        flushPendingActions.call(this, silent);
259

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

S
sushuang 已提交
263 264 265 266 267 268
    // Avoid do both lazy update and progress in one frame.
    else {
        // Stream progress.
        var remainTime = TEST_FRAME_REMAIN_TIME;
        var scheduler = this._scheduler;
        var ecModel = this._model;
S
tweak  
sushuang 已提交
269

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

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

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

S
sushuang 已提交
280
                scheduler.updateModes(ecModel);
S
sushuang 已提交
281

S
sushuang 已提交
282 283
                // ???! coordSys create
                // this._coordSysMgr.update();
S
tweak  
sushuang 已提交
284

S
sushuang 已提交
285 286
                // console.log('--- ec frame visual ---', remainTime);
                scheduler.performVisualTasks(visualFuncs, ecModel);
S
sushuang 已提交
287

S
sushuang 已提交
288 289 290 291 292 293 294 295 296 297 298 299
                render(this, this._model, this._api, 'none');

                remainTime -= (+new Date() - startTime);
            }
            while (remainTime > 0 && scheduler.unfinished);

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


S
sushuang 已提交
305 306 307 308 309 310
/**
 * @return {HTMLElement}
 */
echartsProto.getDom = function () {
    return this._dom;
};
311

S
sushuang 已提交
312 313 314 315 316 317
/**
 * @return {module:zrender~ZRender}
 */
echartsProto.getZr = function () {
    return this._zr;
};
318

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

S
sushuang 已提交
338
    var silent;
S
sushuang 已提交
339
    if (isObject(notMerge)) {
S
sushuang 已提交
340 341 342 343
        lazyUpdate = notMerge.lazyUpdate;
        silent = notMerge.silent;
        notMerge = notMerge.notMerge;
    }
344

S
sushuang 已提交
345
    this[IN_MAIN_PROCESS] = true;
346

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

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

S
sushuang 已提交
357 358 359 360 361
    if (lazyUpdate) {
        this[OPTION_UPDATED] = {silent: silent};
        this[IN_MAIN_PROCESS] = false;
    }
    else {
S
sushuang 已提交
362 363 364 365
        prepare(this);

        updateMethods.update.call(this);

S
sushuang 已提交
366 367 368
        // Ensure zr refresh sychronously, and then pixel in canvas can be
        // fetched after `setOption`.
        this._zr.flush();
L
lang 已提交
369

S
sushuang 已提交
370 371
        this[OPTION_UPDATED] = false;
        this[IN_MAIN_PROCESS] = false;
L
lang 已提交
372

S
sushuang 已提交
373 374 375 376 377 378 379 380 381 382 383
        flushPendingActions.call(this, silent);
        triggerUpdatedEvent.call(this, silent);
    }
};

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

S
sushuang 已提交
385 386 387 388 389 390
/**
 * @return {module:echarts/model/Global}
 */
echartsProto.getModel = function () {
    return this._model;
};
391

S
sushuang 已提交
392 393 394 395 396 397
/**
 * @return {Object}
 */
echartsProto.getOption = function () {
    return this._model && this._model.getOption();
};
P
pah100 已提交
398

S
sushuang 已提交
399 400 401 402 403 404
/**
 * @return {number}
 */
echartsProto.getWidth = function () {
    return this._zr.getWidth();
};
405

S
sushuang 已提交
406 407 408 409 410 411
/**
 * @return {number}
 */
echartsProto.getHeight = function () {
    return this._zr.getHeight();
};
L
lang 已提交
412

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

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

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

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

S
sushuang 已提交
459 460
    return zr.painter.pathToSvg();
};
461

S
sushuang 已提交
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
/**
 * @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 已提交
488

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

S
sushuang 已提交
495 496 497
    each(excludesComponentViews, function (view) {
        view.group.ignore = false;
    });
L
lang 已提交
498

S
sushuang 已提交
499 500
    return url;
};
501

502

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

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

S
sushuang 已提交
567 568 569 570 571 572
        return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
    }
    else {
        return this.getDataURL(opts);
    }
};
L
lang 已提交
573

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

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

S
sushuang 已提交
614 615 616 617
function doConvertPixel(methodName, finder, value) {
    var ecModel = this._model;
    var coordSysList = this._coordSysMgr.getCoordinateSystems();
    var result;
618

S
sushuang 已提交
619
    finder = modelUtil.parseFinder(ecModel, finder);
620

S
sushuang 已提交
621 622 623 624 625 626 627 628
    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 已提交
629

S
sushuang 已提交
630 631 632 633 634 635
    if (__DEV__) {
        console.warn(
            'No coordinate system that supports ' + methodName + ' found by the given finder.'
        );
    }
}
636

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

S
sushuang 已提交
658
    finder = modelUtil.parseFinder(ecModel, finder);
659

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

S
sushuang 已提交
688 689
    return !!result;
};
P
pah100 已提交
690

S
sushuang 已提交
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
/**
 * 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;
708

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

S
sushuang 已提交
711
    var seriesModel = finder.seriesModel;
712

S
sushuang 已提交
713 714 715 716 717
    if (__DEV__) {
        if (!seriesModel) {
            console.warn('There is no specified seires model');
        }
    }
718

S
sushuang 已提交
719
    var data = seriesModel.getData();
720

S
sushuang 已提交
721 722 723 724 725
    var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
        ? finder.dataIndexInside
        : finder.hasOwnProperty('dataIndex')
        ? data.indexOfRawIndex(finder.dataIndex)
        : null;
L
lang 已提交
726

S
sushuang 已提交
727 728 729 730
    return dataIndexInside != null
        ? data.getItemVisual(dataIndexInside, visualType)
        : data.getVisual(visualType);
};
731

S
sushuang 已提交
732 733 734 735 736 737 738 739
/**
 * 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 已提交
740

S
sushuang 已提交
741 742 743 744 745 746 747 748
/**
 * 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 已提交
749

S
sushuang 已提交
750
var updateMethods = {
751 752

    /**
S
sushuang 已提交
753
     * @param {Object} payload
754 755
     * @private
     */
S
sushuang 已提交
756 757
    update: function (payload) {
        // console.profile && console.profile('update');
P
pah100 已提交
758

S
sushuang 已提交
759 760 761
        var ecModel = this._model;
        var api = this._api;
        var zr = this._zr;
S
sushuang 已提交
762
        var coordSysMgr = this._coordSysMgr;
S
tweak  
sushuang 已提交
763 764
        var scheduler = this._scheduler;

S
sushuang 已提交
765 766
        // update before setOption
        if (!ecModel) {
P
pah100 已提交
767 768 769
            return;
        }

S
sushuang 已提交
770 771
        // Fixme First time update ?
        ecModel.restoreData();
S
sushuang 已提交
772
        scheduler.performSeriesTasks(ecModel);
773

S
sushuang 已提交
774 775 776
        // 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 已提交
777

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

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

S
sushuang 已提交
786 787 788
        scheduler.performDataProcessorTasks(dataProcessorFuncs, ecModel, payload);

        scheduler.updateModes(ecModel);
789

S
sushuang 已提交
790
        stackSeriesData.call(this, ecModel);
791

S
sushuang 已提交
792
        // ??? coord data travel
S
sushuang 已提交
793
        coordSysMgr.update(ecModel, api);
P
pah100 已提交
794

S
sushuang 已提交
795
        clearColorPalette(ecModel);
S
sushuang 已提交
796
        scheduler.performVisualTasks(visualFuncs, ecModel, payload);
797

S
sushuang 已提交
798
        render(this, ecModel, api, payload);
S
tweak  
sushuang 已提交
799

S
sushuang 已提交
800 801
        // Set background
        var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
L
lang 已提交
802

S
sushuang 已提交
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
        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;
826

S
sushuang 已提交
827 828 829 830 831 832 833 834 835
                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 已提交
836

S
sushuang 已提交
837 838 839
                this._dom.style.background = backgroundColor;
            }
        }
840

S
sushuang 已提交
841
        performPostUpdateFuncs(ecModel, api);
842

S
sushuang 已提交
843 844
        // console.profile && console.profileEnd('update');
    },
L
lang 已提交
845

S
sushuang 已提交
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
    /**
     * @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');

        var seriesModels = [];
        ecModel.eachSeries(function (seriesModel) {
            var chartView = ecIns._chartsMap[seriesModel.__viewId];
            if (chartView.updateTransform) {
                var result = chartView.updateTransform
                    && chartView.updateTransform(seriesModel, ecModel, api, payload);
                result && result.update && seriesModels.push(seriesModel);
            }
            else {
                seriesModels.push(seriesModel);
            }
        });

        // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
S
sushuang 已提交
876 877
        // this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, 'layout', true);
        this._scheduler.performVisualTasks(
S
sushuang 已提交
878 879 880
            visualFuncs, ecModel, payload, {setDirty: true, seriesModels: seriesModels}
        );

S
sushuang 已提交
881
        renderSeries(this, ecModel, this._api, payload, seriesModels);
S
sushuang 已提交
882 883 884 885

        performPostUpdateFuncs(ecModel, this._api);
    },

L
lang 已提交
886
    /**
S
sushuang 已提交
887 888
     * @param {Object} payload
     * @private
L
lang 已提交
889
     */
S
sushuang 已提交
890 891
    updateView: function (payload) {
        var ecModel = this._model;
892

S
sushuang 已提交
893 894
        // update before setOption
        if (!ecModel) {
L
lang 已提交
895 896
            return;
        }
L
lang 已提交
897

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

S
sushuang 已提交
900
        clearColorPalette(ecModel);
L
lang 已提交
901

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

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

S
sushuang 已提交
907
        performPostUpdateFuncs(ecModel, this._api);
S
sushuang 已提交
908
    },
L
lang 已提交
909

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

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

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

S
sushuang 已提交
924
        clearColorPalette(ecModel);
925

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

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

S
sushuang 已提交
931
        performPostUpdateFuncs(ecModel, this._api);
S
sushuang 已提交
932
    },
1
tweak  
100pah 已提交
933

S
sushuang 已提交
934 935 936 937 938 939 940 941 942 943
    /**
     * @param {Object} payload
     * @private
     */
    updateLayout: function (payload) {
        var ecModel = this._model;

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

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

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

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

S
sushuang 已提交
954 955 956
        performPostUpdateFuncs(ecModel, this._api);
    }
};
S
sushuang 已提交
957

S
sushuang 已提交
958
function prepare(ecIns) {
S
sushuang 已提交
959 960
    var ecModel = ecIns._model;
    var scheduler = ecIns._scheduler;
1
tweak  
100pah 已提交
961

S
sushuang 已提交
962 963 964
    scheduler.restorePipelines(ecModel);

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

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

S
sushuang 已提交
968
    prepareView(ecIns, 'component', ecModel, scheduler);
S
sushuang 已提交
969

S
sushuang 已提交
970
    prepareView(ecIns, 'chart', ecModel, scheduler);
S
sushuang 已提交
971

S
sushuang 已提交
972
    scheduler.plan();
S
sushuang 已提交
973
}
L
lang 已提交
974

S
sushuang 已提交
975 976 977 978 979
/**
 * @private
 */
function updateDirectly(ecIns, method, payload, mainType, subType) {
    var ecModel = ecIns._model;
P
pah100 已提交
980

S
sushuang 已提交
981 982 983 984 985
    // broadcast
    if (!mainType) {
        each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
        return;
    }
986

S
sushuang 已提交
987 988 989 990
    var query = {};
    query[mainType + 'Id'] = payload[mainType + 'Id'];
    query[mainType + 'Index'] = payload[mainType + 'Index'];
    query[mainType + 'Name'] = payload[mainType + 'Name'];
991

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

S
sushuang 已提交
995 996 997 998 999 1000
    // If dispatchAction before setOption, do nothing.
    ecModel && ecModel.eachComponent(condition, function (model, index) {
        callView(ecIns[
            mainType === 'series' ? '_chartsMap' : '_componentsMap'
        ][model.__viewId]);
    }, ecIns);
1001

S
sushuang 已提交
1002 1003 1004 1005
    function callView(view) {
        view && view.__alive && view[method] && view[method](
            view.__model, ecModel, ecIns._api, payload
        );
1
tweak  
100pah 已提交
1006
    }
S
sushuang 已提交
1007
}
L
tweak  
lang 已提交
1008

S
sushuang 已提交
1009 1010 1011 1012 1013 1014 1015 1016 1017
/**
 * 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 已提交
1018
        assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
1
tweak  
100pah 已提交
1019
    }
L
lang 已提交
1020

S
sushuang 已提交
1021
    this._zr.resize(opts);
L
lang 已提交
1022

S
sushuang 已提交
1023 1024 1025 1026 1027 1028
    var ecModel = this._model;

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

    optionChanged && ecModel.settingTask.dirty();

S
sushuang 已提交
1029 1030 1031
    // ???
    // can not visual???

S
sushuang 已提交
1032 1033 1034 1035
    ecModel.eachComponent(function (model, componentType) {
        optionChanged && model.settingTask.dirty();
        model.dataInitTask && model.dataInitTask.dirty();
    });
L
lang 已提交
1036

S
sushuang 已提交
1037
    refresh(this, optionChanged, opts && opts.silent);
S
sushuang 已提交
1038 1039
};

S
sushuang 已提交
1040
function refresh(ecIns, needPrepare, silent) {
S
tweak  
sushuang 已提交
1041
    ecIns[IN_MAIN_PROCESS] = true;
S
sushuang 已提交
1042

S
sushuang 已提交
1043 1044
    needPrepare && prepare(ecIns);
    updateMethods.update.call(ecIns);
1045

S
sushuang 已提交
1046
    // Resize loading effect
S
tweak  
sushuang 已提交
1047
    ecIns._loadingFX && ecIns._loadingFX.resize();
L
lang 已提交
1048

S
tweak  
sushuang 已提交
1049
    ecIns[IN_MAIN_PROCESS] = false;
1050

S
tweak  
sushuang 已提交
1051
    flushPendingActions.call(ecIns, silent);
1052

S
tweak  
sushuang 已提交
1053
    triggerUpdatedEvent.call(ecIns, silent);
S
sushuang 已提交
1054
}
1055

S
sushuang 已提交
1056 1057 1058 1059 1060 1061
/**
 * Show loading effect
 * @param  {string} [name='default']
 * @param  {Object} [cfg]
 */
echartsProto.showLoading = function (name, cfg) {
S
sushuang 已提交
1062
    if (isObject(name)) {
S
sushuang 已提交
1063 1064
        cfg = name;
        name = '';
1065
    }
S
sushuang 已提交
1066
    name = name || 'default';
L
lang 已提交
1067

S
sushuang 已提交
1068 1069 1070 1071
    this.hideLoading();
    if (!loadingEffects[name]) {
        if (__DEV__) {
            console.warn('Loading effects ' + name + ' not exists.');
L
tweak  
lang 已提交
1072
        }
S
sushuang 已提交
1073 1074 1075 1076 1077
        return;
    }
    var el = loadingEffects[name](this._api, cfg);
    var zr = this._zr;
    this._loadingFX = el;
L
lang 已提交
1078

S
sushuang 已提交
1079 1080
    zr.add(el);
};
L
tweak  
lang 已提交
1081

S
sushuang 已提交
1082 1083 1084 1085 1086 1087 1088
/**
 * Hide loading effect
 */
echartsProto.hideLoading = function () {
    this._loadingFX && this._zr.remove(this._loadingFX);
    this._loadingFX = null;
};
L
Tweak  
lang 已提交
1089

S
sushuang 已提交
1090 1091 1092 1093 1094 1095 1096 1097 1098
/**
 * @param {Object} eventObj
 * @return {Object}
 */
echartsProto.makeActionFromEvent = function (eventObj) {
    var payload = zrUtil.extend({}, eventObj);
    payload.type = eventActionMap[eventObj.type];
    return payload;
};
L
tweak  
lang 已提交
1099

S
sushuang 已提交
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
/**
 * @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 已提交
1113
    if (!isObject(opt)) {
S
sushuang 已提交
1114
        opt = {silent: !!opt};
1115 1116
    }

S
sushuang 已提交
1117 1118
    if (!actions[payload.type]) {
        return;
1119
    }
L
lang 已提交
1120

S
sushuang 已提交
1121 1122 1123
    // Avoid dispatch action before setOption. Especially in `connect`.
    if (!this._model) {
        return;
1124
    }
L
lang 已提交
1125

S
sushuang 已提交
1126 1127 1128 1129
    // May dispatchAction in rendering procedure
    if (this[IN_MAIN_PROCESS]) {
        this._pendingActions.push(payload);
        return;
1130
    }
L
lang 已提交
1131

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

S
sushuang 已提交
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
    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 已提交
1145

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

S
sushuang 已提交
1148 1149
    triggerUpdatedEvent.call(this, opt.silent);
};
L
tweak  
lang 已提交
1150

S
sushuang 已提交
1151 1152 1153 1154 1155
function doDispatchAction(payload, silent) {
    var payloadType = payload.type;
    var escapeConnect = payload.escapeConnect;
    var actionWrap = actions[payloadType];
    var actionInfo = actionWrap.actionInfo;
L
tweak  
lang 已提交
1156

S
sushuang 已提交
1157 1158 1159
    var cptType = (actionInfo.update || 'update').split(':');
    var updateMethod = cptType.pop();
    cptType = cptType[0] != null && parseClassType(cptType[0]);
L
lang 已提交
1160

S
sushuang 已提交
1161
    this[IN_MAIN_PROCESS] = true;
1162

S
sushuang 已提交
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
    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 已提交
1174

S
sushuang 已提交
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
    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 已提交
1197

S
sushuang 已提交
1198 1199 1200 1201
    if (updateMethod !== 'none' && !isHighDown && !cptType) {
        // Still dirty
        if (this[OPTION_UPDATED]) {
            // FIXME Pass payload ?
S
sushuang 已提交
1202 1203
            prepare(this);
            updateMethods.update.call(this, payload);
S
sushuang 已提交
1204 1205 1206 1207 1208 1209
            this[OPTION_UPDATED] = false;
        }
        else {
            updateMethods[updateMethod].call(this, payload);
        }
    }
1210

S
sushuang 已提交
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
    // Follow the rule of action batch
    if (batched) {
        eventObj = {
            type: actionInfo.event || payloadType,
            escapeConnect: escapeConnect,
            batch: eventObjBatch
        };
    }
    else {
        eventObj = eventObjBatch[0];
1221
    }
L
lang 已提交
1222

S
sushuang 已提交
1223
    this[IN_MAIN_PROCESS] = false;
1
100pah 已提交
1224

S
sushuang 已提交
1225 1226
    !silent && this._messageCenter.trigger(eventObj.type, eventObj);
}
1
100pah 已提交
1227

S
sushuang 已提交
1228 1229 1230 1231 1232 1233 1234
function flushPendingActions(silent) {
    var pendingActions = this._pendingActions;
    while (pendingActions.length) {
        var payload = pendingActions.shift();
        doDispatchAction.call(this, payload, silent);
    }
}
L
lang 已提交
1235

S
sushuang 已提交
1236 1237 1238
function triggerUpdatedEvent(silent) {
    !silent && this.trigger('updated');
}
L
lang 已提交
1239

S
tweak  
sushuang 已提交
1240 1241 1242 1243
// ???
echartsProto.addData = function (params) {
    var seriesIndex = params.seriesIndex;
    var ecModel = this.getModel();
S
sushuang 已提交
1244
    var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
S
sushuang 已提交
1245

S
tweak  
sushuang 已提交
1246
    if (__DEV__) {
S
sushuang 已提交
1247
        assert(params.data && seriesModel);
S
tweak  
sushuang 已提交
1248
    }
S
sushuang 已提交
1249

P
pissang 已提交
1250
    seriesModel.appendData(params);
S
sushuang 已提交
1251 1252

    this._scheduler.unfinished = true;
S
tweak  
sushuang 已提交
1253
};
S
sushuang 已提交
1254

S
sushuang 已提交
1255 1256 1257 1258 1259 1260 1261
/**
 * Register event
 * @method
 */
echartsProto.on = createRegisterEventWithLowercaseName('on');
echartsProto.off = createRegisterEventWithLowercaseName('off');
echartsProto.one = createRegisterEventWithLowercaseName('one');
L
lang 已提交
1262

S
sushuang 已提交
1263 1264 1265 1266 1267
/**
 * Prepare view instances of charts and components
 * @param  {module:echarts/model/Global} ecModel
 * @private
 */
S
sushuang 已提交
1268
function prepareView(ecIns, type, ecModel, scheduler) {
S
sushuang 已提交
1269
    var isComponent = type === 'component';
S
sushuang 已提交
1270 1271 1272 1273
    var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
    var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
    var zr = ecIns._zr;
    var api = ecIns._api;
S
sushuang 已提交
1274 1275 1276

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

S
sushuang 已提交
1279 1280 1281 1282 1283
    isComponent
        ? ecModel.eachComponent(function (componentType, model) {
            componentType !== 'series' && doPrepare(model);
        })
        : ecModel.eachSeries(doPrepare);
1284

S
sushuang 已提交
1285
    function doPrepare(model) {
S
sushuang 已提交
1286 1287 1288 1289 1290 1291 1292 1293
        // 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 已提交
1294 1295

            if (__DEV__) {
S
sushuang 已提交
1296
                assert(Clazz, classType.sub + ' does not exist.');
1297
            }
S
sushuang 已提交
1298 1299

            view = new Clazz();
S
sushuang 已提交
1300
            view.init(ecModel, api);
S
sushuang 已提交
1301 1302 1303
            viewMap[viewId] = view;
            viewList.push(view);
            zr.add(view.group);
S
sushuang 已提交
1304
        }
1305

S
sushuang 已提交
1306 1307 1308 1309 1310 1311 1312
        model.__viewId = view.__id = viewId;
        view.__alive = true;
        view.__model = model;
        view.group.__ecComponentInfo = {
            mainType: model.mainType,
            index: model.componentIndex
        };
S
sushuang 已提交
1313
        !isComponent && scheduler.prepareView(view, model, ecModel, api);
S
sushuang 已提交
1314
    }
S
sushuang 已提交
1315 1316 1317 1318

    for (var i = 0; i < viewList.length;) {
        var view = viewList[i];
        if (!view.__alive) {
S
sushuang 已提交
1319
            view.renderTask.dispose();
S
sushuang 已提交
1320
            zr.remove(view.group);
S
sushuang 已提交
1321
            view.dispose(ecModel, api);
S
sushuang 已提交
1322 1323 1324 1325 1326 1327 1328
            viewList.splice(i, 1);
            delete viewMap[view.__id];
            view.__id = view.group.__ecComponentInfo = null;
        }
        else {
            i++;
        }
L
lang 已提交
1329
    }
S
sushuang 已提交
1330
}
1331

S
sushuang 已提交
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
/**
 * @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 已提交
1350

S
sushuang 已提交
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
// /**
//  * 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 已提交
1378
    });
S
sushuang 已提交
1379 1380
}

S
sushuang 已提交
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
function render(ecIns, ecModel, api, payload) {
    // Render all components
    each(ecIns._componentsViews, function (componentView) {
        var componentModel = componentView.__model;
        componentView.render(componentModel, ecModel, api, payload);

        updateZ(componentModel, componentView);
    });

    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 已提交
1404 1405 1406 1407
/**
 * Render each chart and component
 * @private
 */
S
sushuang 已提交
1408
function renderSeries(ecIns, ecModel, api, payload, dirtySeriesModels) {
S
sushuang 已提交
1409
    // Render all charts
S
sushuang 已提交
1410 1411
    var scheduler = ecIns._scheduler;
    var unfinished;
S
sushuang 已提交
1412
    dirtySeriesModels ? each(dirtySeriesModels, doEach) : ecModel.eachSeries(doEach);
S
sushuang 已提交
1413
    function doEach(seriesModel) {
S
sushuang 已提交
1414
        var chartView = ecIns._chartsMap[seriesModel.__viewId];
S
sushuang 已提交
1415
        chartView.__alive = true;
L
lang 已提交
1416

S
sushuang 已提交
1417
        var renderTask = chartView.renderTask;
S
sushuang 已提交
1418 1419 1420
        payload !== 'none' && (renderTask.context.payload = payload);
        dirtySeriesModels && renderTask.dirty();
        unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
L
lang 已提交
1421

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

S
sushuang 已提交
1424
        updateZ(seriesModel, chartView);
S
sushuang 已提交
1425

P
pissang 已提交
1426
        updateBlend(seriesModel, chartView);
S
sushuang 已提交
1427
    }
S
sushuang 已提交
1428
    scheduler.unfinished |= unfinished;
S
sushuang 已提交
1429 1430

    // If use hover layer
S
sushuang 已提交
1431 1432 1433
    // ??? updateHoverLayerStatus(this._zr, ecModel);
}

S
sushuang 已提交
1434 1435 1436
function performPostUpdateFuncs(ecModel, api) {
    each(postUpdateFuncs, function (func) {
        func(ecModel, api);
S
sushuang 已提交
1437
    });
S
tweak  
sushuang 已提交
1438 1439
}

S
sushuang 已提交
1440

S
sushuang 已提交
1441 1442 1443 1444
var MOUSE_EVENT_NAMES = [
    'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
    'mousedown', 'mouseup', 'globalout', 'contextmenu'
];
S
sushuang 已提交
1445

S
sushuang 已提交
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
/**
 * @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 已提交
1468

S
sushuang 已提交
1469 1470 1471 1472
            if (params) {
                params.event = e;
                params.type = eveName;
                this.trigger(eveName, params);
L
lang 已提交
1473
            }
S
sushuang 已提交
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505

        }, 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 已提交
1506
        }
S
sushuang 已提交
1507 1508 1509
        return;
    }
    this._disposed = true;
P
pah100 已提交
1510

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

S
sushuang 已提交
1513 1514
    var api = this._api;
    var ecModel = this._model;
P
pah100 已提交
1515

S
sushuang 已提交
1516 1517 1518 1519 1520 1521
    each(this._componentsViews, function (component) {
        component.dispose(ecModel, api);
    });
    each(this._chartsViews, function (chart) {
        chart.dispose(ecModel, api);
    });
1
100pah 已提交
1522

S
sushuang 已提交
1523 1524
    // Dispose after all views disposed
    this._zr.dispose();
1
100pah 已提交
1525

S
sushuang 已提交
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
    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 已提交
1544 1545
        });
    }
S
sushuang 已提交
1546
}
P
pah100 已提交
1547

S
sushuang 已提交
1548 1549 1550 1551 1552
/**
 * 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 已提交
1553
function updateBlend(seriesModel, chartView) {
S
sushuang 已提交
1554
    // Blend configration
S
sushuang 已提交
1555
    // ???
S
sushuang 已提交
1556 1557 1558 1559
    var blendMode = seriesModel.get('blendMode') || null;
    if (__DEV__) {
        if (!env.canvasSupported && blendMode && blendMode !== 'source-over') {
            console.warn('Only canvas support blendMode');
P
pah100 已提交
1560
        }
S
sushuang 已提交
1561 1562 1563 1564 1565 1566
    }
    chartView.group.traverse(function (el) {
        // FIXME marker and other components
        if (!el.isGroup) {
            el.setStyle('blend', blendMode);
        }
P
pissang 已提交
1567 1568 1569 1570 1571
        if (el.eachPendingDisplayable) {
            el.eachPendingDisplayable(function (displayable) {
                displayable.setStyle('blend', blendMode);
            });
        }
S
sushuang 已提交
1572 1573
    });
}
P
pah100 已提交
1574

S
sushuang 已提交
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
/**
 * @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 已提交
1587
        }
S
sushuang 已提交
1588 1589
    });
}
P
pah100 已提交
1590

S
sushuang 已提交
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
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;
1605
            }
1606
        }
S
sushuang 已提交
1607 1608
    });
}
L
lang 已提交
1609

S
sushuang 已提交
1610 1611 1612 1613 1614
/**
 * @type {Object} key: actionType.
 * @inner
 */
var actions = {};
L
lang 已提交
1615

S
sushuang 已提交
1616 1617 1618 1619 1620
/**
 * Map eventType to actionType
 * @type {Object}
 */
var eventActionMap = {};
L
lang 已提交
1621

S
sushuang 已提交
1622 1623 1624 1625 1626 1627
/**
 * Data processor functions of each stage
 * @type {Array.<Object.<string, Function>>}
 * @inner
 */
var dataProcessorFuncs = [];
L
lang 已提交
1628

S
sushuang 已提交
1629 1630 1631 1632 1633
/**
 * @type {Array.<Function>}
 * @inner
 */
var optionPreprocessorFuncs = [];
L
lang 已提交
1634

S
sushuang 已提交
1635 1636 1637 1638 1639
/**
 * @type {Array.<Function>}
 * @inner
 */
var postUpdateFuncs = [];
L
lang 已提交
1640

S
sushuang 已提交
1641 1642 1643 1644 1645
/**
 * Visual encoding functions of each stage
 * @type {Array.<Object.<string, Function>>}
 */
var visualFuncs = [];
S
sushuang 已提交
1646

S
sushuang 已提交
1647 1648 1649 1650 1651 1652 1653 1654 1655
/**
 * Theme storage
 * @type {Object.<key, Object>}
 */
var themeStorage = {};
/**
 * Loading effects
 */
var loadingEffects = {};
L
lang 已提交
1656

S
sushuang 已提交
1657 1658 1659 1660 1661 1662 1663
var instances = {};
var connectedGroups = {};

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

S
sushuang 已提交
1664 1665
var mapDataStores = {};

S
sushuang 已提交
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
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 已提交
1676
        }
S
sushuang 已提交
1677 1678
    }

S
sushuang 已提交
1679
    each(eventActionMap, function (actionType, eventType) {
S
sushuang 已提交
1680 1681 1682 1683 1684 1685 1686 1687 1688
        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 已提交
1689
                each(instances, function (otherChart) {
S
sushuang 已提交
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717
                    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 已提交
1718
export function init(dom, theme, opts) {
S
sushuang 已提交
1719 1720
    if (__DEV__) {
        // Check version
S
sushuang 已提交
1721
        if ((zrender.version.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
S
sushuang 已提交
1722
            throw new Error(
S
sushuang 已提交
1723
                'zrender/src ' + zrender.version
S
sushuang 已提交
1724
                + ' is too old for ECharts ' + version
S
sushuang 已提交
1725
                + '. Current version need ZRender '
S
sushuang 已提交
1726
                + dependencies.zrender + '+'
S
sushuang 已提交
1727
            );
P
pissang 已提交
1728
        }
S
sushuang 已提交
1729 1730 1731

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

S
sushuang 已提交
1735
    var existInstance = getInstanceByDom(dom);
S
sushuang 已提交
1736 1737 1738
    if (existInstance) {
        if (__DEV__) {
            console.warn('There is a chart instance already initialized on the dom.');
P
pissang 已提交
1739
        }
S
sushuang 已提交
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
        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 已提交
1752
        }
S
sushuang 已提交
1753
    }
P
pah100 已提交
1754

S
sushuang 已提交
1755 1756 1757
    var chart = new ECharts(dom, theme, opts);
    chart.id = 'ec_' + idBase++;
    instances[chart.id] = chart;
L
lang 已提交
1758

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

S
sushuang 已提交
1761
    enableConnect(chart);
1762

S
sushuang 已提交
1763
    return chart;
S
sushuang 已提交
1764
}
S
sushuang 已提交
1765 1766 1767 1768

/**
 * @return {string|Array.<module:echarts~ECharts>} groupId
 */
S
sushuang 已提交
1769
export function connect(groupId) {
S
sushuang 已提交
1770 1771 1772 1773 1774
    // Is array of charts
    if (zrUtil.isArray(groupId)) {
        var charts = groupId;
        groupId = null;
        // If any chart has group
S
sushuang 已提交
1775
        each(charts, function (chart) {
S
sushuang 已提交
1776 1777
            if (chart.group != null) {
                groupId = chart.group;
1778
            }
1779
        });
S
sushuang 已提交
1780
        groupId = groupId || ('g_' + groupIdBase++);
S
sushuang 已提交
1781
        each(charts, function (chart) {
S
sushuang 已提交
1782 1783 1784 1785 1786
            chart.group = groupId;
        });
    }
    connectedGroups[groupId] = true;
    return groupId;
S
sushuang 已提交
1787
}
L
lang 已提交
1788

S
sushuang 已提交
1789 1790 1791 1792
/**
 * @DEPRECATED
 * @return {string} groupId
 */
S
sushuang 已提交
1793
export function disConnect(groupId) {
S
sushuang 已提交
1794
    connectedGroups[groupId] = false;
S
sushuang 已提交
1795
}
1796

S
sushuang 已提交
1797 1798 1799
/**
 * @return {string} groupId
 */
S
sushuang 已提交
1800
export var disconnect = disConnect;
L
lang 已提交
1801

S
sushuang 已提交
1802 1803 1804 1805
/**
 * Dispose a chart instance
 * @param  {module:echarts~ECharts|HTMLDomElement|string} chart
 */
S
sushuang 已提交
1806
export function dispose(chart) {
S
sushuang 已提交
1807 1808 1809 1810 1811
    if (typeof chart === 'string') {
        chart = instances[chart];
    }
    else if (!(chart instanceof ECharts)){
        // Try to treat as dom
S
sushuang 已提交
1812
        chart = getInstanceByDom(chart);
S
sushuang 已提交
1813 1814 1815 1816
    }
    if ((chart instanceof ECharts) && !chart.isDisposed()) {
        chart.dispose();
    }
S
sushuang 已提交
1817
}
1818

S
sushuang 已提交
1819 1820 1821 1822
/**
 * @param  {HTMLElement} dom
 * @return {echarts~ECharts}
 */
S
sushuang 已提交
1823
export function getInstanceByDom(dom) {
S
sushuang 已提交
1824
    return instances[modelUtil.getAttribute(dom, DOM_ATTRIBUTE_KEY)];
S
sushuang 已提交
1825
}
1
100pah 已提交
1826

S
sushuang 已提交
1827 1828 1829 1830
/**
 * @param {string} key
 * @return {echarts~ECharts}
 */
S
sushuang 已提交
1831
export function getInstanceById(key) {
S
sushuang 已提交
1832
    return instances[key];
S
sushuang 已提交
1833
}
P
pah100 已提交
1834

S
sushuang 已提交
1835 1836 1837
/**
 * Register theme
 */
S
sushuang 已提交
1838
export function registerTheme(name, theme) {
S
sushuang 已提交
1839
    themeStorage[name] = theme;
S
sushuang 已提交
1840
}
L
lang 已提交
1841

S
sushuang 已提交
1842 1843 1844 1845
/**
 * Register option preprocessor
 * @param {Function} preprocessorFunc
 */
S
sushuang 已提交
1846
export function registerPreprocessor(preprocessorFunc) {
S
sushuang 已提交
1847
    optionPreprocessorFuncs.push(preprocessorFunc);
S
sushuang 已提交
1848
}
1849

S
sushuang 已提交
1850 1851
/**
 * @param {number} [priority=1000]
S
sushuang 已提交
1852
 * @param {Object|Function} processor
S
sushuang 已提交
1853
 */
S
sushuang 已提交
1854 1855
export function registerProcessor(priority, processor) {
    normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
S
sushuang 已提交
1856
}
L
lang 已提交
1857

S
sushuang 已提交
1858 1859 1860 1861
/**
 * Register postUpdater
 * @param {Function} postUpdateFunc
 */
S
sushuang 已提交
1862
export function registerPostUpdate(postUpdateFunc) {
S
sushuang 已提交
1863
    postUpdateFuncs.push(postUpdateFunc);
S
sushuang 已提交
1864
}
L
Update  
lang 已提交
1865

S
sushuang 已提交
1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881
/**
 * 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 已提交
1882
export function registerAction(actionInfo, eventName, action) {
S
sushuang 已提交
1883 1884 1885 1886
    if (typeof eventName === 'function') {
        action = eventName;
        eventName = '';
    }
S
sushuang 已提交
1887
    var actionType = isObject(actionInfo)
S
sushuang 已提交
1888 1889 1890 1891
        ? actionInfo.type
        : ([actionInfo, actionInfo = {
            event: eventName
        }][0]);
L
lang 已提交
1892

S
sushuang 已提交
1893 1894 1895
    // Event name is all lowercase
    actionInfo.event = (actionInfo.event || actionType).toLowerCase();
    eventName = actionInfo.event;
L
Update  
lang 已提交
1896

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

S
sushuang 已提交
1900 1901 1902 1903
    if (!actions[actionType]) {
        actions[actionType] = {action: action, actionInfo: actionInfo};
    }
    eventActionMap[eventName] = actionType;
S
sushuang 已提交
1904
}
P
pah100 已提交
1905

S
sushuang 已提交
1906 1907 1908 1909
/**
 * @param {string} type
 * @param {*} CoordinateSystem
 */
S
sushuang 已提交
1910
export function registerCoordinateSystem(type, CoordinateSystem) {
S
sushuang 已提交
1911
    CoordinateSystemManager.register(type, CoordinateSystem);
S
sushuang 已提交
1912
}
L
lang 已提交
1913

S
sushuang 已提交
1914 1915 1916 1917 1918
/**
 * Get dimensions of specified coordinate system.
 * @param {string} type
 * @return {Array.<string|Object>}
 */
S
sushuang 已提交
1919
export function getCoordinateSystemDimensions(type) {
S
sushuang 已提交
1920 1921 1922 1923 1924 1925
    var coordSysCreator = CoordinateSystemManager.get(type);
    if (coordSysCreator) {
        return coordSysCreator.getDimensionsInfo
                ? coordSysCreator.getDimensionsInfo()
                : coordSysCreator.dimensions.slice();
    }
S
sushuang 已提交
1926
}
1927

S
sushuang 已提交
1928 1929 1930 1931 1932 1933
/**
 * 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 已提交
1934
 * @param {Function} layoutTask
S
sushuang 已提交
1935
 */
S
sushuang 已提交
1936
export function registerLayout(priority, layoutTask) {
S
sushuang 已提交
1937
    normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
S
sushuang 已提交
1938
}
P
pah100 已提交
1939

S
sushuang 已提交
1940 1941
/**
 * @param {number} [priority=3000]
S
sushuang 已提交
1942
 * @param {module:echarts/stream/Task} visualTask
S
sushuang 已提交
1943
 */
S
sushuang 已提交
1944
export function registerVisual(priority, visualTask) {
S
sushuang 已提交
1945
    normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
S
sushuang 已提交
1946 1947
}

S
sushuang 已提交
1948
/**
S
sushuang 已提交
1949
 * @param {Object|Function} fn: {seriesType, processRawSeries, reset}
S
sushuang 已提交
1950
 */
S
sushuang 已提交
1951
function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
S
sushuang 已提交
1952
    if (isFunction(priority) || isObject(priority)) {
S
sushuang 已提交
1953 1954
        fn = priority;
        priority = defaultPriority;
S
sushuang 已提交
1955
    }
S
sushuang 已提交
1956

S
sushuang 已提交
1957
    if (__DEV__) {
S
sushuang 已提交
1958 1959
        if (isNaN(priority) || priority == null) {
            throw new Error('Illegal priority');
1960
        }
S
sushuang 已提交
1961
        // Check duplicate
S
sushuang 已提交
1962
        each(targetList, function (wrap) {
S
sushuang 已提交
1963
            assert(wrap.__raw !== fn);
S
sushuang 已提交
1964
        });
S
sushuang 已提交
1965
    }
S
sushuang 已提交
1966

S
sushuang 已提交
1967 1968 1969 1970
    var stageHandler = Scheduler.wrapStageHandler(fn, visualType);

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

S
sushuang 已提交
1973
    return stageHandler;
S
sushuang 已提交
1974
}
S
sushuang 已提交
1975 1976 1977 1978

/**
 * @param {string} name
 */
S
sushuang 已提交
1979
export function registerLoading(name, loadingFx) {
S
sushuang 已提交
1980
    loadingEffects[name] = loadingFx;
S
sushuang 已提交
1981
}
S
sushuang 已提交
1982 1983 1984 1985 1986

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

/**
 * @param {Object} opts
 * @param {string} [superClass]
 */
S
sushuang 已提交
2000
export function extendComponentView(opts/*, superClass*/) {
S
sushuang 已提交
2001 2002 2003 2004 2005 2006
    // var Clazz = ComponentView;
    // if (superClass) {
    //     var classType = parseClassType(superClass);
    //     Clazz = ComponentView.getClass(classType.main, classType.sub, true);
    // }
    return ComponentView.extend(opts);
S
sushuang 已提交
2007
}
S
sushuang 已提交
2008 2009 2010 2011 2012

/**
 * @param {Object} opts
 * @param {string} [superClass]
 */
S
sushuang 已提交
2013
export function extendSeriesModel(opts/*, superClass*/) {
S
sushuang 已提交
2014 2015 2016 2017 2018 2019 2020
    // 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 已提交
2021
}
S
sushuang 已提交
2022 2023 2024 2025 2026

/**
 * @param {Object} opts
 * @param {string} [superClass]
 */
S
sushuang 已提交
2027
export function extendChartView(opts/*, superClass*/) {
S
sushuang 已提交
2028 2029 2030 2031 2032 2033 2034
    // 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 已提交
2035
}
S
sushuang 已提交
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052

/**
 * 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 已提交
2053
export function setCanvasCreator(creator) {
S
sushuang 已提交
2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092
    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 已提交
2093
}
S
sushuang 已提交
2094

S
sushuang 已提交
2095 2096 2097
registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
registerPreprocessor(backwardCompat);
registerLoading('default', loadingDefault);
S
sushuang 已提交
2098

S
sushuang 已提交
2099 2100
// Default actions

S
sushuang 已提交
2101
registerAction({
S
sushuang 已提交
2102 2103 2104 2105
    type: 'highlight',
    event: 'highlight',
    update: 'highlight'
}, zrUtil.noop);
S
sushuang 已提交
2106

S
sushuang 已提交
2107
registerAction({
S
sushuang 已提交
2108 2109 2110 2111 2112
    type: 'downplay',
    event: 'downplay',
    update: 'downplay'
}, zrUtil.noop);

S
sushuang 已提交
2113

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