custom.ts 26.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/

S
sushuang 已提交
20
import {__DEV__} from '../config';
S
sushuang 已提交
21
import * as zrUtil from 'zrender/src/core/util';
S
sushuang 已提交
22
import * as graphicUtil from '../util/graphic';
23
import {getDefaultLabel} from './helper/labelHelper';
S
sushuang 已提交
24
import createListFromArray from './helper/createListFromArray';
25
import {getLayoutOnAxis} from '../layout/barGrid';
S
sushuang 已提交
26
import DataDiffer from '../data/DataDiffer';
27
import SeriesModel from '../model/Series';
28
import Model from '../model/Model';
29
import ChartView from '../view/Chart';
30
import {createClipPath} from './helper/createClipPathFromCoordSys';
S
sushuang 已提交
31 32 33 34 35 36 37

import prepareCartesian2d from '../coord/cartesian/prepareCustom';
import prepareGeo from '../coord/geo/prepareCustom';
import prepareSingleAxis from '../coord/single/prepareCustom';
import preparePolar from '../coord/polar/prepareCustom';
import prepareCalendar from '../coord/calendar/prepareCustom';

38
var CACHED_LABEL_STYLE_PROPERTIES = graphicUtil.CACHED_LABEL_STYLE_PROPERTIES;
39 40 41 42
var ITEM_STYLE_NORMAL_PATH = ['itemStyle'];
var ITEM_STYLE_EMPHASIS_PATH = ['emphasis', 'itemStyle'];
var LABEL_NORMAL = ['label'];
var LABEL_EMPHASIS = ['emphasis', 'label'];
S
sushuang 已提交
43 44 45 46
// Use prefix to avoid index to be the same as el.name,
// which will cause weird udpate animation.
var GROUP_DIFF_PREFIX = 'e\0\0';

47

S
sushuang 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
/**
 * To reduce total package size of each coordinate systems, the modules `prepareCustom`
 * of each coordinate systems are not required by each coordinate systems directly, but
 * required by the module `custom`.
 *
 * prepareInfoForCustomSeries {Function}: optional
 *     @return {Object} {coordSys: {...}, api: {
 *         coord: function (data, clamp) {}, // return point in global.
 *         size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
 *     }}
 */
var prepareCustoms = {
    cartesian2d: prepareCartesian2d,
    geo: prepareGeo,
    singleAxis: prepareSingleAxis,
    polar: preparePolar,
    calendar: prepareCalendar
};

67

S
sushuang 已提交
68 69 70 71
// ------
// Model
// ------

72
SeriesModel.extend({
S
sushuang 已提交
73 74 75 76 77 78 79 80 81

    type: 'series.custom',

    dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],

    defaultOption: {
        coordinateSystem: 'cartesian2d', // Can be set as 'none'
        zlevel: 0,
        z: 2,
82 83
        legendHoverLink: true,

84 85 86 87 88 89 90
        useTransform: true,

        // Custom series will not clip by default.
        // Some case will use custom series to draw label
        // For example https://echarts.apache.org/examples/en/editor.html?c=custom-gantt-flight
        // Only works on polar and cartesian2d coordinate system.
        clip: false
S
sushuang 已提交
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105

        // Cartesian coordinate system
        // xAxisIndex: 0,
        // yAxisIndex: 0,

        // Polar coordinate system
        // polarIndex: 0,

        // Geo coordinate system
        // geoIndex: 0,

        // label: {}
        // itemStyle: {}
    },

106 107 108
    /**
     * @override
     */
S
sushuang 已提交
109
    getInitialData: function (option, ecModel) {
110
        return createListFromArray(this.getSource(), this);
111 112 113 114 115 116 117 118 119
    },

    /**
     * @override
     */
    getDataParams: function (dataIndex, dataType, el) {
        var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
        el && (params.info = el.info);
        return params;
S
sushuang 已提交
120 121
    }
});
P
pah100 已提交
122

