custom.ts 70.6 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';
21
import {
22
    hasOwn, assert, isString, retrieve2, retrieve3, defaults, each, keys, isArrayLike, bind
23
} from 'zrender/src/core/util';
S
sushuang 已提交
24
import * as graphicUtil from '../util/graphic';
25
import { setDefaultStateProxy, enableHoverEmphasis } from '../util/states';
26
import * as labelStyleHelper from '../label/labelStyle';
27
import {getDefaultLabel} from './helper/labelHelper';
S
sushuang 已提交
28
import createListFromArray from './helper/createListFromArray';
29
import {getLayoutOnAxis} from '../layout/barGrid';
S
sushuang 已提交
30
import DataDiffer from '../data/DataDiffer';
31
import SeriesModel from '../model/Series';
32
import Model from '../model/Model';
33
import ChartView from '../view/Chart';
34
import {createClipPath} from './helper/createClipPathFromCoordSys';
1
100pah 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
import {
    EventQueryItem, ECEvent, SeriesOption, SeriesOnCartesianOptionMixin,
    SeriesOnPolarOptionMixin, SeriesOnSingleOptionMixin, SeriesOnGeoOptionMixin,
    SeriesOnCalendarOptionMixin, ItemStyleOption, SeriesEncodeOptionMixin,
    SeriesTooltipOption,
    DimensionLoose,
    ParsedValue,
    Dictionary,
    CallbackDataParams,
    Payload,
    StageHandlerProgressParams,
    LabelOption,
    ViewRootGroup,
    OptionDataValue,
    ZRStyleProps,
    DisplayState,
    ECElement,
52 53
    DisplayStateNonNormal,
    BlurScope
1
100pah 已提交
54 55
} from '../util/types';
import Element, { ElementProps, ElementTextConfig } from 'zrender/src/Element';
S
sushuang 已提交
56 57 58 59 60
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';
1
100pah 已提交
61 62 63
import ComponentModel from '../model/Component';
import List, { DefaultDataVisual } from '../data/List';
import GlobalModel from '../model/Global';
64
import { makeInner, normalizeToArray } from '../util/model';
1
100pah 已提交
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
import ExtensionAPI from '../ExtensionAPI';
import Displayable from 'zrender/src/graphic/Displayable';
import Axis2D from '../coord/cartesian/Axis2D';
import { RectLike } from 'zrender/src/core/BoundingRect';
import { PathProps } from 'zrender/src/graphic/Path';
import { ImageStyleProps } from 'zrender/src/graphic/Image';
import { CoordinateSystem } from '../coord/CoordinateSystem';
import { TextStyleProps } from 'zrender/src/graphic/Text';
import {
    convertToEC4StyleForCustomSerise,
    isEC4CompatibleStyle,
    convertFromEC4CompatibleStyle,
    LegacyStyleProps,
    warnDeprecated
} from '../util/styleCompat';
import Transformable from 'zrender/src/core/Transformable';
import { ItemStyleProps } from '../model/mixin/itemStyle';
82
import { cloneValue } from 'zrender/src/animation/Animator';
1
100pah 已提交
83 84 85 86 87 88 89


const inner = makeInner<{
    info: CustomExtraElementInfo;
    customPathData: string;
    customGraphicType: string;
    customImagePath: CustomImageOption['style']['image'];
90
    // customText: string;
1
100pah 已提交
91
    txConZ2Set: number;
92 93
    leaveToProps: ElementProps;
    userDuring: CustomBaseElementOption['during'];
1
100pah 已提交
94 95 96
}, Element>();

type CustomExtraElementInfo = Dictionary<unknown>;
97 98 99 100 101 102 103 104 105 106
const TRANSFORM_PROPS = {
    x: 1,
    y: 1,
    scaleX: 1,
    scaleY: 1,
    originX: 1,
    originY: 1,
    rotation: 1
} as const;
type TransformProps = keyof typeof TRANSFORM_PROPS;
107
const transformPropNamesStr = keys(TRANSFORM_PROPS).join(', ');
108 109 110 111 112

type TransitionAnyProps = string | string[];
type TransitionTransformProps = TransformProps | TransformProps[];
// Do not declare "Dictionary" in TransitionAnyOption to restrict the type check.
type TransitionAnyOption = {
113 114 115
    transition?: TransitionAnyProps;
    enterFrom?: Dictionary<unknown>;
    leaveTo?: Dictionary<unknown>;
116 117
};
type TransitionTransformOption = {
118 119 120
    transition?: TransitionTransformProps;
    enterFrom?: Dictionary<unknown>;
    leaveTo?: Dictionary<unknown>;
121
};
1
100pah 已提交
122 123 124

interface CustomBaseElementOption extends Partial<Pick<
    Element, TransformProps | 'silent' | 'ignore' | 'textConfig'
125
>>, TransitionTransformOption {
1
100pah 已提交
126 127 128 129 130 131 132 133
    // element type, mandatory.
    type: string;
    id?: string;
    // For animation diff.
    name?: string;
    info?: CustomExtraElementInfo;
    // `false` means remove the textContent.
    textContent?: CustomTextOption | false;
134 135
    // `false` means remove the clipPath
    clipPath?: CustomZRPathOption | false;
136 137
    // `extra` can be set in any el option for custom prop for annimation duration.
    extra?: TransitionAnyOption;
138
    // updateDuringAnimation
139
    during?(params: typeof customDuringAPI): void;
140

141
    focus?: 'none' | 'self' | 'series' | ArrayLike<number>
142
    blurScope?: BlurScope
1
100pah 已提交
143 144 145 146
};
interface CustomDisplayableOption extends CustomBaseElementOption, Partial<Pick<
    Displayable, 'zlevel' | 'z' | 'z2' | 'invisible'
>> {
147
    style?: ZRStyleProps & TransitionAnyOption;
1
100pah 已提交
148 149 150
    // `false` means remove emphasis trigger.
    styleEmphasis?: ZRStyleProps | false;
    emphasis?: CustomDisplayableOptionOnState;
151 152
    blur?: CustomDisplayableOptionOnState;
    select?: CustomDisplayableOptionOnState;
1
100pah 已提交
153 154 155 156 157
}
interface CustomDisplayableOptionOnState extends Partial<Pick<
    Displayable, TransformProps | 'textConfig' | 'z2'
>> {
    // `false` means remove emphasis trigger.
158
    style?: (ZRStyleProps & TransitionAnyOption) | false;
1
100pah 已提交
159 160 161 162 163
}
interface CustomGroupOption extends CustomBaseElementOption {
    type: 'group';
    width?: number;
    height?: number;
164
    // @deprecated
1
100pah 已提交
165
    diffChildrenByName?: boolean;
166 167
    // Can only set focus, blur on the root element.
    children: Omit<CustomElementOption, 'focus' | 'blurScope'>[];
1
100pah 已提交
168 169
    $mergeChildren: false | 'byName' | 'byIndex';
}
170 171
interface CustomZRPathOption extends CustomDisplayableOption {
    shape?: PathProps['shape'] & TransitionAnyOption;
1
100pah 已提交
172 173 174 175 176 177 178 179 180 181 182 183 184
}
interface CustomSVGPathOption extends CustomDisplayableOption {
    type: 'path';
    shape?: {
        // SVG Path, like 'M0,0 L0,-20 L70,-1 L70,0 Z'
        pathData?: string;
        // "d" is the alias of `pathData` follows the SVG convention.
        d?: string;
        layout?: 'center' | 'cover';
        x?: number;
        y?: number;
        width?: number;
        height?: number;
185
    } & TransitionAnyOption;
1
100pah 已提交
186 187 188
}
interface CustomImageOption extends CustomDisplayableOption {
    type: 'image';
189
    style?: ImageStyleProps & TransitionAnyOption;
1
100pah 已提交
190
    emphasis?: CustomImageOptionOnState;
191 192
    blur?: CustomImageOptionOnState;
    select?: CustomImageOptionOnState;
1
100pah 已提交
193 194
}
interface CustomImageOptionOnState extends CustomDisplayableOptionOnState {
195
    style?: ImageStyleProps & TransitionAnyOption;
1
100pah 已提交
196 197 198 199 200 201 202 203 204 205 206 207
}
interface CustomTextOption extends CustomDisplayableOption {
    type: 'text';
}
type CustomElementOption = CustomZRPathOption | CustomSVGPathOption | CustomImageOption | CustomTextOption;
type CustomElementOptionOnState = CustomDisplayableOptionOnState | CustomImageOptionOnState;


interface CustomSeriesRenderItemAPI extends
        CustomSeriesRenderItemCoordinateSystemAPI,
        Pick<ExtensionAPI, 'getWidth' | 'getHeight' | 'getZr' | 'getDevicePixelRatio'> {
    value(dim: DimensionLoose, dataIndexInside?: number): ParsedValue;
208 209
    style(userProps?: ZRStyleProps, dataIndexInside?: number): ZRStyleProps;
    styleEmphasis(userProps?: ZRStyleProps, dataIndexInside?: number): ZRStyleProps;
1
100pah 已提交
210 211 212
    visual(visualType: string, dataIndexInside?: number): ReturnType<List['getItemVisual']>;
    barLayout(opt: Omit<Parameters<typeof getLayoutOnAxis>[0], 'axis'>): ReturnType<typeof getLayoutOnAxis>;
    currentSeriesIndices(): ReturnType<GlobalModel['getCurrentSeriesIndices']>;
213
    font(opt: Parameters<typeof labelStyleHelper.getFont>[0]): ReturnType<typeof labelStyleHelper.getFont>;
1
100pah 已提交
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
}
interface CustomSeriesRenderItemParamsCoordSys {
    type: string;
    // And extra params for each coordinate systems.
}
interface CustomSeriesRenderItemCoordinateSystemAPI {
    coord(
        data: OptionDataValue | OptionDataValue[],
        clamp?: boolean
    ): number[];
    size?(
        dataSize: OptionDataValue | OptionDataValue[],
        dataItem: OptionDataValue | OptionDataValue[]
    ): number | number[];
}
interface CustomSeriesRenderItemParams {
1
100pah 已提交
230
    context: Dictionary<unknown>;
1
100pah 已提交
231 232 233 234 235
    seriesId: string;
    seriesName: string;
    seriesIndex: number;
    coordSys: CustomSeriesRenderItemParamsCoordSys;
    dataInsideLength: number;
1
100pah 已提交
236
    encode: ReturnType<typeof wrapEncodeDef>;
1
100pah 已提交
237 238 239 240 241 242
}
type CustomSeriesRenderItem = (
    params: CustomSeriesRenderItemParams,
    api: CustomSeriesRenderItemAPI
) => CustomElementOption;