S
sushuang 已提交
123 124 125
// -----
// View
// -----
P
pah100 已提交
126

127
ChartView.extend({
P
pah100 已提交
128

S
sushuang 已提交
129
    type: 'custom',
P
pah100 已提交
130

S
sushuang 已提交
131 132 133 134 135
    /**
     * @private
     * @type {module:echarts/data/List}
     */
    _data: null,
P
pah100 已提交
136

S
sushuang 已提交
137 138 139
    /**
     * @override
     */
140
    render: function (customSeries, ecModel, api, payload) {
S
sushuang 已提交
141 142 143 144 145
        var oldData = this._data;
        var data = customSeries.getData();
        var group = this.group;
        var renderItem = makeRenderItem(customSeries, data, ecModel, api);

146 147 148 149 150
        // By default, merge mode is applied. In most cases, custom series is
        // used in the scenario that data amount is not large but graphic elements
        // is complicated, where merge mode is probably necessary for optimization.
        // For example, reuse graphic elements and only update the transform when
        // roam or data zoom according to `actionType`.
S
sushuang 已提交
151 152
        data.diff(oldData)
            .add(function (newIdx) {
153
                createOrUpdate(
154
                    null, newIdx, renderItem(newIdx, payload), customSeries, group, data
S
sushuang 已提交
155 156 157 158
                );
            })
            .update(function (newIdx, oldIdx) {
                var el = oldData.getItemGraphicEl(oldIdx);
159
                createOrUpdate(
160
                    el, newIdx, renderItem(newIdx, payload), customSeries, group, data
161
                );
S
sushuang 已提交
162 163 164 165 166 167
            })
            .remove(function (oldIdx) {
                var el = oldData.getItemGraphicEl(oldIdx);
                el && group.remove(el);
            })
            .execute();
P
pah100 已提交
168

169
        // Do clipping
170
        var clipPath = customSeries.get('clip', true)
171 172 173 174 175 176 177 178 179
            ? createClipPath(customSeries.coordinateSystem, false, customSeries)
            : null;
        if (clipPath) {
            group.setClipPath(clipPath);
        }
        else {
            group.removeClipPath();
        }

S
sushuang 已提交
180 181
        this._data = data;
    },
P
pah100 已提交
182

P
pissang 已提交
183 184 185 186 187
    incrementalPrepareRender: function (customSeries, ecModel, api) {
        this.group.removeAll();
        this._data = null;
    },

188
    incrementalRender: function (params, customSeries, ecModel, api, payload) {
P
pissang 已提交
189 190 191 192 193 194 195 196 197
        var data = customSeries.getData();
        var renderItem = makeRenderItem(customSeries, data, ecModel, api);
        function setIncrementalAndHoverLayer(el) {
            if (!el.isGroup) {
                el.incremental = true;
                el.useHoverLayer = true;
            }
        }
        for (var idx = params.start; idx < params.end; idx++) {
198
            var el = createOrUpdate(null, idx, renderItem(idx, payload), customSeries, this.group, data);
P
pissang 已提交
199 200 201 202
            el.traverse(setIncrementalAndHoverLayer);
        }
    },

S
sushuang 已提交
203 204 205
    /**
     * @override
     */
206 207 208 209 210 211
    dispose: zrUtil.noop,

    /**
     * @override
     */
    filterForExposedEvent: function (eventType, query, targetEl, packedEvent) {
212 213
        var elementName = query.element;
        if (elementName == null || targetEl.name === elementName) {
214 215 216 217 218 219
            return true;
        }

        // Enable to give a name on a group made by `renderItem`, and listen
        // events that triggerd by its descendents.
        while ((targetEl = targetEl.parent) && targetEl !== this.group) {
220
            if (targetEl.name === elementName) {
221 222 223 224 225 226
                return true;
            }
        }

        return false;
    }
S
sushuang 已提交
227
});
P
pah100 已提交
228 229