243 244 245 246
interface CustomSeriesStateOption {
    itemStyle?: ItemStyleOption;
    label?: LabelOption;
}
1
100pah 已提交
247 248

interface CustomSeriesOption extends
249
    SeriesOption<never>,    // don't support StateOption in custom series.
1
100pah 已提交
250 251 252 253 254 255 256 257 258 259 260
    SeriesEncodeOptionMixin,
    SeriesOnCartesianOptionMixin,
    SeriesOnPolarOptionMixin,
    SeriesOnSingleOptionMixin,
    SeriesOnGeoOptionMixin,
    SeriesOnCalendarOptionMixin {

    // If set as 'none', do not depends on coord sys.
    coordinateSystem?: string | 'none';

    renderItem?: CustomSeriesRenderItem;
S
sushuang 已提交
261

1
100pah 已提交
262 263
    // Only works on polar and cartesian2d coordinate system.
    clip?: boolean;
S
sushuang 已提交
264

1
100pah 已提交
265 266 267 268
    // FIXME needed?
    tooltip?: SeriesTooltipOption;
}

269 270 271
interface LegacyCustomSeriesOption extends SeriesOption<CustomSeriesStateOption>, CustomSeriesStateOption {}


272 273 274 275 276
interface LooseElementProps extends ElementProps {
    style?: ZRStyleProps;
    shape?: Dictionary<unknown>;
}

1
100pah 已提交
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
// Also compat with ec4, where
// `visual('color') visual('borderColor')` is supported.
const STYLE_VISUAL_TYPE = {
    color: 'fill',
    borderColor: 'stroke'
} as const;

const VISUAL_PROPS = {
    symbol: 1,
    symbolSize: 1,
    symbolKeepAspect: 1,
    legendSymbol: 1,
    visualMeta: 1,
    liftZ: 1
} as const;

const EMPHASIS = 'emphasis' as const;
const NORMAL = 'normal' as const;
295 296 297
const BLUR = 'blur' as const;
const SELECT = 'select' as const;
const STATES = [NORMAL, EMPHASIS, BLUR, SELECT] as const;
1
100pah 已提交
298 299
const PATH_ITEM_STYLE = {
    normal: ['itemStyle'],
300 301 302
    emphasis: [EMPHASIS, 'itemStyle'],
    blur: [BLUR, 'itemStyle'],
    select: [SELECT, 'itemStyle']
1
100pah 已提交
303 304 305
} as const;
const PATH_LABEL = {
    normal: ['label'],
306 307 308
    emphasis: [EMPHASIS, 'label'],
    blur: [BLUR, 'label'],
    select: [SELECT, 'label']
1
100pah 已提交
309
} as const;
S
sushuang 已提交
310
// Use prefix to avoid index to be the same as el.name,
1
100pah 已提交
311
// which will cause weird update animation.
312
const GROUP_DIFF_PREFIX = 'e\0\0';
S
sushuang 已提交
313

1
100pah 已提交
314 315 316 317 318 319 320 321 322 323
type AttachedTxInfo = {
    isLegacy: boolean;
    normal: {
        cfg: ElementTextConfig;
        conOpt: CustomElementOption | false;
    };
    emphasis: {
        cfg: ElementTextConfig;
        conOpt: CustomElementOptionOnState;
    };
324 325 326 327 328 329 330 331
    blur: {
        cfg: ElementTextConfig;
        conOpt: CustomElementOptionOnState;
    };
    select: {
        cfg: ElementTextConfig;
        conOpt: CustomElementOptionOnState;
    };
1
100pah 已提交
332 333 334
};
const attachedTxInfoTmp = {
    normal: {},
335 336 337
    emphasis: {},
    blur: {},
    select: {}
1
100pah 已提交
338 339
} as AttachedTxInfo;

340 341 342 343 344 345 346
const LEGACY_TRANSFORM_PROPS = {
    position: ['x', 'y'],
    scale: ['scaleX', 'scaleY'],
    origin: ['originX', 'originY']
} as const;
type LegacyTransformProp = keyof typeof LEGACY_TRANSFORM_PROPS;

1
100pah 已提交
347 348 349 350
export type PrepareCustomInfo = (coordSys: CoordinateSystem) => {
    coordSys: CustomSeriesRenderItemParamsCoordSys;
    api: CustomSeriesRenderItemCoordinateSystemAPI
};
351

S
sushuang 已提交
352 353 354 355 356 357 358 359 360 361 362
/**
 * 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.
 *     }}
 */
1
100pah 已提交
363
const prepareCustoms: Dictionary<PrepareCustomInfo> = {
S
sushuang 已提交
364 365 366 367 368 369 370
    cartesian2d: prepareCartesian2d,
    geo: prepareGeo,
    singleAxis: prepareSingleAxis,
    polar: preparePolar,
    calendar: prepareCalendar
};

1
100pah 已提交
371
class CustomSeriesModel extends SeriesModel<CustomSeriesOption> {
372

1
100pah 已提交
373 374
    static type = 'series.custom';
    readonly type = CustomSeriesModel.type;
S
sushuang 已提交
375

1
100pah 已提交
376
    static dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar'];
S
sushuang 已提交
377

378
    // preventAutoZ = true;
S
sushuang 已提交
379

1
100pah 已提交
380 381
    currentZLevel: number;
    currentZ: number;
S
sushuang 已提交
382

1
100pah 已提交
383
    static defaultOption: CustomSeriesOption = {
S
sushuang 已提交
384 385 386
        coordinateSystem: 'cartesian2d', // Can be set as 'none'
        zlevel: 0,
        z: 2,
387 388
        legendHoverLink: true,

389 390 391 392
        // 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
        clip: false
S
sushuang 已提交
393 394 395 396 397 398 399 400 401 402

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

        // Polar coordinate system
        // polarIndex: 0,

        // Geo coordinate system
        // geoIndex: 0,
1
100pah 已提交
403
    };
S
sushuang 已提交
404

1
100pah 已提交
405 406 407 408 409 410
    optionUpdated() {
        this.currentZLevel = this.get('zlevel', true);
        this.currentZ = this.get('z', true);
    }

    getInitialData(option: CustomSeriesOption, ecModel: GlobalModel): List {
411
        return createListFromArray(this.getSource(), this);
1
100pah 已提交
412
    }
413

414
    getDataParams(dataIndex: number, dataType?: string, el?: Element): CallbackDataParams & {
1
100pah 已提交
415 416
        info: CustomExtraElementInfo
    } {
417
        const params = super.getDataParams(dataIndex, dataType) as ReturnType<CustomSeriesModel['getDataParams']>;
1
100pah 已提交
418
        el && (params.info = inner(el).info);
419
        return params;
S
sushuang 已提交
420
    }
1
100pah 已提交
421
}
P
pah100 已提交
422

1
100pah 已提交
423
ComponentModel.registerClass(CustomSeriesModel);
P
pah100 已提交
424 425 426



1
100pah 已提交
427
class CustomSeriesView extends ChartView {
P
pah100 已提交
428

1
100pah 已提交
429 430 431 432 433 434 435 436 437 438 439 440
    static type = 'custom';
    readonly type = CustomSeriesView.type;

    private _data: List;


    render(
        customSeries: CustomSeriesModel,
        ecModel: GlobalModel,
        api: ExtensionAPI,
        payload: Payload
    ): void {
441 442 443 444
        const oldData = this._data;
        const data = customSeries.getData();
        const group = this.group;
        const renderItem = makeRenderItem(customSeries, data, ecModel, api);
S
sushuang 已提交
445

446 447 448 449 450
        // 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 已提交
451 452
        data.diff(oldData)
            .add(function (newIdx) {
453
                createOrUpdateItem(
454
                    null, newIdx, renderItem(newIdx, payload), customSeries, group, data
S
sushuang 已提交
455 456 457
                );
            })
            .update(function (newIdx, oldIdx) {
458
                createOrUpdateItem(
459 460
                    oldData.getItemGraphicEl(oldIdx),
                    newIdx, renderItem(newIdx, payload), customSeries, group, data
461
                );
S
sushuang 已提交
462 463
            })
            .remove(function (oldIdx) {
464
                doRemoveEl(oldData.getItemGraphicEl(oldIdx), customSeries, group);
S
sushuang 已提交
465 466
            })
            .execute();
P
pah100 已提交
467

468
        // Do clipping
469
        const clipPath = customSeries.get('clip', true)
470 471 472 473 474 475 476 477 478
            ? createClipPath(customSeries.coordinateSystem, false, customSeries)
            : null;
        if (clipPath) {
            group.setClipPath(clipPath);
        }
        else {
            group.removeClipPath();
        }

S
sushuang 已提交
479
        this._data = data;
1
100pah 已提交
480
    }
P
pah100 已提交
481

1
100pah 已提交
482 483 484 485 486
    incrementalPrepareRender(
        customSeries: CustomSeriesModel,
        ecModel: GlobalModel,
        api: ExtensionAPI
    ): void {
P
pissang 已提交
487 488
        this.group.removeAll();
        this._data = null;
1
100pah 已提交
489
    }
P
pissang 已提交
490

1
100pah 已提交
491 492 493 494 495 496 497
    incrementalRender(
        params: StageHandlerProgressParams,
        customSeries: CustomSeriesModel,
        ecModel: GlobalModel,
        api: ExtensionAPI,
        payload: Payload
    ): void {
498 499
        const data = customSeries.getData();
        const renderItem = makeRenderItem(customSeries, data, ecModel, api);
1
100pah 已提交
500
        function setIncrementalAndHoverLayer(el: Displayable) {
P
pissang 已提交
501 502 503 504 505
            if (!el.isGroup) {
                el.incremental = true;
                el.useHoverLayer = true;
            }
        }
506
        for (let idx = params.start; idx < params.end; idx++) {
507
            const el = createOrUpdateItem(null, idx, renderItem(idx, payload), customSeries, this.group, data);
P
pissang 已提交
508 509
            el.traverse(setIncrementalAndHoverLayer);
        }
1
100pah 已提交
510
    }
511

1
100pah 已提交
512
    filterForExposedEvent(
513 514
        eventType: string, query: EventQueryItem, targetEl: Element, packedEvent: ECEvent
    ): boolean {
515
        const elementName = query.element;
516
        if (elementName == null || targetEl.name === elementName) {
517 518 519 520 521 522
            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) {
523
            if (targetEl.name === elementName) {
524 525 526 527 528 529
                return true;
            }
        }

        return false;
    }
1
100pah 已提交
530
}
P
pah100 已提交
531

1
100pah 已提交
532
ChartView.registerClass(CustomSeriesView);
P
pah100 已提交
533 534


1
100pah 已提交
535
function createEl(elOption: CustomElementOption): Element {
536
    const graphicType = elOption.type;
537
    let el;
S
sushuang 已提交
538

539 540
    // Those graphic elements are not shapes. They should not be
    // overwritten by users, so do them first.
S
sushuang 已提交
541
    if (graphicType === 'path') {
1
100pah 已提交
542
        const shape = (elOption as CustomSVGPathOption).shape;
S
sushuang 已提交
543
        // Using pathRect brings convenience to users sacle svg path.
544
        const pathRect = (shape.width != null && shape.height != null)
S
sushuang 已提交
545
            ? {
S
sushuang 已提交
546 547
                x: shape.x || 0,
                y: shape.y || 0,
S
sushuang 已提交
548 549
                width: shape.width,
                height: shape.height
1
100pah 已提交
550
            } as RectLike
S
sushuang 已提交
551
            : null;
552
        const pathData = getPathData(shape);
S
sushuang 已提交
553 554
        // Path is also used for icon, so layout 'center' by default.
        el = graphicUtil.makePath(pathData, null, pathRect, shape.layout || 'center');
1
100pah 已提交
555
        inner(el).customPathData = pathData;
S
sushuang 已提交
556 557
    }
    else if (graphicType === 'image') {
558
        el = new graphicUtil.Image({});
1
100pah 已提交
559
        inner(el).customImagePath = (elOption as CustomImageOption).style.image;
S
sushuang 已提交
560 561
    }
    else if (graphicType === 'text') {
562
        el = new graphicUtil.Text({});
563
        // inner(el).customText = (elOption.style as TextStyleProps).text;
S
sushuang 已提交
564
    }
565 566 567 568 569 570
    else if (graphicType === 'group') {
        el = new graphicUtil.Group();
    }
    else if (graphicType === 'compoundPath') {
        throw new Error('"compoundPath" is not supported yet.');
    }
S
sushuang 已提交
571
    else {
572
        const Clz = graphicUtil.getShapeClass(graphicType);
P
pah100 已提交
573

S
sushuang 已提交
574
        if (__DEV__) {
575
            assert(Clz, 'graphic type "' + graphicType + '" can not be found.');
P
pah100 已提交
576 577
        }

S
sushuang 已提交
578 579
        el = new Clz();
    }
P
pah100 已提交
580

1
100pah 已提交
581
    inner(el).customGraphicType = graphicType;
S
sushuang 已提交
582
    el.name = elOption.name;
P
pah100 已提交
583

1
100pah 已提交
584 585 586 587
    // Compat ec4: the default z2 lift is 1. If changing the number,
    // some cases probably be broken: hierarchy layout along z, like circle packing,
    // where emphasis only intending to modify color/border rather than lift z2.
    (el as ECElement).z2EmphasisLift = 1;
588
    (el as ECElement).z2SelectLift = 1;
1
100pah 已提交
589

S
sushuang 已提交
590 591
    return el;
}
P
pah100 已提交
592

1
100pah 已提交
593
/**
594 595
 * ----------------------------------------------------------
 * [STRATEGY_MERGE] Merge properties or erase all properties:
1
100pah 已提交
596
 *
597
 * Based on the fact that the existing zr element probably be reused, we now consider whether
1
100pah 已提交
598
 * merge or erase all properties to the exsiting elements.
599 600 601
 * That is, if a certain props is not specified in the lastest return of `renderItem`:
 * + "Merge" means that do not modify the value on the existing element.
 * + "Erase all" means that use a default value to the existing element.
1
100pah 已提交
602 603
 *
 * "Merge" might bring some unexpected state retaining for users and "erase all" seams to be
604 605 606 607
 * more safe. "erase all" force users to specify all of the props each time, which is recommanded
 * in most cases.
 * But "erase all" theoretically disables the chance of performance optimization (e.g., just
 * generete shape and style at the first time rather than always do that).
1
100pah 已提交
608 609 610 611 612
 * So we still use "merge" rather than "erase all". If users need "erase all", they can
 * simple always set all of the props each time.
 * Some "object-like" config like `textConfig`, `textContent`, `style` which are not needed for
 * every elment, so we replace them only when user specify them. And the that is a total replace.
 *
613 614 615 616 617 618 619
 * TODO: there is no hint of 'isFirst' to users. So the performance enhancement can not be
 * performed yet. Consider the case:
 * (1) setOption to "mergeChildren" with a smaller children count
 * (2) Use dataZoom to make an item disappear.
 * (3) User dataZoom to make the item display again. At that time, renderItem need to return the
 * full option rather than partial option to recreate the element.
 *
620 621
 * ----------------------------------------------
 * [STRATEGY_NULL] `hasOwnProperty` or `== null`:
1
100pah 已提交
622 623 624 625 626 627 628
 *
 * Ditinguishing "own property" probably bring little trouble to user when make el options.
 * So we  trade a {xx: null} or {xx: undefined} as "not specified" if possible rather than
 * "set them to null/undefined". In most cases, props can not be cleared. Some typicall
 * clearable props like `style`/`textConfig`/`textContent` we enable `false` to means
 * "clear". In some othere special cases that the prop is able to set as null/undefined,
 * but not suitable to use `false`, `hasOwnProperty` is checked.
629 630 631 632
 *
 * ---------------------------------------------
 * [STRATEGY_TRANSITION] The rule of transition:
 * + For props on the root level of a element:
633
 *      If there is no `transition` specified, tansform props will be transitioned by default,
634 635
 *      which is the same as the previous setting in echarts4 and suitable for the scenario
 *      of dataZoom change.
636
 *      If `transition` specified, only the specified props will be transitioned.
637
 * + For props in `shape` and `style`:
638
 *      Only props specified in `transition` will be transitioned.
639 640 641
 * + Break:
 *      Since ec5, do not make transition to shape by default, because it might result in
 *      performance issue (especially `points` of polygon) and do not necessary in most cases.
1
100pah 已提交
642 643 644 645 646
 */
function updateElNormal(
    el: Element,
    dataIndex: number,
    elOption: CustomElementOption,
647
    styleOpt: CustomElementOption['style'],
1
100pah 已提交
648 649 650 651 652
    attachedTxInfo: AttachedTxInfo,
    seriesModel: CustomSeriesModel,
    isInit: boolean,
    isTextContent: boolean
): void {
653 654
    const transFromProps = {} as ElementProps;
    const allProps = {} as ElementProps;
1
100pah 已提交
655 656
    const elDisplayable = el.isGroup ? null : el as Displayable;

657 658
    prepareShapeOrExtraUpdate('shape', el, elOption, allProps, transFromProps, isInit);
    prepareShapeOrExtraUpdate('extra', el, elOption, allProps, transFromProps, isInit);
659
    prepareTransformUpdate(el, elOption, allProps, transFromProps, isInit);
1
100pah 已提交
660 661 662 663 664 665

    const txCfgOpt = attachedTxInfo && attachedTxInfo.normal.cfg;
    if (txCfgOpt) {
        // PENDING: whether use user object directly rather than clone?
        // TODO:5.0 textConfig transition animation?
        el.setTextConfig(txCfgOpt);
P
pah100 已提交
666 667
    }

1
100pah 已提交
668 669 670
    if (el.type === 'text' && styleOpt) {
        const textOptionStyle = styleOpt as TextStyleProps;
        // Compatible with ec4: if `textFill` or `textStroke` exists use them.
671
        hasOwn(textOptionStyle, 'textFill') && (
1
100pah 已提交
672
            textOptionStyle.fill = (textOptionStyle as any).textFill
S
sushuang 已提交
673
        );
674
        hasOwn(textOptionStyle, 'textStroke') && (
1
100pah 已提交
675
            textOptionStyle.stroke = (textOptionStyle as any).textStroke
S
sushuang 已提交
676 677
        );
    }
P
pah100 已提交
678

679 680
    prepareStyleUpdate(el, styleOpt, transFromProps, isInit);

1
100pah 已提交
681 682 683 684
    if (elDisplayable) {
        // PENDING: here the input style object is used directly.
        // Good for performance but bad for compatibility control.
        styleOpt && elDisplayable.useStyle(styleOpt);
P
pah100 已提交
685

686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
        // When style object changed, how to trade the existing animation?
        // It is probably conplicated and not needed to cover all the cases.
        // But still need consider the case:
        // (1) When using init animation on `style.opacity`, and before the animation
        //     ended users triggers an update by mousewhell. At that time the init
        //     animation should better be continued rather than terminated.
        //     So after `useStyle` called, we should change the animation target manually
        //     to continue the effect of the init animation.
        // (2) PENDING: If the previous animation targeted at a `val1`, and currently we need
        //     to update the value to `val2` and no animation declared, should be terminate
        //     the previous animation or just modify the target of the animation?
        //     Therotically That will happen not only on `style` but also on `shape` and
        //     `transfrom` props. But we haven't handle this case at present yet.
        // (3) PENDING: Is it proper to visit `animators` and `targetName`?
        const animators = elDisplayable.animators;
        for (let i = 0; i < animators.length; i++) {
            const animator = animators[i];
            // targetName is the "topKey".
            if (animator.targetName === 'style') {
                animator.changeTarget(elDisplayable.style);
            }
P
pah100 已提交
707
        }
1
100pah 已提交
708

709
        hasOwn(elOption, 'invisible') && (elDisplayable.invisible = elOption.invisible);
S
sushuang 已提交
710
    }
P
pah100 已提交
711

712 713 714 715 716 717 718 719 720 721
    // Do not use `el.updateDuringAnimation` here becuase `el.updateDuringAnimation` will
    // be called mutiple time in each animation frame. For example, if both "transform" props
    // and shape props and style props changed, it will generate three animator and called
    // one-by-one in each animation frame.
    // We use the during in `animateTo/From` params.
    const userDuring = elOption.during;
    // For simplicity, if during not specified, the previous during will not work any more.
    inner(el).userDuring = userDuring;
    const cfgDuringCall = userDuring ? bind(duringCall, { el: el, userDuring: userDuring }) : null;

722
    el.attr(allProps);
723 724 725 726 727
    const cfg = {
        dataIndex: dataIndex,
        isFrom: true,
        during: cfgDuringCall
    };
728
    isInit
729 730
        ? graphicUtil.initProps(el, transFromProps, seriesModel, cfg)
        : graphicUtil.updateProps(el, transFromProps, seriesModel, cfg);
P
pah100 已提交
731

732
    // Merge by default.
733 734
    hasOwn(elOption, 'silent') && (el.silent = elOption.silent);
    hasOwn(elOption, 'ignore') && (el.ignore = elOption.ignore);
1
100pah 已提交
735 736 737 738 739

    if (!isTextContent) {
        // `elOption.info` enables user to mount some info on
        // elements and use them in event handlers.
        // Update them only when user specified, otherwise, remain.
740
        hasOwn(elOption, 'info') && (inner(el).info = elOption.info);
S
sushuang 已提交
741
    }
1
100pah 已提交
742

743
    styleOpt ? el.dirty() : el.markRedraw();
1
100pah 已提交
744 745
}