S
sushuang 已提交
230 231 232 233
function createEl(elOption) {
    var graphicType = elOption.type;
    var el;

234 235
    // Those graphic elements are not shapes. They should not be
    // overwritten by users, so do them first.
S
sushuang 已提交
236 237
    if (graphicType === 'path') {
        var shape = elOption.shape;
S
sushuang 已提交
238 239 240
        // Using pathRect brings convenience to users sacle svg path.
        var pathRect = (shape.width != null && shape.height != null)
            ? {
S
sushuang 已提交
241 242
                x: shape.x || 0,
                y: shape.y || 0,
S
sushuang 已提交
243 244 245 246
                width: shape.width,
                height: shape.height
            }
            : null;
S
sushuang 已提交
247
        var pathData = getPathData(shape);
S
sushuang 已提交
248 249 250
        // Path is also used for icon, so layout 'center' by default.
        el = graphicUtil.makePath(pathData, null, pathRect, shape.layout || 'center');
        el.__customPathData = pathData;
S
sushuang 已提交
251 252
    }
    else if (graphicType === 'image') {
253
        el = new graphicUtil.Image({});
S
sushuang 已提交
254 255 256
        el.__customImagePath = elOption.style.image;
    }
    else if (graphicType === 'text') {
257
        el = new graphicUtil.Text({});
S
sushuang 已提交
258 259
        el.__customText = elOption.style.text;
    }
260 261 262 263 264 265
    else if (graphicType === 'group') {
        el = new graphicUtil.Group();
    }
    else if (graphicType === 'compoundPath') {
        throw new Error('"compoundPath" is not supported yet.');
    }
S
sushuang 已提交
266
    else {
267
        var Clz = graphicUtil.getShapeClass(graphicType);
P
pah100 已提交
268

S
sushuang 已提交
269 270
        if (__DEV__) {
            zrUtil.assert(Clz, 'graphic type "' + graphicType + '" can not be found.');
P
pah100 已提交
271 272
        }

S
sushuang 已提交
273 274
        el = new Clz();
    }
P
pah100 已提交
275

S
sushuang 已提交
276 277
    el.__customGraphicType = graphicType;
    el.name = elOption.name;
P
pah100 已提交
278

S
sushuang 已提交
279 280
    return el;
}
P
pah100 已提交
281

S
sushuang 已提交
282
function updateEl(el, dataIndex, elOption, animatableModel, data, isInit, isRoot) {
283
    var transitionProps = {};
S
sushuang 已提交
284
    var elOptionStyle = elOption.style || {};
P
pah100 已提交
285

286 287 288 289 290
    elOption.shape && (transitionProps.shape = zrUtil.clone(elOption.shape));
    elOption.position && (transitionProps.position = elOption.position.slice());
    elOption.scale && (transitionProps.scale = elOption.scale.slice());
    elOption.origin && (transitionProps.origin = elOption.origin.slice());
    elOption.rotation && (transitionProps.rotation = elOption.rotation);
P
pah100 已提交
291

S
sushuang 已提交
292
    if (el.type === 'image' && elOption.style) {
293
        var targetStyle = transitionProps.style = {};
S
sushuang 已提交
294 295 296
        zrUtil.each(['x', 'y', 'width', 'height'], function (prop) {
            prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
        });
P
pah100 已提交
297 298
    }

S
sushuang 已提交
299
    if (el.type === 'text' && elOption.style) {
300
        var targetStyle = transitionProps.style = {};
S
sushuang 已提交
301 302 303 304 305 306 307 308 309 310 311 312
        zrUtil.each(['x', 'y'], function (prop) {
            prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
        });
        // Compatible with previous: both support
        // textFill and fill, textStroke and stroke in 'text' element.
        !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
            elOptionStyle.textFill = elOptionStyle.fill
        );
        !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
            elOptionStyle.textStroke = elOptionStyle.stroke
        );
    }
P
pah100 已提交
313