746

747
// See [STRATEGY_TRANSITION]
748 749
function prepareShapeOrExtraUpdate(
    mainAttr: 'shape' | 'extra',
750 751 752 753 754 755 756
    el: Element,
    elOption: CustomElementOption,
    allProps: LooseElementProps,
    transFromProps: LooseElementProps,
    isInit: boolean
): void {

757 758
    const attrOpt: Dictionary<unknown> & TransitionAnyOption = (elOption as any)[mainAttr];
    if (!attrOpt) {
759 760 761
        return;
    }

762 763
    const elPropsInAttr = (el as LooseElementProps)[mainAttr];
    let transFromPropsInAttr: Dictionary<unknown>;
764

765
    const enterFrom = attrOpt.enterFrom;
766
    if (isInit && enterFrom) {
767
        !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
768 769
        const enterFromKeys = keys(enterFrom);
        for (let i = 0; i < enterFromKeys.length; i++) {
770 771
            // `enterFrom` props are not necessarily also declared in `shape`/`style`/...,
            // for example, `opacity` can only declared in `enterFrom` but not in `style`.
772 773
            const key = enterFromKeys[i];
            // Do not clone, animator will perform that clone.
774
            transFromPropsInAttr[key] = enterFrom[key];
775 776 777
        }
    }

778 779 780
    if (!isInit && elPropsInAttr && attrOpt.transition) {
        !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
        const transitionKeys = normalizeToArray(attrOpt.transition);
781 782
        for (let i = 0; i < transitionKeys.length; i++) {
            const key = transitionKeys[i];
783
            const elVal = elPropsInAttr[key];
784
            if (__DEV__) {
785
                checkTansitionRefer(key, (attrOpt as any)[key], elVal);
786 787
            }
            // Do not clone, see `checkTansitionRefer`.
788
            transFromPropsInAttr[key] = elVal;
789 790 791
        }
    }

792 793 794 795
    const allPropsInAttr = allProps[mainAttr] = {} as Dictionary<unknown>;
    const keysInAttr = keys(attrOpt);
    for (let i = 0; i < keysInAttr.length; i++) {
        const key = keysInAttr[i];
796 797
        // To avoid share one object with different element, and
        // to avoid user modify the object inexpectedly, have to clone.
798
        allPropsInAttr[key] = cloneValue((attrOpt as any)[key]);
799 800
    }

801
    const leaveTo = attrOpt.leaveTo;
802 803
    if (leaveTo) {
        const leaveToProps = getOrCreateLeaveToPropsFromEl(el);
804
        const leaveToPropsInAttr: Dictionary<unknown> = leaveToProps[mainAttr] || (leaveToProps[mainAttr] = {});
805 806 807
        const leaveToKeys = keys(leaveTo);
        for (let i = 0; i < leaveToKeys.length; i++) {
            const key = leaveToKeys[i];
808
            leaveToPropsInAttr[key] = leaveTo[key];
809 810 811 812 813 814 815 816 817 818 819 820
        }
    }
}

// See [STRATEGY_TRANSITION].
function prepareTransformUpdate(
    el: Element,
    elOption: CustomElementOption,
    allProps: ElementProps,
    transFromProps: ElementProps,
    isInit: boolean
): void {
821
    const enterFrom = elOption.enterFrom;
822 823 824 825 826
    if (isInit && enterFrom) {
        const enterFromKeys = keys(enterFrom);
        for (let i = 0; i < enterFromKeys.length; i++) {
            const key = enterFromKeys[i] as TransformProps;
            if (__DEV__) {
827
                checkTransformPropRefer(key, 'el.enterFrom');
828 829 830 831 832 833 834
            }
            // Do not clone, animator will perform that clone.
            transFromProps[key] = enterFrom[key] as number;
        }
    }

    if (!isInit) {
835 836
        if (elOption.transition) {
            const transitionKeys = normalizeToArray(elOption.transition);
837 838 839 840
            for (let i = 0; i < transitionKeys.length; i++) {
                const key = transitionKeys[i];
                const elVal = el[key];
                if (__DEV__) {
841
                    checkTransformPropRefer(key, 'el.transition');
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
                    checkTansitionRefer(key, elOption[key], elVal);
                }
                // Do not clone, see `checkTansitionRefer`.
                transFromProps[key] = elVal;
            }
        }
        // This default transition see [STRATEGY_TRANSITION]
        else {
            setLagecyProp(elOption, transFromProps, 'position', el);
            setTransProp(elOption, transFromProps, 'x', el);
            setTransProp(elOption, transFromProps, 'y', el);
        }
    }

    setLagecyProp(elOption, allProps, 'position');
    setLagecyProp(elOption, allProps, 'scale');
    setLagecyProp(elOption, allProps, 'origin');
    setTransProp(elOption, allProps, 'x');
    setTransProp(elOption, allProps, 'y');
    setTransProp(elOption, allProps, 'scaleX');
    setTransProp(elOption, allProps, 'scaleY');
    setTransProp(elOption, allProps, 'originX');
    setTransProp(elOption, allProps, 'originY');
    setTransProp(elOption, allProps, 'rotation');

867
    const leaveTo = elOption.leaveTo;
868 869 870 871 872 873
    if (leaveTo) {
        const leaveToProps = getOrCreateLeaveToPropsFromEl(el);
        const leaveToKeys = keys(leaveTo);
        for (let i = 0; i < leaveToKeys.length; i++) {
            const key = leaveToKeys[i] as TransformProps;
            if (__DEV__) {
874
                checkTransformPropRefer(key, 'el.leaveTo');
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
            }
            leaveToProps[key] = leaveTo[key] as number;
        }
    }
}

// See [STRATEGY_TRANSITION].
function prepareStyleUpdate(
    el: Element,
    styleOpt: CustomElementOption['style'],
    transFromProps: LooseElementProps,
    isInit: boolean
): void {
    if (!styleOpt) {
        return;
    }

    const elStyle = (el as LooseElementProps).style as LooseElementProps['style'];
    let transFromStyleProps: LooseElementProps['style'];

895
    const enterFrom = styleOpt.enterFrom;
896 897 898 899 900 901 902 903 904 905
    if (isInit && enterFrom) {
        const enterFromKeys = keys(enterFrom);
        !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
        for (let i = 0; i < enterFromKeys.length; i++) {
            const key = enterFromKeys[i];
            // Do not clone, animator will perform that clone.
            (transFromStyleProps as any)[key] = enterFrom[key];
        }
    }

906 907
    if (!isInit && elStyle && styleOpt.transition) {
        const transitionKeys = normalizeToArray(styleOpt.transition);
908 909 910 911 912 913 914 915 916 917 918 919
        !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
        for (let i = 0; i < transitionKeys.length; i++) {
            const key = transitionKeys[i];
            const elVal = (elStyle as any)[key];
            if (__DEV__) {
                checkTansitionRefer(key, (styleOpt as any)[key], elVal);
            }
            // Do not clone, see `checkTansitionRefer`.
            (transFromStyleProps as any)[key] = elVal;
        }
    }

920
    const leaveTo = styleOpt.leaveTo;
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
    if (leaveTo) {
        const leaveToKeys = keys(leaveTo);
        const leaveToProps = getOrCreateLeaveToPropsFromEl(el);
        const leaveToStyleProps = leaveToProps.style || (leaveToProps.style = {});
        for (let i = 0; i < leaveToKeys.length; i++) {
            const key = leaveToKeys[i];
            (leaveToStyleProps as any)[key] = leaveTo[key];
        }
    }
}

function checkTansitionRefer(propName: string, optVal: unknown, elVal: unknown): void {
    const isArrLike = isArrayLike(optVal);
    assert(
        isArrLike || (optVal != null && isFinite(optVal as number)),
        'Prop `' + propName + '` must refer to a finite number or ArrayLike for transition.'
    );
    // Try not to copy array for performance, but if user use the same object in different
    // call of `renderItem`, it will casue animation transition fail.
    assert(
        !isArrLike || optVal !== elVal,
        'Prop `' + propName + '` must use different Array object each time for transition.'
    );
}

function checkTransformPropRefer(key: string, usedIn: string): void {
    assert(
        hasOwn(TRANSFORM_PROPS, key),
        'Prop `' + key + '` is not a permitted in `' + usedIn + '`. '
            + 'Only `' + keys(TRANSFORM_PROPS).join('`, `') + '` are permitted.'
    );
}

function getOrCreateLeaveToPropsFromEl(el: Element): LooseElementProps {
    const innerEl = inner(el);
    return innerEl.leaveToProps || (innerEl.leaveToProps = {});
}

959 960 961 962 963 964 965 966
// Use it to avoid it be exposed to user.
const tmpDuringScope = {} as {
    el: Element;
    isShapeDirty: boolean;
    isStyleDirty: boolean;
};
const customDuringAPI = {
    // Usually other props do not need to be changed in animation during.
967
    setTransform(key: TransformProps, val: unknown) {
968 969 970
        if (__DEV__) {
            assert(hasOwn(TRANSFORM_PROPS, key), 'Only ' + transformPropNamesStr + ' available in `setTransform`.');
        }
971
        tmpDuringScope.el[key] = val as number;
972
        return this;
973
    },
974
    getTransform(key: TransformProps): unknown {
975 976 977
        if (__DEV__) {
            assert(hasOwn(TRANSFORM_PROPS, key), 'Only ' + transformPropNamesStr + ' available in `getTransform`.');
        }
978 979
        return tmpDuringScope.el[key];
    },
980
    setShape(key: string, val: unknown) {
981 982 983 984 985
        if (__DEV__) {
            assertNotReserved(key);
        }
        const shape = (tmpDuringScope.el as graphicUtil.Path).shape
            || ((tmpDuringScope.el as graphicUtil.Path).shape = {});
986 987
        shape[key] = val;
        tmpDuringScope.isShapeDirty = true;
988
        return this;
989 990
    },
    getShape(key: string): unknown {
991 992 993 994
        if (__DEV__) {
            assertNotReserved(key);
        }
        const shape = (tmpDuringScope.el as graphicUtil.Path).shape;
995 996 997 998
        if (shape) {
            return shape[key];
        }
    },
999
    setStyle(key: string, val: unknown) {
1000 1001 1002
        if (__DEV__) {
            assertNotReserved(key);
        }
1003 1004 1005 1006 1007
        const style = (tmpDuringScope.el as Displayable).style;
        if (style) {
            style[key] = val;
            tmpDuringScope.isStyleDirty = true;
        }
1008
        return this;
1009 1010
    },
    getStyle(key: string): unknown {
1011 1012 1013
        if (__DEV__) {
            assertNotReserved(key);
        }
1014 1015 1016 1017
        const style = (tmpDuringScope.el as Displayable).style;
        if (style) {
            return style[key];
        }
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
    },
    setExtra(key: string, val: unknown) {
        if (__DEV__) {
            assertNotReserved(key);
        }
        const extra = (tmpDuringScope.el as LooseElementProps).extra
            || ((tmpDuringScope.el as LooseElementProps).extra = {});
        extra[key] = val;
        return this;
    },
    getExtra(key: string): unknown {
        if (__DEV__) {
            assertNotReserved(key);
        }
        const extra = (tmpDuringScope.el as LooseElementProps).extra;
        if (extra) {
            return extra[key];
        }
1036 1037 1038
    }
};

1039 1040 1041 1042 1043 1044 1045 1046
function assertNotReserved(key: string) {
    if (__DEV__) {
        if (key === 'transition' || key === 'enterFrom' || key === 'leaveTo') {
            throw new Error('key must not be "' + key + '"');
        }
    }
}

1047 1048 1049 1050 1051 1052
function duringCall(
    this: {
        el: Element;
        userDuring: CustomBaseElementOption['during']
    }
): void {
1053 1054 1055 1056 1057
    // Do not provide "percent" until some requirements come.
    // Because consider thies case:
    // enterFrom: {x: 100, y: 30}, transition: 'x'.
    // And enter duration is different from update duration.
    // Thus it might be confused about the meaning of "percent" in during callback.
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
    const scope = this;
    const el = scope.el;
    if (!el) {
        return;
    }
    // If el is remove from zr by reason like legend, during still need to called,
    // becuase el will be added back to zr and the prop value should not be incorrect.

    const newstUserDuring = inner(el).userDuring;
    const scopeUserDuring = scope.userDuring;
    // Ensured a during is only called once in each animation frame.
    // If a during is called multiple times in one frame, maybe some users' calulation logic
    // might be wrong (not sure whether this usage exists).
    // The case of a during might be called twice can be: by default there is a animator for
    // 'x', 'y' when init. Before the init animation finished, call `setOption` to start
    // another animators for 'style'/'shape'/'extra'.
    if (newstUserDuring !== scopeUserDuring) {
        // release
        scope.el = scope.userDuring = null;
        return;
    }
1079

1080
    tmpDuringScope.el = el;
1081 1082 1083
    tmpDuringScope.isShapeDirty = false;
    tmpDuringScope.isStyleDirty = false;

1084 1085
    // Give no `this` to user in "during" calling.
    scopeUserDuring(customDuringAPI);
1086

1087 1088
    if (tmpDuringScope.isShapeDirty && (el as graphicUtil.Path).dirtyShape) {
        (el as graphicUtil.Path).dirtyShape();
1089
    }
1090 1091
    if (tmpDuringScope.isStyleDirty && (el as Displayable).dirtyStyle) {
        (el as Displayable).dirtyStyle();
1092 1093
    }
    // markRedraw() will be called by default in during.
1094
    // FIXME `this.markRedraw();` directly ?
1095 1096 1097

    // FIXME: if in future meet the case that some prop will be both modified in `during` and `state`,
    // consider the issue that the prop might be incorrect when return to "normal" state.
1098 1099
}

1
100pah 已提交
1100 1101 1102 1103
function updateElOnState(
    state: DisplayStateNonNormal,
    el: Element,
    elStateOpt: CustomElementOptionOnState,
1104
    styleOpt: CustomElementOptionOnState['style'],
1
100pah 已提交
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
    attachedTxInfo: AttachedTxInfo,
    isRoot: boolean,
    isTextContent: boolean
): void {
    const elDisplayable = el.isGroup ? null : el as Displayable;
    const txCfgOpt = attachedTxInfo && attachedTxInfo[state].cfg;

    // PENDING:5.0 support customize scale change and transition animation?

    if (elDisplayable) {
        // By default support auto lift color when hover whether `emphasis` specified.
        const stateObj = elDisplayable.ensureState(state);
        if (styleOpt === false) {
            const existingEmphasisState = elDisplayable.getState(state);
            if (existingEmphasisState) {
                existingEmphasisState.style = null;
            }
        }
        else {
            // style is needed to enable defaut emphasis.
1125
            stateObj.style = styleOpt || null;
1
100pah 已提交
1126 1127 1128 1129 1130 1131 1132 1133 1134
        }
        // If `elOption.styleEmphasis` or `elOption.emphasis.style` is `false`,
        // remove hover style.
        // If `elOption.textConfig` or `elOption.emphasis.textConfig` is null/undefined, it does not
        // make sense. So for simplicity, we do not ditinguish `hasOwnProperty` and null/undefined.
        if (txCfgOpt) {
            stateObj.textConfig = txCfgOpt;
        }

1135
        setDefaultStateProxy(elDisplayable);
S
sushuang 已提交
1136
    }
1
100pah 已提交
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
}

function updateZ(
    el: Element,
    elOption: CustomElementOption,
    seriesModel: CustomSeriesModel,
    attachedTxInfo: AttachedTxInfo
): void {
    // Group not support textContent and not support z yet.
    if (el.isGroup) {
        return;
    }

    const elDisplayable = el as Displayable;
    const currentZ = seriesModel.currentZ;
    const currentZLevel = seriesModel.currentZLevel;
    // Always erase.
    elDisplayable.z = currentZ;
    elDisplayable.zlevel = currentZLevel;
    // z2 must not be null/undefined, otherwise sort error may occur.
    const optZ2 = elOption.z2;
    optZ2 != null && (elDisplayable.z2 = optZ2 || 0);

1160 1161
    for (let i = 0; i < STATES.length; i++) {
        updateZForEachState(elDisplayable, elOption, STATES[i]);
1
100pah 已提交
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
    }
}

function updateZForEachState(
    elDisplayable: Displayable,
    elOption: CustomDisplayableOption,
    state: DisplayState
): void {
    const isNormal = state === NORMAL;
    const elStateOpt = isNormal ? elOption : retrieveStateOption(elOption, state as DisplayStateNonNormal);
    const optZ2 = elStateOpt ? elStateOpt.z2 : null;
    let stateObj;
    if (optZ2 != null) {
        // Do not `ensureState` until required.
        stateObj = isNormal ? elDisplayable : elDisplayable.ensureState(state);
        stateObj.z2 = optZ2 || 0;
    }
S
sushuang 已提交
1179
}
P
pah100 已提交
1180

1
100pah 已提交
1181 1182
function setLagecyProp(
    elOption: CustomElementOption,
1183 1184 1185
    targetProps: Partial<Pick<Transformable, TransformProps>>,
    legacyName: LegacyTransformProp,
    fromEl?: Element // If provided, retrieve from the element.
1
100pah 已提交
1186 1187
): void {
    const legacyArr = (elOption as any)[legacyName];
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
    const xyName = LEGACY_TRANSFORM_PROPS[legacyName];
    if (legacyArr) {
        if (fromEl) {
            targetProps[xyName[0]] = fromEl[xyName[0]];
            targetProps[xyName[1]] = fromEl[xyName[1]];
        }
        else {
            targetProps[xyName[0]] = legacyArr[0];
            targetProps[xyName[1]] = legacyArr[1];
        }
    }
1
100pah 已提交
1199
}
1200

1
100pah 已提交
1201 1202
function setTransProp(
    elOption: CustomElementOption,
1203 1204 1205
    targetProps: Partial<Pick<Transformable, TransformProps>>,
    name: TransformProps,
    fromEl?: Element // If provided, retrieve from the element.
1
100pah 已提交
1206
): void {
1207 1208
    if (elOption[name] != null) {
        targetProps[name] = fromEl ? fromEl[name] : elOption[name];
P
pah100 已提交
1209
    }
S
sushuang 已提交
1210 1211
}