S
sushuang 已提交
314 315
    if (el.type !== 'group') {
        el.useStyle(elOptionStyle);
P
pah100 已提交
316

S
sushuang 已提交
317 318 319 320 321 322
        // Init animation.
        if (isInit) {
            el.style.opacity = 0;
            var targetOpacity = elOptionStyle.opacity;
            targetOpacity == null && (targetOpacity = 1);
            graphicUtil.initProps(el, {style: {opacity: targetOpacity}}, animatableModel, dataIndex);
P
pah100 已提交
323
        }
S
sushuang 已提交
324
    }
P
pah100 已提交
325

S
sushuang 已提交
326
    if (isInit) {
327
        el.attr(transitionProps);
S
sushuang 已提交
328 329
    }
    else {
330
        graphicUtil.updateProps(el, transitionProps, animatableModel, dataIndex);
S
sushuang 已提交
331
    }
P
pah100 已提交
332

333
    // Merge by default.
S
sushuang 已提交
334
    // z2 must not be null/undefined, otherwise sort error may occur.
335 336 337 338 339 340 341 342
    elOption.hasOwnProperty('z2') && el.attr('z2', elOption.z2 || 0);
    elOption.hasOwnProperty('silent') && el.attr('silent', elOption.silent);
    elOption.hasOwnProperty('invisible') && el.attr('invisible', elOption.invisible);
    elOption.hasOwnProperty('ignore') && el.attr('ignore', elOption.ignore);
    // `elOption.info` enables user to mount some info on
    // elements and use them in event handlers.
    // Update them only when user specified, otherwise, remain.
    elOption.hasOwnProperty('info') && el.attr('info', elOption.info);
P
pah100 已提交
343

S
sushuang 已提交
344 345 346
    // If `elOption.styleEmphasis` is `false`, remove hover style. The
    // logic is ensured by `graphicUtil.setElementHoverStyle`.
    var styleEmphasis = elOption.styleEmphasis;
347 348 349
    // hoverStyle should always be set here, because if the hover style
    // may already be changed, where the inner cache should be reset.
    graphicUtil.setElementHoverStyle(el, styleEmphasis);
350
    if (isRoot) {
351
        graphicUtil.setAsHighDownDispatcher(el, styleEmphasis !== false);
352
    }
S
sushuang 已提交
353
}
P
pah100 已提交
354

S
sushuang 已提交
355 356 357 358
function prepareStyleTransition(prop, targetStyle, elOptionStyle, oldElStyle, isInit) {
    if (elOptionStyle[prop] != null && !isInit) {
        targetStyle[prop] = elOptionStyle[prop];
        elOptionStyle[prop] = oldElStyle[prop];
P
pah100 已提交
359
    }
S
sushuang 已提交
360 361 362 363 364 365 366 367 368 369 370 371 372 373
}