1
100pah 已提交
1212 1213 1214 1215 1216 1217
function makeRenderItem(
    customSeries: CustomSeriesModel,
    data: List<CustomSeriesModel>,
    ecModel: GlobalModel,
    api: ExtensionAPI
) {
1218 1219
    const renderItem = customSeries.get('renderItem');
    const coordSys = customSeries.coordinateSystem;
1
100pah 已提交
1220
    let prepareResult = {} as ReturnType<PrepareCustomInfo>;
S
sushuang 已提交
1221 1222 1223

    if (coordSys) {
        if (__DEV__) {
1224 1225
            assert(renderItem, 'series.render is required.');
            assert(
S
sushuang 已提交
1226 1227 1228
                coordSys.prepareCustoms || prepareCustoms[coordSys.type],
                'This coordSys does not support custom series.'
            );
P
pah100 已提交
1229 1230
        }

1
100pah 已提交
1231
        // `coordSys.prepareCustoms` is used for external coord sys like bmap.
S
sushuang 已提交
1232
        prepareResult = coordSys.prepareCustoms
1
100pah 已提交
1233
            ? coordSys.prepareCustoms(coordSys)
S
sushuang 已提交
1234 1235
            : prepareCustoms[coordSys.type](coordSys);
    }
P
pah100 已提交
1236

1237
    const userAPI = defaults({
S
sushuang 已提交
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
        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
1
100pah 已提交
1249
    }, prepareResult.api || {}) as CustomSeriesRenderItemAPI;
S
sushuang 已提交
1250

1
100pah 已提交
1251
    const userParams: CustomSeriesRenderItemParams = {
S
tweak.  
sushuang 已提交
1252 1253 1254
        // 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 已提交
1255 1256 1257 1258 1259 1260 1261 1262
        context: {},
        seriesId: customSeries.id,
        seriesName: customSeries.name,
        seriesIndex: customSeries.seriesIndex,
        coordSys: prepareResult.coordSys,
        dataInsideLength: data.count(),
        encode: wrapEncodeDef(customSeries.getData())
    };
P
pah100 已提交
1263

1
100pah 已提交
1264 1265 1266 1267
    // If someday intending to refactor them to a class, should consider do not
    // break change: currently these attribute member are encapsulated in a closure
    // so that do not need to force user to call these method with a scope.

S
sushuang 已提交
1268
    // Do not support call `api` asynchronously without dataIndexInside input.
1
100pah 已提交
1269
    let currDataIndexInside: number;
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
    let currItemModel: Model<LegacyCustomSeriesOption>;
    let currItemStyleModels: Partial<Record<DisplayState, Model<LegacyCustomSeriesOption['itemStyle']>>> = {};
    let currLabelModels: Partial<Record<DisplayState, Model<LegacyCustomSeriesOption['label']>>> = {};

    const seriesItemStyleModels = {} as Record<DisplayState, Model<LegacyCustomSeriesOption['itemStyle']>>;

    const seriesLabelModels = {} as Record<DisplayState, Model<LegacyCustomSeriesOption['label']>>;

    for (let i = 0; i < STATES.length; i++) {
        const stateName = STATES[i];
        seriesItemStyleModels[stateName] = (customSeries as Model<LegacyCustomSeriesOption>)
            .getModel(PATH_ITEM_STYLE[stateName]);
        seriesLabelModels[stateName] = (customSeries as Model<LegacyCustomSeriesOption>)
            .getModel(PATH_LABEL[stateName]);
    }

    function getItemModel(dataIndexInside: number): Model<LegacyCustomSeriesOption> {
1
100pah 已提交
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
        return dataIndexInside === currDataIndexInside
            ? (currItemModel || (currItemModel = data.getItemModel(dataIndexInside)))
            : data.getItemModel(dataIndexInside);
    }
    function getItemStyleModel(dataIndexInside: number, state: DisplayState) {
        return !data.hasItemOption
            ? seriesItemStyleModels[state]
            : dataIndexInside === currDataIndexInside
            ? (currItemStyleModels[state] || (
                currItemStyleModels[state] = getItemModel(dataIndexInside).getModel(PATH_ITEM_STYLE[state])
            ))
            : getItemModel(dataIndexInside).getModel(PATH_ITEM_STYLE[state]);
    }
    function getLabelModel(dataIndexInside: number, state: DisplayState) {
        return !data.hasItemOption
            ? seriesLabelModels[state]
            : dataIndexInside === currDataIndexInside
            ? (currLabelModels[state] || (
                currLabelModels[state] = getItemModel(dataIndexInside).getModel(PATH_LABEL[state])
            ))
            : getItemModel(dataIndexInside).getModel(PATH_LABEL[state]);
    }

    return function (dataIndexInside: number, payload: Payload): CustomElementOption {
S
sushuang 已提交
1311
        currDataIndexInside = dataIndexInside;
1
100pah 已提交
1312 1313 1314
        currItemModel = null;
        currItemStyleModels = {};
        currLabelModels = {};
1315

S
sushuang 已提交
1316
        return renderItem && renderItem(
1317
            defaults({
S
sushuang 已提交
1318
                dataIndexInside: dataIndexInside,
1319 1320 1321
                dataIndex: data.getRawIndex(dataIndexInside),
                // Can be used for optimization when zoom or roam.
                actionType: payload ? payload.type : null
S
sushuang 已提交
1322 1323
            }, userParams),
            userAPI
S
sushuang 已提交
1324
        );
S
sushuang 已提交
1325
    };
P
pah100 已提交
1326

S
sushuang 已提交
1327 1328
    /**
     * @public
1
100pah 已提交
1329 1330
     * @param dim by default 0.
     * @param dataIndexInside by default `currDataIndexInside`.
S
sushuang 已提交
1331
     */
1
100pah 已提交
1332
    function value(dim?: DimensionLoose, dataIndexInside?: number): ParsedValue {
S
sushuang 已提交
1333 1334 1335
        dataIndexInside == null && (dataIndexInside = currDataIndexInside);
        return data.get(data.getDimension(dim || 0), dataIndexInside);
    }
P
pah100 已提交
1336

S
sushuang 已提交
1337
    /**
1
100pah 已提交
1338 1339 1340 1341 1342
     * @deprecated The orgininal intention of `api.style` is enable to set itemStyle
     * like other series. But it not necessary and not easy to give a strict definition
     * of what it return. And since echarts5 it needs to be make compat work. So
     * deprecates it since echarts5.
     *
S
sushuang 已提交
1343 1344 1345 1346
     * 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})`;
1
100pah 已提交
1347 1348 1349 1350 1351 1352
     *
     * [Compat]: since ec5, RectText has been separated from its hosts el.
     * so `api.style()` will only return the style from `itemStyle` but not handle `label`
     * any more. But `series.label` config is never published in doc.
     * We still compat it in `api.style()`. But not encourage to use it and will still not
     * to pulish it to doc.
S
sushuang 已提交
1353
     * @public
1
100pah 已提交
1354
     * @param dataIndexInside by default `currDataIndexInside`.
S
sushuang 已提交
1355
     */
1356
    function style(userProps?: ZRStyleProps, dataIndexInside?: number): ZRStyleProps {
1
100pah 已提交
1357 1358 1359 1360
        if (__DEV__) {
            warnDeprecated('api.style', 'Please write literal style directly instead.');
        }

S
sushuang 已提交
1361
        dataIndexInside == null && (dataIndexInside = currDataIndexInside);
P
pah100 已提交
1362

1
100pah 已提交
1363 1364 1365
        const style = data.getItemVisual(dataIndexInside, 'style');
        const visualColor = style && style.fill;
        const opacity = style && style.opacity;
P
pah100 已提交
1366

1
100pah 已提交
1367 1368
        let itemStyle = getItemStyleModel(dataIndexInside, NORMAL).getItemStyle();
        visualColor != null && (itemStyle.fill = visualColor);
S
sushuang 已提交
1369
        opacity != null && (itemStyle.opacity = opacity);
P
pah100 已提交
1370

1371
        const opt = {inheritColor: isString(visualColor) ? visualColor : '#000'};
1
100pah 已提交
1372 1373 1374 1375
        const labelModel = getLabelModel(dataIndexInside, NORMAL);
        // Now that the feture of "auto adjust text fill/stroke" has been migrated to zrender
        // since ec5, we should set `isAttached` as `false` here and make compat in
        // `convertToEC4StyleForCustomSerise`.
1376
        const textStyle = labelStyleHelper.createTextStyle(labelModel, null, opt, false, true);
1
100pah 已提交
1377
        textStyle.text = labelModel.getShallow('show')
1378
            ? retrieve2(
1
100pah 已提交
1379
                customSeries.getFormattedLabel(dataIndexInside, NORMAL),
S
sushuang 已提交
1380 1381 1382
                getDefaultLabel(data, dataIndexInside)
            )
            : null;
P
pissang 已提交
1383
        const textConfig = labelStyleHelper.createTextConfig(labelModel, opt, false);
1
100pah 已提交
1384

1385
        preFetchFromExtra(userProps, itemStyle);
1
100pah 已提交
1386
        itemStyle = convertToEC4StyleForCustomSerise(itemStyle, textStyle, textConfig);
P
pah100 已提交
1387

1388
        userProps && applyUserPropsAfter(itemStyle, userProps);
1
100pah 已提交
1389
        (itemStyle as LegacyStyleProps).legacy = true;
1390

S
sushuang 已提交
1391 1392
        return itemStyle;
    }
P
pah100 已提交
1393

S
sushuang 已提交
1394
    /**
1
100pah 已提交
1395
     * @deprecated The reason see `api.style()`
S
sushuang 已提交
1396
     * @public
1
100pah 已提交
1397
     * @param dataIndexInside by default `currDataIndexInside`.
S
sushuang 已提交
1398
     */
1399
    function styleEmphasis(userProps?: ZRStyleProps, dataIndexInside?: number): ZRStyleProps {
1
100pah 已提交
1400 1401 1402
        if (__DEV__) {
            warnDeprecated('api.styleEmphasis', 'Please write literal style directly instead.');
        }
1403

1
100pah 已提交
1404
        dataIndexInside == null && (dataIndexInside = currDataIndexInside);
S
sushuang 已提交
1405

1
100pah 已提交
1406 1407
        let itemStyle = getItemStyleModel(dataIndexInside, EMPHASIS).getItemStyle();
        const labelModel = getLabelModel(dataIndexInside, EMPHASIS);
1408
        const textStyle = labelStyleHelper.createTextStyle(labelModel, null, null, true, true);
1
100pah 已提交
1409
        textStyle.text = labelModel.getShallow('show')
1410
            ? retrieve3(
1
100pah 已提交
1411 1412
                customSeries.getFormattedLabel(dataIndexInside, EMPHASIS),
                customSeries.getFormattedLabel(dataIndexInside, NORMAL),
S
sushuang 已提交
1413 1414 1415
                getDefaultLabel(data, dataIndexInside)
            )
            : null;
P
pissang 已提交
1416
        const textConfig = labelStyleHelper.createTextConfig(labelModel, null, true);
1
100pah 已提交
1417

1418
        preFetchFromExtra(userProps, itemStyle);
1
100pah 已提交
1419
        itemStyle = convertToEC4StyleForCustomSerise(itemStyle, textStyle, textConfig);
P
pah100 已提交
1420

1421
        userProps && applyUserPropsAfter(itemStyle, userProps);
1
100pah 已提交
1422
        (itemStyle as LegacyStyleProps).legacy = true;
1423

S
sushuang 已提交
1424
        return itemStyle;
P
pah100 已提交
1425 1426
    }

1427
    function applyUserPropsAfter(itemStyle: ZRStyleProps, extra: ZRStyleProps): void {
1428 1429 1430 1431 1432 1433 1434
        for (const key in extra) {
            if (hasOwn(extra, key)) {
                (itemStyle as any)[key] = (extra as any)[key];
            }
        }
    }

1
100pah 已提交
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
    function preFetchFromExtra(extra: ZRStyleProps, itemStyle: ItemStyleProps): void {
        // A trick to retrieve those props firstly, which are used to
        // apply auto inside fill/stroke in `convertToEC4StyleForCustomSerise`.
        // (It's not reasonable but only for a degree of compat)
        if (extra) {
            (extra as any).textFill && ((itemStyle as any).textFill = (extra as any).textFill);
            (extra as any).textPosition && ((itemStyle as any).textPosition = (extra as any).textPosition);
        }
    }

S
sushuang 已提交
1445 1446
    /**
     * @public
1
100pah 已提交
1447
     * @param dataIndexInside by default `currDataIndexInside`.
S
sushuang 已提交
1448
     */
1
100pah 已提交
1449 1450 1451 1452
    function visual(
        visualType: keyof DefaultDataVisual,
        dataIndexInside?: number
    ): ReturnType<List['getItemVisual']> {
S
sushuang 已提交
1453
        dataIndexInside == null && (dataIndexInside = currDataIndexInside);
1
100pah 已提交
1454

1455
        if (hasOwn(STYLE_VISUAL_TYPE, visualType)) {
1
100pah 已提交
1456 1457 1458 1459 1460 1461 1462
            const style = data.getItemVisual(dataIndexInside, 'style');
            return style
                ? style[STYLE_VISUAL_TYPE[visualType as keyof typeof STYLE_VISUAL_TYPE]] as any
                : null;
        }
        // Only support these visuals. Other visual might be inner tricky
        // for performance (like `style`), do not expose to users.
1463
        if (hasOwn(VISUAL_PROPS, visualType)) {
1
100pah 已提交
1464 1465
            return data.getItemVisual(dataIndexInside, visualType);
        }
P
pah100 已提交
1466 1467
    }

S
sushuang 已提交
1468 1469
    /**
     * @public
1
100pah 已提交
1470
     * @return If not support, return undefined.
S
sushuang 已提交
1471
     */
1
100pah 已提交
1472 1473 1474 1475 1476
    function barLayout(
        opt: Omit<Parameters<typeof getLayoutOnAxis>[0], 'axis'>
    ): ReturnType<typeof getLayoutOnAxis> {
        if (coordSys.type === 'cartesian2d') {
            const baseAxis = coordSys.getBaseAxis() as Axis2D;
1477
            return getLayoutOnAxis(defaults({axis: baseAxis}, opt));
1478
        }
P
pah100 已提交
1479 1480
    }

S
sushuang 已提交
1481 1482 1483
    /**
     * @public
     */
1
100pah 已提交
1484
    function currentSeriesIndices(): ReturnType<GlobalModel['getCurrentSeriesIndices']> {
S
sushuang 已提交
1485
        return ecModel.getCurrentSeriesIndices();
1486 1487
    }

S
sushuang 已提交
1488 1489
    /**
     * @public
1
100pah 已提交
1490
     * @return font string
S
sushuang 已提交
1491
     */
1
100pah 已提交
1492
    function font(
1493 1494
        opt: Parameters<typeof labelStyleHelper.getFont>[0]
    ): ReturnType<typeof labelStyleHelper.getFont> {
1495
        return labelStyleHelper.getFont(opt, ecModel);
S
sushuang 已提交
1496 1497 1498
    }
}