function makeRenderItem(customSeries, data, ecModel, api) {
    var renderItem = customSeries.get('renderItem');
    var coordSys = customSeries.coordinateSystem;
    var prepareResult = {};

    if (coordSys) {
        if (__DEV__) {
            zrUtil.assert(renderItem, 'series.render is required.');
            zrUtil.assert(
                coordSys.prepareCustoms || prepareCustoms[coordSys.type],
                'This coordSys does not support custom series.'
            );
P
pah100 已提交
374 375
        }

S
sushuang 已提交
376 377 378 379
        prepareResult = coordSys.prepareCustoms
            ? coordSys.prepareCustoms()
            : prepareCustoms[coordSys.type](coordSys);
    }
P
pah100 已提交
380

S
sushuang 已提交
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
    var userAPI = zrUtil.defaults({
        getWidth: api.getWidth,
        getHeight: api.getHeight,
        getZr: api.getZr,
        getDevicePixelRatio: api.getDevicePixelRatio,
        value: value,
        style: style,
        styleEmphasis: styleEmphasis,
        visual: visual,
        barLayout: barLayout,
        currentSeriesIndices: currentSeriesIndices,
        font: font
    }, prepareResult.api || {});

    var userParams = {
S
tweak.  
sushuang 已提交
396 397 398
        // The life cycle of context: current round of rendering.
        // The global life cycle is probably not necessary, because
        // user can store global status by themselves.
S
sushuang 已提交
399 400 401 402 403 404 405 406
        context: {},
        seriesId: customSeries.id,
        seriesName: customSeries.name,
        seriesIndex: customSeries.seriesIndex,
        coordSys: prepareResult.coordSys,
        dataInsideLength: data.count(),
        encode: wrapEncodeDef(customSeries.getData())
    };
P
pah100 已提交
407

S
sushuang 已提交
408 409 410 411 412 413 414 415
    // Do not support call `api` asynchronously without dataIndexInside input.
    var currDataIndexInside;
    var currDirty = true;
    var currItemModel;
    var currLabelNormalModel;
    var currLabelEmphasisModel;
    var currVisualColor;

416
    return function (dataIndexInside, payload) {
S
sushuang 已提交
417 418
        currDataIndexInside = dataIndexInside;
        currDirty = true;
419

S
sushuang 已提交
420 421 422
        return renderItem && renderItem(
            zrUtil.defaults({
                dataIndexInside: dataIndexInside,
423 424 425
                dataIndex: data.getRawIndex(dataIndexInside),
                // Can be used for optimization when zoom or roam.
                actionType: payload ? payload.type : null
S
sushuang 已提交
426 427
            }, userParams),
            userAPI
S
sushuang 已提交
428
        );
S
sushuang 已提交
429
    };
P
pah100 已提交
430

S
sushuang 已提交
431 432 433 434 435 436 437 438 439 440
    // Do not update cache until api called.
    function updateCache(dataIndexInside) {
        dataIndexInside == null && (dataIndexInside = currDataIndexInside);
        if (currDirty) {
            currItemModel = data.getItemModel(dataIndexInside);
            currLabelNormalModel = currItemModel.getModel(LABEL_NORMAL);
            currLabelEmphasisModel = currItemModel.getModel(LABEL_EMPHASIS);
            currVisualColor = data.getItemVisual(dataIndexInside, 'color');

            currDirty = false;
P
pah100 已提交
441
        }
S
sushuang 已提交
442
    }
P
pah100 已提交
443

S
sushuang 已提交
444 445 446 447 448 449 450 451 452 453
    /**
     * @public
     * @param {number|string} dim
     * @param {number} [dataIndexInside=currDataIndexInside]
     * @return {number|string} value
     */
    function value(dim, dataIndexInside) {
        dataIndexInside == null && (dataIndexInside = currDataIndexInside);
        return data.get(data.getDimension(dim || 0), dataIndexInside);
    }
P
pah100 已提交
454

S
sushuang 已提交
455 456 457 458 459 460 461 462 463 464 465 466
    /**
     * By default, `visual` is applied to style (to support visualMap).
     * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
     * it can be implemented as:
     * `api.style({stroke: api.visual('color'), fill: null})`;
     * @public
     * @param {Object} [extra]
     * @param {number} [dataIndexInside=currDataIndexInside]
     */
    function style(extra, dataIndexInside) {
        dataIndexInside == null && (dataIndexInside = currDataIndexInside);
        updateCache(dataIndexInside);
P
pah100 已提交
467

S
sushuang 已提交
468
        var itemStyle = currItemModel.getModel(ITEM_STYLE_NORMAL_PATH).getItemStyle();
P
pah100 已提交
469

S
sushuang 已提交
470 471 472
        currVisualColor != null && (itemStyle.fill = currVisualColor);
        var opacity = data.getItemVisual(dataIndexInside, 'opacity');
        opacity != null && (itemStyle.opacity = opacity);
P
pah100 已提交
473

474 475 476 477 478
        var labelModel = extra
            ? applyExtraBefore(extra, currLabelNormalModel)
            : currLabelNormalModel;

        graphicUtil.setTextStyle(itemStyle, labelModel, null, {
S
sushuang 已提交
479 480 481
            autoColor: currVisualColor,
            isRectText: true
        });
P
pah100 已提交
482

483
        itemStyle.text = labelModel.getShallow('show')
S
sushuang 已提交
484 485 486 487 488
            ? zrUtil.retrieve2(
                customSeries.getFormattedLabel(dataIndexInside, 'normal'),
                getDefaultLabel(data, dataIndexInside)
            )
            : null;
P
pah100 已提交
489

490 491
        extra && applyExtraAfter(itemStyle, extra);

S
sushuang 已提交
492 493
        return itemStyle;
    }
P
pah100 已提交
494

S
sushuang 已提交
495 496 497 498 499 500 501 502 503 504 505
    /**
     * @public
     * @param {Object} [extra]
     * @param {number} [dataIndexInside=currDataIndexInside]
     */
    function styleEmphasis(extra, dataIndexInside) {
        dataIndexInside == null && (dataIndexInside = currDataIndexInside);
        updateCache(dataIndexInside);

        var itemStyle = currItemModel.getModel(ITEM_STYLE_EMPHASIS_PATH).getItemStyle();

506 507 508 509 510
        var labelModel = extra
            ? applyExtraBefore(extra, currLabelEmphasisModel)
            : currLabelEmphasisModel;

        graphicUtil.setTextStyle(itemStyle, labelModel, null, {
S
sushuang 已提交
511 512 513
            isRectText: true
        }, true);

514
        itemStyle.text = labelModel.getShallow('show')
S
sushuang 已提交
515 516 517 518 519 520
            ? zrUtil.retrieve3(
                customSeries.getFormattedLabel(dataIndexInside, 'emphasis'),
                customSeries.getFormattedLabel(dataIndexInside, 'normal'),
                getDefaultLabel(data, dataIndexInside)
            )
            : null;
P
pah100 已提交
521

522 523
        extra && applyExtraAfter(itemStyle, extra);

S
sushuang 已提交
524
        return itemStyle;
P
pah100 已提交
525 526
    }

S
sushuang 已提交
527 528 529 530 531 532 533 534
    /**
     * @public
     * @param {string} visualType
     * @param {number} [dataIndexInside=currDataIndexInside]
     */
    function visual(visualType, dataIndexInside) {
        dataIndexInside == null && (dataIndexInside = currDataIndexInside);
        return data.getItemVisual(dataIndexInside, visualType);
P
pah100 已提交
535 536
    }

S
sushuang 已提交
537 538 539 540 541
    /**
     * @public
     * @param {number} opt.count Positive interger.
     * @param {number} [opt.barWidth]
     * @param {number} [opt.barMaxWidth]
S
SHUANG SU 已提交
542
     * @param {number} [opt.barMinWidth]
S
sushuang 已提交
543 544 545 546 547 548 549
     * @param {number} [opt.barGap]
     * @param {number} [opt.barCategoryGap]
     * @return {Object} {width, offset, offsetCenter} is not support, return undefined.
     */
    function barLayout(opt) {
        if (coordSys.getBaseAxis) {
            var baseAxis = coordSys.getBaseAxis();
550
            return getLayoutOnAxis(zrUtil.defaults({axis: baseAxis}, opt), api);
551
        }
P
pah100 已提交
552 553
    }

S
sushuang 已提交
554 555 556 557 558 559
    /**
     * @public
     * @return {Array.<number>}
     */
    function currentSeriesIndices() {
        return ecModel.getCurrentSeriesIndices();
560 561
    }

S
sushuang 已提交
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
    /**
     * @public
     * @param {Object} opt
     * @param {string} [opt.fontStyle]
     * @param {number} [opt.fontWeight]
     * @param {number} [opt.fontSize]
     * @param {string} [opt.fontFamily]
     * @return {string} font string
     */
    function font(opt) {
        return graphicUtil.getFont(opt, ecModel);
    }
}

function wrapEncodeDef(data) {
    var encodeDef = {};
    zrUtil.each(data.dimensions, function (dimName, dataDimIndex) {
        var dimInfo = data.getDimensionInfo(dimName);
        if (!dimInfo.isExtraCoord) {
            var coordDim = dimInfo.coordDim;
            var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
            dataDims[dimInfo.coordDimIndex] = dataDimIndex;
        }
    });
    return encodeDef;
}

function createOrUpdate(el, dataIndex, elOption, animatableModel, group, data) {
S
sushuang 已提交
590
    el = doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data, true);
S
sushuang 已提交
591
    el && data.setItemGraphicEl(dataIndex, el);
P
pissang 已提交
592 593

    return el;
S
sushuang 已提交
594 595
}

S
sushuang 已提交
596
function doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data, isRoot) {
597

S
sushuang 已提交
598 599 600 601 602 603 604 605 606 607 608 609
    // [Rule]
    // By default, follow merge mode.
    //     (It probably brings benifit for performance in some cases of large data, where
    //     user program can be optimized to that only updated props needed to be re-calculated,
    //     or according to `actionType` some calculation can be skipped.)
    // If `renderItem` returns `null`/`undefined`/`false`, remove the previous el if existing.
    //     (It seems that violate the "merge" principle, but most of users probably intuitively
    //     regard "return;" as "show nothing element whatever", so make a exception to meet the
    //     most cases.)

    var simplyRemove = !elOption; // `null`/`undefined`/`false`
    elOption = elOption || {};
S
sushuang 已提交
610
    var elOptionType = elOption.type;
S
sushuang 已提交
611 612 613
    var elOptionShape = elOption.shape;
    var elOptionStyle = elOption.style;

614
    if (el && (
S
sushuang 已提交
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
        simplyRemove
        // || elOption.$merge === false
        // If `elOptionType` is `null`, follow the merge principle.
        || (elOptionType != null
            && elOptionType !== el.__customGraphicType
        )
        || (elOptionType === 'path'
            && hasOwnPathData(elOptionShape) && getPathData(elOptionShape) !== el.__customPathData
        )
        || (elOptionType === 'image'
            && hasOwn(elOptionStyle, 'image') && elOptionStyle.image !== el.__customImagePath
        )
        // FIXME test and remove this restriction?
        || (elOptionType === 'text'
            && hasOwn(elOptionShape, 'text') && elOptionStyle.text !== el.__customText
630 631
        )
    )) {
S
sushuang 已提交
632 633
        group.remove(el);
        el = null;
634 635
    }

S
sushuang 已提交
636
    // `elOption.type` is undefined when `renderItem` returns nothing.
S
sushuang 已提交
637
    if (simplyRemove) {
S
sushuang 已提交
638
        return;
639 640
    }

S
sushuang 已提交
641 642
    var isInit = !el;
    !el && (el = createEl(elOption));
S
sushuang 已提交
643
    updateEl(el, dataIndex, elOption, animatableModel, data, isInit, isRoot);
S
sushuang 已提交
644

645 646
    if (elOptionType === 'group') {
        mergeChildren(el, dataIndex, elOption, animatableModel, data);
647 648
    }

649
    // Always add whatever already added to ensure sequence.
S
sushuang 已提交
650 651 652 653 654
    group.add(el);

    return el;
}