1
100pah 已提交
1499 1500
function wrapEncodeDef(data: List<CustomSeriesModel>): Dictionary<number[]> {
    const encodeDef = {} as Dictionary<number[]>;
1501
    each(data.dimensions, function (dimName, dataDimIndex) {
1502
        const dimInfo = data.getDimensionInfo(dimName);
S
sushuang 已提交
1503
        if (!dimInfo.isExtraCoord) {
1504 1505
            const coordDim = dimInfo.coordDim;
            const dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
S
sushuang 已提交
1506 1507 1508 1509 1510 1511
            dataDims[dimInfo.coordDimIndex] = dataDimIndex;
        }
    });
    return encodeDef;
}

1512
function createOrUpdateItem(
1
100pah 已提交
1513 1514 1515 1516 1517 1518 1519
    el: Element,
    dataIndex: number,
    elOption: CustomElementOption,
    seriesModel: CustomSeriesModel,
    group: ViewRootGroup,
    data: List<CustomSeriesModel>
): Element {
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
    // [Rule]
    // 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.)
    // The rule or "merge" see [STRATEGY_MERGE].

    // If `elOption` is `null`/`undefined`/`false` (when `renderItem` returns nothing).
    if (!elOption) {
        el && group.remove(el);
        return;
    }
    el = doCreateOrUpdateEl(el, dataIndex, elOption, seriesModel, group, true);
S
sushuang 已提交
1533
    el && data.setItemGraphicEl(dataIndex, el);
P
pissang 已提交
1534

1535 1536
    enableHoverEmphasis(el, elOption.focus, elOption.blurScope);

P
pissang 已提交
1537
    return el;
S
sushuang 已提交
1538 1539
}

1540
function doCreateOrUpdateEl(
1
100pah 已提交
1541 1542 1543 1544 1545 1546 1547
    el: Element,
    dataIndex: number,
    elOption: CustomElementOption,
    seriesModel: CustomSeriesModel,
    group: ViewRootGroup,
    isRoot: boolean
): Element {
1548

1549 1550
    if (__DEV__) {
        assert(elOption, 'should not have an null/undefined element setting');
1
100pah 已提交
1551
    }
S
sushuang 已提交
1552

1553
    let toBeReplacedIdx = -1;
S
sushuang 已提交
1554

1555 1556 1557 1558
    if (el && doesElNeedRecreate(el, elOption)) {
        // Should keep at the original index, otherwise "merge by index" will be incorrect.
        toBeReplacedIdx = group.childrenRef().indexOf(el);
        el = null;
1559 1560
    }

1
100pah 已提交
1561 1562 1563 1564 1565 1566
    const isInit = !el;

    if (!el) {
        el = createEl(elOption);
    }
    else {
1567
        // FIMXE:NEXT unified clearState?
1
100pah 已提交
1568 1569 1570
        // If in some case the performance issue arised, consider
        // do not clearState but update cached normal state directly.
        el.clearStates();
1571 1572
    }

1
100pah 已提交
1573
    attachedTxInfoTmp.normal.cfg = attachedTxInfoTmp.normal.conOpt =
1574 1575 1576 1577
        attachedTxInfoTmp.emphasis.cfg = attachedTxInfoTmp.emphasis.conOpt =
        attachedTxInfoTmp.blur.cfg = attachedTxInfoTmp.blur.conOpt =
        attachedTxInfoTmp.select.cfg = attachedTxInfoTmp.select.conOpt = null;

1
100pah 已提交
1578 1579 1580 1581 1582 1583
    attachedTxInfoTmp.isLegacy = false;

    doCreateOrUpdateAttachedTx(
        el, dataIndex, elOption, seriesModel, isInit, attachedTxInfoTmp
    );

1584 1585 1586 1587
    doCreateOrUpdateClipPath(
        el, dataIndex, elOption, seriesModel, isInit
    );

1
100pah 已提交
1588
    updateElNormal(el, dataIndex, elOption, elOption.style, attachedTxInfoTmp, seriesModel, isInit, false);
1589 1590 1591 1592 1593 1594 1595 1596 1597

    for (let i = 0; i < STATES.length; i++) {
        const stateName = STATES[i];
        if (stateName !== NORMAL) {
            const otherStateOpt = retrieveStateOption(elOption, stateName);
            const otherStyleOpt = retrieveStyleOptionOnState(elOption, otherStateOpt, stateName);
            updateElOnState(stateName, el, otherStateOpt, otherStyleOpt, attachedTxInfoTmp, isRoot, false);
        }
    }
1
100pah 已提交
1598 1599

    updateZ(el, elOption, seriesModel, attachedTxInfoTmp);
S
sushuang 已提交
1600

1601
    if (elOption.type === 'group') {
1602
        mergeChildren(el as graphicUtil.Group, dataIndex, elOption as CustomGroupOption, seriesModel);
1603 1604
    }

1605 1606 1607 1608 1609 1610
    if (toBeReplacedIdx >= 0) {
        group.replaceAt(el, toBeReplacedIdx);
    }
    else {
        group.add(el);
    }
S
sushuang 已提交
1611 1612 1613 1614

    return el;
}

1615 1616 1617
// `el` must not be null/undefined.
function doesElNeedRecreate(el: Element, elOption: CustomElementOption): boolean {
    const elInner = inner(el);
1618
    const elOptionType = elOption.type;
1619
    const elOptionShape = (elOption as CustomZRPathOption).shape;
1620
    const elOptionStyle = elOption.style;
1621
    return (
S
sushuang 已提交
1622
        // If `elOptionType` is `null`, follow the merge principle.
1623 1624
        (elOptionType != null
            && elOptionType !== elInner.customGraphicType
S
sushuang 已提交
1625 1626
        )
        || (elOptionType === 'path'
1627 1628
            && hasOwnPathData(elOptionShape)
            && getPathData(elOptionShape) !== elInner.customPathData
S
sushuang 已提交
1629 1630
        )
        || (elOptionType === 'image'
1631
            && hasOwn(elOptionStyle, 'image')
1632
            && (elOptionStyle as CustomImageOption['style']).image !== elInner.customImagePath
S
sushuang 已提交
1633
        )
1634 1635
        // // FIXME test and remove this restriction?
        // || (elOptionType === 'text'
1636
        //     && hasOwn(elOptionStyle, 'text')
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
        //     && (elOptionStyle as TextStyleProps).text !== elInner.customText
        // )
    );
}

function doCreateOrUpdateClipPath(
    el: Element,
    dataIndex: number,
    elOption: CustomElementOption,
    seriesModel: CustomSeriesModel,
    isInit: boolean
): void {
    // Based on the "merge" principle, if no clipPath provided,
    // do nothing. The exists clip will be totally removed only if
    // `el.clipPath` is `false`. Otherwise it will be merged/replaced.
    const clipPathOpt = elOption.clipPath;
    if (clipPathOpt === false) {
        if (el && el.getClipPath()) {
            el.removeClipPath();
        }
1657
    }
1658 1659 1660 1661 1662 1663 1664 1665
    else if (clipPathOpt) {
        let clipPath = el.getClipPath();
        if (clipPath && doesElNeedRecreate(clipPath, clipPathOpt)) {
            clipPath = null;
        }
        if (!clipPath) {
            clipPath = createEl(clipPathOpt) as graphicUtil.Path;
            if (__DEV__) {
1666
                assert(
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
                    clipPath instanceof graphicUtil.Path,
                    'Only any type of `path` can be used in `clipPath`, rather than ' + clipPath.type + '.'
                );
            }
            el.setClipPath(clipPath);
        }
        updateElNormal(
            clipPath, dataIndex, clipPathOpt, null, null, seriesModel, isInit, false
        );
    }
    // If not define `clipPath` in option, do nothing unnecessary.
}
1679