655 656 657 658 659 660 661 662 663 664
// Usage:
// (1) By default, `elOption.$mergeChildren` is `'byIndex'`, which indicates that
//     the existing children will not be removed, and enables the feature that
//     update some of the props of some of the children simply by construct
//     the returned children of `renderItem` like:
//     `var children = group.children = []; children[3] = {opacity: 0.5};`
// (2) If `elOption.$mergeChildren` is `'byName'`, add/update/remove children
//     by child.name. But that might be lower performance.
// (3) If `elOption.$mergeChildren` is `false`, the existing children will be
//     replaced totally.
S
sushuang 已提交
665 666
// (4) If `!elOption.children`, following the "merge" principle, nothing will happen.
//
667 668 669 670 671 672 673 674 675 676 677 678 679
// For implementation simpleness, do not provide a direct way to remove sinlge
// child (otherwise the total indicies of the children array have to be modified).
// User can remove a single child by set its `ignore` as `true` or replace
// it by another element, where its `$merge` can be set as `true` if necessary.
function mergeChildren(el, dataIndex, elOption, animatableModel, data) {
    var newChildren = elOption.children;
    var newLen = newChildren ? newChildren.length : 0;
    var mergeChildren = elOption.$mergeChildren;
    // `diffChildrenByName` has been deprecated.
    var byName = mergeChildren === 'byName' || elOption.diffChildrenByName;
    var notMerge = mergeChildren === false;

    // For better performance on roam update, only enter if necessary.
S
tweak.  
sushuang 已提交
680
    if (!newLen && !byName && !notMerge) {
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
        return;
    }

    if (byName) {
        diffGroupChildren({
            oldChildren: el.children() || [],
            newChildren: newChildren || [],
            dataIndex: dataIndex,
            animatableModel: animatableModel,
            group: el,
            data: data
        });
        return;
    }

    notMerge && el.removeAll();

    // Mapping children of a group simply by index, which
    // might be better performance.
    var index = 0;
    for (; index < newLen; index++) {
        newChildren[index] && doCreateOrUpdate(
            el.childAt(index),
            dataIndex,
            newChildren[index],
            animatableModel,
            el,
            data
        );
    }
    if (__DEV__) {
        zrUtil.assert(
            !notMerge || el.childCount() === index,
            'MUST NOT contain empty item in children array when `group.$mergeChildren` is `false`.'
        );
    }
}

S
sushuang 已提交
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
function diffGroupChildren(context) {
    (new DataDiffer(
        context.oldChildren,
        context.newChildren,
        getKey,
        getKey,
        context
    ))
        .add(processAddUpdate)
        .update(processAddUpdate)
        .remove(processRemove)
        .execute();
}

function getKey(item, idx) {
    var name = item && item.name;
    return name != null ? name : GROUP_DIFF_PREFIX + idx;
}

function processAddUpdate(newIndex, oldIndex) {
    var context = this.context;
    var childOption = newIndex != null ? context.newChildren[newIndex] : null;
    var child = oldIndex != null ? context.oldChildren[oldIndex] : null;

    doCreateOrUpdate(
        child,
        context.dataIndex,
        childOption,
        context.animatableModel,
        context.group,
        context.data
    );
}

753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
// `graphic#applyDefaultTextStyle` will cache
// textFill, textStroke, textStrokeWidth.
// We have to do this trick.
function applyExtraBefore(extra, model) {
    var dummyModel = new Model({}, model);
    zrUtil.each(CACHED_LABEL_STYLE_PROPERTIES, function (stylePropName, modelPropName) {
        if (extra.hasOwnProperty(stylePropName)) {
            dummyModel.option[modelPropName] = extra[stylePropName];
        }
    });
    return dummyModel;
}

function applyExtraAfter(itemStyle, extra) {
    for (var key in extra) {
        if (extra.hasOwnProperty(key)
            || !CACHED_LABEL_STYLE_PROPERTIES.hasOwnProperty(key)
        ) {
            itemStyle[key] = extra[key];
        }
    }
}

S
sushuang 已提交
776 777 778 779 780
function processRemove(oldIndex) {
    var context = this.context;
    var child = context.oldChildren[oldIndex];
    child && context.group.remove(child);
}
S
sushuang 已提交
781 782 783 784 785 786 787 788 789 790 791 792 793

function getPathData(shape) {
    // "d" follows the SVG convention.
    return shape && (shape.pathData || shape.d);
}

function hasOwnPathData(shape) {
    return shape && (shape.hasOwnProperty('pathData') || shape.hasOwnProperty('d'));
}

function hasOwn(host, prop) {
    return host && host.hasOwnProperty(prop);
}