1
100pah 已提交
1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
function doCreateOrUpdateAttachedTx(
    el: Element,
    dataIndex: number,
    elOption: CustomElementOption,
    seriesModel: CustomSeriesModel,
    isInit: boolean,
    attachedTxInfo: AttachedTxInfo
): void {
    // group do not support textContent temporarily untill necessary.
    if (el.isGroup) {
S
sushuang 已提交
1690
        return;
1691 1692
    }

1
100pah 已提交
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
    // Normal must be called before emphasis, for `isLegacy` detection.
    processTxInfo(elOption, null, attachedTxInfo);
    processTxInfo(elOption, EMPHASIS, attachedTxInfo);

    // If `elOption.textConfig` or `elOption.textContent` is null/undefined, it does not make sence.
    // So for simplicity, if "elOption hasOwnProperty of them but be null/undefined", we do not
    // trade them as set to null to el.
    // Especially:
    // `elOption.textContent: false` means remove textContent.
    // `elOption.textContent.emphasis.style: false` means remove the style from emphasis state.
    let txConOptNormal = attachedTxInfo.normal.conOpt as CustomElementOption | false;
    const txConOptEmphasis = attachedTxInfo.emphasis.conOpt as CustomElementOptionOnState;
1705 1706
    const txConOptBlur = attachedTxInfo.blur.conOpt as CustomElementOptionOnState;
    const txConOptSelect = attachedTxInfo.select.conOpt as CustomElementOptionOnState;
1
100pah 已提交
1707

1708
    if (txConOptNormal != null || txConOptEmphasis != null || txConOptSelect != null || txConOptBlur != null) {
1
100pah 已提交
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
        let textContent = el.getTextContent();
        if (txConOptNormal === false) {
            textContent && el.removeTextContent();
        }
        else {
            txConOptNormal = attachedTxInfo.normal.conOpt = txConOptNormal || {type: 'text'};
            if (!textContent) {
                textContent = createEl(txConOptNormal) as graphicUtil.Text;
                el.setTextContent(textContent);
            }
            else {
                // If in some case the performance issue arised, consider
                // do not clearState but update cached normal state directly.
                textContent.clearStates();
            }
            const txConStlOptNormal = txConOptNormal && txConOptNormal.style;

            updateElNormal(
                textContent, dataIndex, txConOptNormal, txConStlOptNormal, null, seriesModel, isInit, true
            );
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
            for (let i = 0; i < STATES.length; i++) {
                const stateName = STATES[i];
                if (stateName !== NORMAL) {
                    const txConOptOtherState = attachedTxInfo[stateName].conOpt as CustomElementOptionOnState;
                    updateElOnState(
                        stateName,
                        textContent,
                        txConOptOtherState,
                        retrieveStyleOptionOnState(txConOptNormal, txConOptOtherState, stateName),
                        null, false, true
                    );
                }
            }
S
sushuang 已提交
1742

1743
            txConStlOptNormal ? textContent.dirty() : textContent.markRedraw();
1
100pah 已提交
1744
        }
1745
    }
1
100pah 已提交
1746
}
1747

1
100pah 已提交
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
function processTxInfo(
    elOption: CustomElementOption,
    state: DisplayStateNonNormal,
    attachedTxInfo: AttachedTxInfo
): void {
    const stateOpt = !state ? elOption : retrieveStateOption(elOption, state);
    const styleOpt = !state ? elOption.style : retrieveStyleOptionOnState(elOption, stateOpt, EMPHASIS);

    const elType = elOption.type;
    let txCfg = stateOpt ? stateOpt.textConfig : null;
    const txConOptNormal = elOption.textContent;
    let txConOpt: CustomElementOption | CustomElementOptionOnState =
        !txConOptNormal ? null : !state ? txConOptNormal : retrieveStateOption(txConOptNormal, state);

    if (styleOpt && (
        // Because emphasis style has little info to detect legacy,
        // if normal is legacy, emphasis is trade as legacy.
        attachedTxInfo.isLegacy
        || isEC4CompatibleStyle(styleOpt, elType, !!txCfg, !!txConOpt)
    )) {
        attachedTxInfo.isLegacy = true;
        const convertResult = convertFromEC4CompatibleStyle(styleOpt, elType, !state);
        // Explicitly specified `textConfig` and `textContent` has higher priority than
        // the ones generated by legacy style. Otherwise if users use them and `api.style`
        // at the same time, they not both work and hardly to known why.
        if (!txCfg && convertResult.textConfig) {
            txCfg = convertResult.textConfig;
        }
        if (!txConOpt && convertResult.textContent) {
            txConOpt = convertResult.textContent;
        }
    }
S
sushuang 已提交
1780

1
100pah 已提交
1781 1782 1783 1784 1785 1786
    if (!state && txConOpt) {
        const txConOptNormal = txConOpt as CustomElementOption;
        // `textContent: {type: 'text'}`, the "type" is easy to be missing. So we tolerate it.
        !txConOptNormal.type && (txConOptNormal.type = 'text');
        if (__DEV__) {
            // Do not tolerate incorret type for forward compat.
1787
            txConOptNormal.type !== 'text' && assert(
1
100pah 已提交
1788 1789 1790 1791 1792 1793 1794 1795 1796
                txConOptNormal.type === 'text',
                'textContent.type must be "text"'
            );
        }
    }

    const info = !state ? attachedTxInfo.normal : attachedTxInfo[state];
    info.cfg = txCfg;
    info.conOpt = txConOpt;
S
sushuang 已提交
1797 1798
}

1
100pah 已提交
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
function retrieveStateOption(
    elOption: CustomElementOption, state: DisplayStateNonNormal
): CustomElementOptionOnState {
    return !state ? elOption : elOption ? elOption[state] : null;
}

function retrieveStyleOptionOnState(
    stateOptionNormal: CustomElementOption,
    stateOption: CustomElementOptionOnState,
    state: DisplayStateNonNormal
1809
): CustomElementOptionOnState['style'] {
1
100pah 已提交
1810 1811 1812 1813 1814 1815 1816 1817
    let style = stateOption && stateOption.style;
    if (style == null && state === EMPHASIS && stateOptionNormal) {
        style = stateOptionNormal.styleEmphasis;
    }
    return style;
}


1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
// 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 已提交
1828 1829
// (4) If `!elOption.children`, following the "merge" principle, nothing will happen.
//
1830 1831
// 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).
1832
// User can remove a single child by set its `ignore` as `true`.
1
100pah 已提交
1833 1834 1835 1836
function mergeChildren(
    el: graphicUtil.Group,
    dataIndex: number,
    elOption: CustomGroupOption,
1837
    seriesModel: CustomSeriesModel
1
100pah 已提交
1838 1839
): void {

1840 1841 1842
    const newChildren = elOption.children;
    const newLen = newChildren ? newChildren.length : 0;
    const mergeChildren = elOption.$mergeChildren;
1843
    // `diffChildrenByName` has been deprecated.
1844 1845
    const byName = mergeChildren === 'byName' || elOption.diffChildrenByName;
    const notMerge = mergeChildren === false;
1846 1847

    // For better performance on roam update, only enter if necessary.
S
tweak.  
sushuang 已提交
1848
    if (!newLen && !byName && !notMerge) {
1849 1850 1851 1852 1853 1854 1855 1856
        return;
    }

    if (byName) {
        diffGroupChildren({
            oldChildren: el.children() || [],
            newChildren: newChildren || [],
            dataIndex: dataIndex,
1
100pah 已提交
1857
            seriesModel: seriesModel,
1858
            group: el
1859 1860 1861 1862 1863 1864 1865 1866
        });
        return;
    }

    notMerge && el.removeAll();

    // Mapping children of a group simply by index, which
    // might be better performance.
1867
    let index = 0;
1868
    for (; index < newLen; index++) {
1869
        newChildren[index] && doCreateOrUpdateEl(
1870 1871 1872
            el.childAt(index),
            dataIndex,
            newChildren[index],
1
100pah 已提交
1873
            seriesModel,
1874
            el,
1
100pah 已提交
1875
            false
1876 1877
        );
    }
1878
    for (let i = el.childCount() - 1; i >= index; i--) {
1879 1880 1881
        // Do not supprot leave elements that are not mentioned in the latest
        // `renderItem` return. Otherwise users may not have a clear and simple
        // concept that how to contorl all of the elements.
1882
        doRemoveEl(el.childAt(i), seriesModel, el);
1883 1884 1885
    }
}

1
100pah 已提交
1886 1887 1888 1889 1890
type DiffGroupContext = {
    oldChildren: Element[],
    newChildren: CustomElementOption[],
    dataIndex: number,
    seriesModel: CustomSeriesModel,
1891
    group: graphicUtil.Group
1
100pah 已提交
1892 1893
};
function diffGroupChildren(context: DiffGroupContext) {
S
sushuang 已提交
1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
    (new DataDiffer(
        context.oldChildren,
        context.newChildren,
        getKey,
        getKey,
        context
    ))
        .add(processAddUpdate)
        .update(processAddUpdate)
        .remove(processRemove)
        .execute();
}

1
100pah 已提交
1907
function getKey(item: Element, idx: number): string {
1908
    const name = item && item.name;
S
sushuang 已提交
1909 1910 1911
    return name != null ? name : GROUP_DIFF_PREFIX + idx;
}

1
100pah 已提交
1912 1913 1914 1915 1916
function processAddUpdate(
    this: DataDiffer<DiffGroupContext>,
    newIndex: number,
    oldIndex?: number
): void {
1917 1918 1919
    const context = this.context;
    const childOption = newIndex != null ? context.newChildren[newIndex] : null;
    const child = oldIndex != null ? context.oldChildren[oldIndex] : null;
S
sushuang 已提交
1920

1921
    doCreateOrUpdateEl(
S
sushuang 已提交
1922 1923 1924
        child,
        context.dataIndex,
        childOption,
1
100pah 已提交
1925
        context.seriesModel,
S
sushuang 已提交
1926
        context.group,
1
100pah 已提交
1927
        false
S
sushuang 已提交
1928 1929 1930
    );
}

1
100pah 已提交
1931
function processRemove(this: DataDiffer<DiffGroupContext>, oldIndex: number): void {
1932 1933
    const context = this.context;
    const child = context.oldChildren[oldIndex];
1934
    doRemoveEl(child, context.seriesModel, context.group);
1935 1936
}

1937
function doRemoveEl(
1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950
    el: Element,
    seriesModel: CustomSeriesModel,
    group: ViewRootGroup
): void {
    if (el) {
        const leaveToProps = inner(el).leaveToProps;
        leaveToProps
            ? graphicUtil.updateProps(el, leaveToProps, seriesModel, {
                cb: function () {
                    group.remove(el);
                }
            })
            : group.remove(el);
1951 1952 1953
    }
}

1
100pah 已提交
1954 1955 1956 1957
/**
 * @return SVG Path data.
 */
function getPathData(shape: CustomSVGPathOption['shape']): string {
S
sushuang 已提交
1958 1959 1960 1961
    // "d" follows the SVG convention.
    return shape && (shape.pathData || shape.d);
}

1
100pah 已提交
1962
function hasOwnPathData(shape: CustomSVGPathOption['shape']): boolean {
1963
    return shape && (hasOwn(shape, 'pathData') || hasOwn(shape, 'd'));
S
sushuang 已提交
1964 1965
}