custom.ts 99.9 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.
*/

20
import {
21
    hasOwn, assert, isString, retrieve2, retrieve3, defaults, each,
22
    keys, isArrayLike, bind, isFunction, eqNaN, indexOf, clone
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';
30
import DataDiffer, { DataDiffMode } 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
    DisplayStateNonNormal,
53
    BlurScope,
54
    SeriesDataType,
55 56
    OrdinalRawValue,
    PayloadAnimationPart
1
100pah 已提交
57 58
} from '../util/types';
import Element, { ElementProps, ElementTextConfig } from 'zrender/src/Element';
S
sushuang 已提交
59 60 61 62 63
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 已提交
64 65 66
import ComponentModel from '../model/Component';
import List, { DefaultDataVisual } from '../data/List';
import GlobalModel from '../model/Global';
67
import { makeInner, normalizeToArray } from '../util/model';
1
100pah 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
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';
85
import { cloneValue } from 'zrender/src/animation/Animator';
86 87
import { warn, throwError } from '../util/log';
import {
88
    combine, isInAnyMorphing, morphPath, isCombiningPath, CombineSeparateConfig, separate, CombineSeparateResult
89 90
} from 'zrender/src/tool/morphPath';
import { AnimationEasing } from 'zrender/src/animation/easing';
91
import * as matrix from 'zrender/src/core/matrix';
1
100pah 已提交
92 93 94 95 96 97 98


const inner = makeInner<{
    info: CustomExtraElementInfo;
    customPathData: string;
    customGraphicType: string;
    customImagePath: CustomImageOption['style']['image'];
99
    // customText: string;
1
100pah 已提交
100
    txConZ2Set: number;
101
    leaveToProps: ElementProps;
102 103
    // Can morph: "morph" specified in option and el is Path.
    canMorph: boolean;
104
    userDuring: CustomBaseElementOption['during'];
1
100pah 已提交
105 106 107
}, Element>();

type CustomExtraElementInfo = Dictionary<unknown>;
108 109 110 111 112 113 114 115 116
const TRANSFORM_PROPS = {
    x: 1,
    y: 1,
    scaleX: 1,
    scaleY: 1,
    originX: 1,
    originY: 1,
    rotation: 1
} as const;
117
type TransformProp = keyof typeof TRANSFORM_PROPS;
118
const transformPropNamesStr = keys(TRANSFORM_PROPS).join(', ');
119 120 121

// Do not declare "Dictionary" in TransitionAnyOption to restrict the type check.
type TransitionAnyOption = {
122 123 124
    transition?: TransitionAnyProps;
    enterFrom?: Dictionary<unknown>;
    leaveTo?: Dictionary<unknown>;
125
};
126
type TransitionAnyProps = string | string[];
127
type TransitionTransformOption = {
128
    transition?: ElementRootTransitionProp | ElementRootTransitionProp[];
129 130
    enterFrom?: Dictionary<unknown>;
    leaveTo?: Dictionary<unknown>;
131
};
132
type ElementRootTransitionProp = TransformProp | 'shape' | 'extra' | 'style';
133 134 135 136 137
type ShapeMorphingOption = {
    /**
     * If do shape morphing animation when type is changed.
     * Only available on path.
     */
138
    morph?: boolean
139
};
1
100pah 已提交
140 141

interface CustomBaseElementOption extends Partial<Pick<
142
    Element, TransformProp | 'silent' | 'ignore' | 'textConfig'
143
>>, TransitionTransformOption {
1
100pah 已提交
144 145 146 147 148 149 150 151
    // element type, mandatory.
    type: string;
    id?: string;
    // For animation diff.
    name?: string;
    info?: CustomExtraElementInfo;
    // `false` means remove the textContent.
    textContent?: CustomTextOption | false;
152 153
    // `false` means remove the clipPath
    clipPath?: CustomZRPathOption | false;
154 155
    // `extra` can be set in any el option for custom prop for annimation duration.
    extra?: TransitionAnyOption;
156
    // updateDuringAnimation
157
    during?(params: typeof customDuringAPI): void;
158

159
    focus?: 'none' | 'self' | 'series' | ArrayLike<number>
160
    blurScope?: BlurScope
1
100pah 已提交
161 162 163 164
};
interface CustomDisplayableOption extends CustomBaseElementOption, Partial<Pick<
    Displayable, 'zlevel' | 'z' | 'z2' | 'invisible'
>> {
165
    style?: ZRStyleProps & TransitionAnyOption;
1
100pah 已提交
166 167 168
    // `false` means remove emphasis trigger.
    styleEmphasis?: ZRStyleProps | false;
    emphasis?: CustomDisplayableOptionOnState;
169 170
    blur?: CustomDisplayableOptionOnState;
    select?: CustomDisplayableOptionOnState;
1
100pah 已提交
171 172
}
interface CustomDisplayableOptionOnState extends Partial<Pick<
173
    Displayable, TransformProp | 'textConfig' | 'z2'
1
100pah 已提交
174 175
>> {
    // `false` means remove emphasis trigger.
176
    style?: (ZRStyleProps & TransitionAnyOption) | false;
1
100pah 已提交
177 178 179 180 181
}
interface CustomGroupOption extends CustomBaseElementOption {
    type: 'group';
    width?: number;
    height?: number;
182
    // @deprecated
1
100pah 已提交
183
    diffChildrenByName?: boolean;
184 185
    // Can only set focus, blur on the root element.
    children: Omit<CustomElementOption, 'focus' | 'blurScope'>[];
1
100pah 已提交
186 187
    $mergeChildren: false | 'byName' | 'byIndex';
}
188
interface CustomZRPathOption extends CustomDisplayableOption, ShapeMorphingOption {
189
    shape?: PathProps['shape'] & TransitionAnyOption;
1
100pah 已提交
190
}
191
interface CustomSVGPathOption extends CustomDisplayableOption, ShapeMorphingOption {
1
100pah 已提交
192 193 194 195 196 197 198 199 200 201 202
    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;
203
    } & TransitionAnyOption;
1
100pah 已提交
204 205 206
}
interface CustomImageOption extends CustomDisplayableOption {
    type: 'image';
207
    style?: ImageStyleProps & TransitionAnyOption;
1
100pah 已提交
208
    emphasis?: CustomImageOptionOnState;
209 210
    blur?: CustomImageOptionOnState;
    select?: CustomImageOptionOnState;
1
100pah 已提交
211 212
}
interface CustomImageOptionOnState extends CustomDisplayableOptionOnState {
213
    style?: ImageStyleProps & TransitionAnyOption;
1
100pah 已提交
214 215 216 217 218 219 220 221 222 223 224 225
}
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;
226
    ordinalRawValue(dim: DimensionLoose, dataIndexInside?: number): ParsedValue | OrdinalRawValue;
227 228
    style(userProps?: ZRStyleProps, dataIndexInside?: number): ZRStyleProps;
    styleEmphasis(userProps?: ZRStyleProps, dataIndexInside?: number): ZRStyleProps;
1
100pah 已提交
229 230 231
    visual(visualType: string, dataIndexInside?: number): ReturnType<List['getItemVisual']>;
    barLayout(opt: Omit<Parameters<typeof getLayoutOnAxis>[0], 'axis'>): ReturnType<typeof getLayoutOnAxis>;
    currentSeriesIndices(): ReturnType<GlobalModel['getCurrentSeriesIndices']>;
232
    font(opt: Parameters<typeof labelStyleHelper.getFont>[0]): ReturnType<typeof labelStyleHelper.getFont>;
1
100pah 已提交
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
}
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 已提交
249
    context: Dictionary<unknown>;
1
100pah 已提交
250 251 252 253 254
    seriesId: string;
    seriesName: string;
    seriesIndex: number;
    coordSys: CustomSeriesRenderItemParamsCoordSys;
    dataInsideLength: number;
1
100pah 已提交
255
    encode: ReturnType<typeof wrapEncodeDef>;
1
100pah 已提交
256 257 258 259 260 261
}
type CustomSeriesRenderItem = (
    params: CustomSeriesRenderItemParams,
    api: CustomSeriesRenderItemAPI
) => CustomElementOption;

262 263 264 265
interface CustomSeriesStateOption {
    itemStyle?: ItemStyleOption;
    label?: LabelOption;
}
1
100pah 已提交
266

267
export interface CustomSeriesOption extends
268
    SeriesOption<never>,    // don't support StateOption in custom series.
1
100pah 已提交
269 270 271 272 273 274 275
    SeriesEncodeOptionMixin,
    SeriesOnCartesianOptionMixin,
    SeriesOnPolarOptionMixin,
    SeriesOnSingleOptionMixin,
    SeriesOnGeoOptionMixin,
    SeriesOnCalendarOptionMixin {

276 277
    type?: 'custom'

1
100pah 已提交
278 279 280 281
    // If set as 'none', do not depends on coord sys.
    coordinateSystem?: string | 'none';

    renderItem?: CustomSeriesRenderItem;
S
sushuang 已提交
282

1
100pah 已提交
283 284
    // Only works on polar and cartesian2d coordinate system.
    clip?: boolean;
S
sushuang 已提交
285

1
100pah 已提交
286 287 288 289
    // FIXME needed?
    tooltip?: SeriesTooltipOption;
}

290 291 292
interface LegacyCustomSeriesOption extends SeriesOption<CustomSeriesStateOption>, CustomSeriesStateOption {}


293 294 295 296 297
interface LooseElementProps extends ElementProps {
    style?: ZRStyleProps;
    shape?: Dictionary<unknown>;
}

1
100pah 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
// 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;
316 317 318
const BLUR = 'blur' as const;
const SELECT = 'select' as const;
const STATES = [NORMAL, EMPHASIS, BLUR, SELECT] as const;
1
100pah 已提交
319 320
const PATH_ITEM_STYLE = {
    normal: ['itemStyle'],
321 322 323
    emphasis: [EMPHASIS, 'itemStyle'],
    blur: [BLUR, 'itemStyle'],
    select: [SELECT, 'itemStyle']
1
100pah 已提交
324 325 326
} as const;
const PATH_LABEL = {
    normal: ['label'],
327 328 329
    emphasis: [EMPHASIS, 'label'],
    blur: [BLUR, 'label'],
    select: [SELECT, 'label']
1
100pah 已提交
330
} as const;
S
sushuang 已提交
331
// Use prefix to avoid index to be the same as el.name,
1
100pah 已提交
332
// which will cause weird update animation.
333
const GROUP_DIFF_PREFIX = 'e\0\0';
S
sushuang 已提交
334

1
100pah 已提交
335 336 337 338 339 340 341 342 343 344
type AttachedTxInfo = {
    isLegacy: boolean;
    normal: {
        cfg: ElementTextConfig;
        conOpt: CustomElementOption | false;
    };
    emphasis: {
        cfg: ElementTextConfig;
        conOpt: CustomElementOptionOnState;
    };
345 346 347 348 349 350 351 352
    blur: {
        cfg: ElementTextConfig;
        conOpt: CustomElementOptionOnState;
    };
    select: {
        cfg: ElementTextConfig;
        conOpt: CustomElementOptionOnState;
    };
1
100pah 已提交
353 354 355
};
const attachedTxInfoTmp = {
    normal: {},
356 357 358
    emphasis: {},
    blur: {},
    select: {}
1
100pah 已提交
359 360
} as AttachedTxInfo;

361 362 363 364 365 366 367
const LEGACY_TRANSFORM_PROPS = {
    position: ['x', 'y'],
    scale: ['scaleX', 'scaleY'],
    origin: ['originX', 'originY']
} as const;
type LegacyTransformProp = keyof typeof LEGACY_TRANSFORM_PROPS;

1
100pah 已提交
368 369 370 371
export type PrepareCustomInfo = (coordSys: CoordinateSystem) => {
    coordSys: CustomSeriesRenderItemParamsCoordSys;
    api: CustomSeriesRenderItemCoordinateSystemAPI
};
372

373 374
const tmpTransformable = new Transformable();

S
sushuang 已提交
375 376 377 378 379 380 381 382 383 384 385
/**
 * 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 已提交
386
const prepareCustoms: Dictionary<PrepareCustomInfo> = {
S
sushuang 已提交
387 388 389 390 391 392 393
    cartesian2d: prepareCartesian2d,
    geo: prepareGeo,
    singleAxis: prepareSingleAxis,
    polar: preparePolar,
    calendar: prepareCalendar
};

1
100pah 已提交
394
class CustomSeriesModel extends SeriesModel<CustomSeriesOption> {
395

1
100pah 已提交
396 397
    static type = 'series.custom';
    readonly type = CustomSeriesModel.type;
S
sushuang 已提交
398

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

401
    // preventAutoZ = true;
S
sushuang 已提交
402

1
100pah 已提交
403 404
    currentZLevel: number;
    currentZ: number;
S
sushuang 已提交
405

1
100pah 已提交
406
    static defaultOption: CustomSeriesOption = {
S
sushuang 已提交
407 408 409
        coordinateSystem: 'cartesian2d', // Can be set as 'none'
        zlevel: 0,
        z: 2,
410 411
        legendHoverLink: true,

412 413 414 415
        // 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 已提交
416 417 418 419 420 421 422 423 424 425

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

        // Polar coordinate system
        // polarIndex: 0,

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

1
100pah 已提交
428 429 430 431 432 433
    optionUpdated() {
        this.currentZLevel = this.get('zlevel', true);
        this.currentZ = this.get('z', true);
    }

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

437
    getDataParams(dataIndex: number, dataType?: SeriesDataType, el?: Element): CallbackDataParams & {
1
100pah 已提交
438 439
        info: CustomExtraElementInfo
    } {
440
        const params = super.getDataParams(dataIndex, dataType) as ReturnType<CustomSeriesModel['getDataParams']>;
1
100pah 已提交
441
        el && (params.info = inner(el).info);
442
        return params;
S
sushuang 已提交
443
    }
1
100pah 已提交
444
}
P
pah100 已提交
445

1
100pah 已提交
446
ComponentModel.registerClass(CustomSeriesModel);
P
pah100 已提交
447 448 449



1
100pah 已提交
450
class CustomSeriesView extends ChartView {
P
pah100 已提交
451

1
100pah 已提交
452 453 454 455 456 457 458 459 460 461 462 463
    static type = 'custom';
    readonly type = CustomSeriesView.type;

    private _data: List;


    render(
        customSeries: CustomSeriesModel,
        ecModel: GlobalModel,
        api: ExtensionAPI,
        payload: Payload
    ): void {
464 465 466 467
        const oldData = this._data;
        const data = customSeries.getData();
        const group = this.group;
        const renderItem = makeRenderItem(customSeries, data, ecModel, api);
S
sushuang 已提交
468

469 470 471 472 473
        // 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`.
1
100pah 已提交
474 475 476

        const transOpt = customSeries.__transientTransitionOpt;

477 478
        // Enable user to disable transition animation by both set
        // `from` and `to` dimension as `null`/`undefined`.
1
100pah 已提交
479 480 481 482 483 484 485 486 487 488 489
        if (transOpt && (transOpt.from == null || transOpt.to == null)) {
            oldData && oldData.each(function (oldIdx) {
                doRemoveEl(oldData.getItemGraphicEl(oldIdx), customSeries, group);
            });
            data.each(function (newIdx) {
                createOrUpdateItem(
                    null, newIdx, renderItem(newIdx, payload), customSeries, group, data, null
                );
            });
        }
        else {
490 491
            const morphPreparation = new MorphPreparation(customSeries, transOpt);
            const diffMode: DataDiffMode = transOpt ? 'multiple' : 'oneToOne';
492

1
100pah 已提交
493 494 495
            (new DataDiffer(
                oldData ? oldData.getIndices() : [],
                data.getIndices(),
496 497
                createGetKey(oldData, diffMode, transOpt && transOpt.from),
                createGetKey(data, diffMode, transOpt && transOpt.to),
1
100pah 已提交
498
                null,
499
                diffMode
1
100pah 已提交
500 501 502
            ))
            .add(function (newIdx) {
                createOrUpdateItem(
503 504
                    null, newIdx, renderItem(newIdx, payload), customSeries, group,
                    data, null
1
100pah 已提交
505 506
                );
            })
1
100pah 已提交
507 508 509
            .remove(function (oldIdx) {
                doRemoveEl(oldData.getItemGraphicEl(oldIdx), customSeries, group);
            })
1
100pah 已提交
510
            .update(function (newIdx, oldIdx) {
511 512 513 514 515 516 517 518 519 520 521 522 523 524
                morphPreparation.reset('oneToOne');
                let oldEl = oldData.getItemGraphicEl(oldIdx);
                morphPreparation.findAndAddFrom(oldEl);

                // PENDING:
                // if may morph, currently we alway recreate the whole el.
                // because if reuse some of the el in the group tree, the old el has to
                // be removed from the group, and consequently we can not calculate
                // the "global transition" of the old element.
                // But is there performance issue?
                if (morphPreparation.hasFrom()) {
                    removeElementDirectly(oldEl, group);
                    oldEl = null;
                }
1
100pah 已提交
525
                createOrUpdateItem(
526 527
                    oldEl, newIdx, renderItem(newIdx, payload), customSeries, group,
                    data, morphPreparation
1
100pah 已提交
528
                );
529
                morphPreparation.applyMorphing();
1
100pah 已提交
530 531
            })
            .updateManyToOne(function (newIdx, oldIndices) {
532
                morphPreparation.reset('manyToOne');
1
100pah 已提交
533 534
                for (let i = 0; i < oldIndices.length; i++) {
                    const oldEl = oldData.getItemGraphicEl(oldIndices[i]);
535
                    morphPreparation.findAndAddFrom(oldEl);
1
100pah 已提交
536
                    removeElementDirectly(oldEl, group);
1
100pah 已提交
537
                }
538
                createOrUpdateItem(
539 540
                    null, newIdx, renderItem(newIdx, payload), customSeries, group,
                    data, morphPreparation
541
                );
542
                morphPreparation.applyMorphing();
1
100pah 已提交
543 544
            })
            .updateOneToMany(function (newIndices, oldIdx) {
545
                morphPreparation.reset('oneToMany');
1
100pah 已提交
546 547
                const newLen = newIndices.length;
                const oldEl = oldData.getItemGraphicEl(oldIdx);
548
                morphPreparation.findAndAddFrom(oldEl);
1
100pah 已提交
549
                removeElementDirectly(oldEl, group);
550

1
100pah 已提交
551 552
                for (let i = 0; i < newLen; i++) {
                    createOrUpdateItem(
553 554
                        null, newIndices[i], renderItem(newIndices[i], payload), customSeries, group,
                        data, morphPreparation
1
100pah 已提交
555 556
                    );
                }
557
                morphPreparation.applyMorphing();
1
100pah 已提交
558 559 560
            })
            .execute();
        }
P
pah100 已提交
561

562
        // Do clipping
563
        const clipPath = customSeries.get('clip', true)
564 565 566 567 568 569 570 571 572
            ? createClipPath(customSeries.coordinateSystem, false, customSeries)
            : null;
        if (clipPath) {
            group.setClipPath(clipPath);
        }
        else {
            group.removeClipPath();
        }

S
sushuang 已提交
573
        this._data = data;
1
100pah 已提交
574
    }
P
pah100 已提交
575

1
100pah 已提交
576 577 578 579 580
    incrementalPrepareRender(
        customSeries: CustomSeriesModel,
        ecModel: GlobalModel,
        api: ExtensionAPI
    ): void {
P
pissang 已提交
581 582
        this.group.removeAll();
        this._data = null;
1
100pah 已提交
583
    }
P
pissang 已提交
584

1
100pah 已提交
585 586 587 588 589 590 591
    incrementalRender(
        params: StageHandlerProgressParams,
        customSeries: CustomSeriesModel,
        ecModel: GlobalModel,
        api: ExtensionAPI,
        payload: Payload
    ): void {
592 593
        const data = customSeries.getData();
        const renderItem = makeRenderItem(customSeries, data, ecModel, api);
1
100pah 已提交
594
        function setIncrementalAndHoverLayer(el: Displayable) {
P
pissang 已提交
595 596
            if (!el.isGroup) {
                el.incremental = true;
597
                el.ensureState('emphasis').hoverLayer = true;
P
pissang 已提交
598 599
            }
        }
600
        for (let idx = params.start; idx < params.end; idx++) {
1
100pah 已提交
601 602 603
            const el = createOrUpdateItem(
                null, idx, renderItem(idx, payload), customSeries, this.group, data, null
            );
P
pissang 已提交
604 605
            el.traverse(setIncrementalAndHoverLayer);
        }
1
100pah 已提交
606
    }
607

1
100pah 已提交
608
    filterForExposedEvent(
609 610
        eventType: string, query: EventQueryItem, targetEl: Element, packedEvent: ECEvent
    ): boolean {
611
        const elementName = query.element;
612
        if (elementName == null || targetEl.name === elementName) {
613 614 615 616 617
            return true;
        }

        // Enable to give a name on a group made by `renderItem`, and listen
        // events that triggerd by its descendents.
618
        while ((targetEl = (targetEl.__hostTarget || targetEl.parent)) && targetEl !== this.group) {
619
            if (targetEl.name === elementName) {
620 621 622 623 624 625
                return true;
            }
        }

        return false;
    }
1
100pah 已提交
626
}
P
pah100 已提交
627

1
100pah 已提交
628
ChartView.registerClass(CustomSeriesView);
P
pah100 已提交
629 630


1
100pah 已提交
631 632
function createGetKey(
    data: List,
633
    diffMode: DataDiffMode,
1
100pah 已提交
634 635
    dimension: DimensionLoose
) {
1
100pah 已提交
636 637 638 639
    if (!data) {
        return;
    }

640
    if (diffMode === 'oneToOne') {
1
100pah 已提交
641 642 643 644 645
        return function (rawIdx: number, dataIndex: number) {
            return data.getId(dataIndex);
        };
    }

1
100pah 已提交
646 647 648
    const diffByDimName = data.getDimension(dimension);
    const dimInfo = data.getDimensionInfo(diffByDimName);

1
100pah 已提交
649 650 651 652 653 654 655 656 657
    if (!dimInfo) {
        let errMsg = '';
        if (__DEV__) {
            errMsg = `${dimension} is not a valid dimension.`;
        }
        throwError(errMsg);
    }
    const ordinalMeta = dimInfo.ordinalMeta;
    return function (rawIdx: number, dataIndex: number) {
1
100pah 已提交
658
        let key = data.get(diffByDimName, dataIndex);
1
100pah 已提交
659 660 661 662 663 664 665 666 667 668
        if (ordinalMeta) {
            key = ordinalMeta.categories[key as number];
        }
        return (key == null || eqNaN(key))
            ? rawIdx + ''
            : '_ec_' + key;
    };
}


1
100pah 已提交
669
function createEl(elOption: CustomElementOption): Element {
670
    const graphicType = elOption.type;
671
    let el;
S
sushuang 已提交
672

673 674
    // Those graphic elements are not shapes. They should not be
    // overwritten by users, so do them first.
S
sushuang 已提交
675
    if (graphicType === 'path') {
1
100pah 已提交
676
        const shape = (elOption as CustomSVGPathOption).shape;
S
sushuang 已提交
677
        // Using pathRect brings convenience to users sacle svg path.
678
        const pathRect = (shape.width != null && shape.height != null)
S
sushuang 已提交
679
            ? {
S
sushuang 已提交
680 681
                x: shape.x || 0,
                y: shape.y || 0,
S
sushuang 已提交
682 683
                width: shape.width,
                height: shape.height
1
100pah 已提交
684
            } as RectLike
S
sushuang 已提交
685
            : null;
686
        const pathData = getPathData(shape);
S
sushuang 已提交
687 688
        // Path is also used for icon, so layout 'center' by default.
        el = graphicUtil.makePath(pathData, null, pathRect, shape.layout || 'center');
1
100pah 已提交
689
        inner(el).customPathData = pathData;
S
sushuang 已提交
690 691
    }
    else if (graphicType === 'image') {
692
        el = new graphicUtil.Image({});
1
100pah 已提交
693
        inner(el).customImagePath = (elOption as CustomImageOption).style.image;
S
sushuang 已提交
694 695
    }
    else if (graphicType === 'text') {
696
        el = new graphicUtil.Text({});
697
        // inner(el).customText = (elOption.style as TextStyleProps).text;
S
sushuang 已提交
698
    }
699 700 701 702 703 704
    else if (graphicType === 'group') {
        el = new graphicUtil.Group();
    }
    else if (graphicType === 'compoundPath') {
        throw new Error('"compoundPath" is not supported yet.');
    }
S
sushuang 已提交
705
    else {
706
        const Clz = graphicUtil.getShapeClass(graphicType);
1
100pah 已提交
707 708 709 710 711 712
        if (!Clz) {
            let errMsg = '';
            if (__DEV__) {
                errMsg = 'graphic type "' + graphicType + '" can not be found.';
            }
            throwError(errMsg);
P
pah100 已提交
713
        }
S
sushuang 已提交
714 715
        el = new Clz();
    }
P
pah100 已提交
716

1
100pah 已提交
717
    inner(el).customGraphicType = graphicType;
S
sushuang 已提交
718
    el.name = elOption.name;
P
pah100 已提交
719

1
100pah 已提交
720 721 722 723
    // 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;
724
    (el as ECElement).z2SelectLift = 1;
1
100pah 已提交
725

S
sushuang 已提交
726 727
    return el;
}
P
pah100 已提交
728

1
100pah 已提交
729
/**
730 731
 * ----------------------------------------------------------
 * [STRATEGY_MERGE] Merge properties or erase all properties:
1
100pah 已提交
732
 *
733
 * Based on the fact that the existing zr element probably be reused, we now consider whether
1
100pah 已提交
734
 * merge or erase all properties to the exsiting elements.
735 736 737
 * 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 已提交
738 739
 *
 * "Merge" might bring some unexpected state retaining for users and "erase all" seams to be
740 741 742 743
 * 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 已提交
744 745 746 747 748
 * 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.
 *
749 750 751 752 753 754 755
 * 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.
 *
756 757
 * ----------------------------------------------
 * [STRATEGY_NULL] `hasOwnProperty` or `== null`:
1
100pah 已提交
758 759 760 761 762 763 764
 *
 * 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.
765 766 767 768
 *
 * ---------------------------------------------
 * [STRATEGY_TRANSITION] The rule of transition:
 * + For props on the root level of a element:
769
 *      If there is no `transition` specified, tansform props will be transitioned by default,
770 771
 *      which is the same as the previous setting in echarts4 and suitable for the scenario
 *      of dataZoom change.
772
 *      If `transition` specified, only the specified props will be transitioned.
773
 * + For props in `shape` and `style`:
774
 *      Only props specified in `transition` will be transitioned.
775 776 777
 * + 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.
778 779
 *
 * @return if `isMorphTo`, return `allPropsFinal`.
1
100pah 已提交
780 781 782
 */
function updateElNormal(
    el: Element,
783 784
    // Whether be a morph target.
    isMorphTo: boolean,
1
100pah 已提交
785 786
    dataIndex: number,
    elOption: CustomElementOption,
787
    styleOpt: CustomElementOption['style'],
1
100pah 已提交
788 789 790 791
    attachedTxInfo: AttachedTxInfo,
    seriesModel: CustomSeriesModel,
    isInit: boolean,
    isTextContent: boolean
792
): ElementProps {
793
    const transFromProps = {} as ElementProps;
794
    const allPropsFinal = {} as ElementProps;
1
100pah 已提交
795 796
    const elDisplayable = el.isGroup ? null : el as Displayable;

797 798 799
    // If be "morph to", delay the `updateElNormal` when all of the els in
    // this data item processed. Because at that time we can get all of the
    // "morph from" and make correct separate/combine.
800

801 802 803 804 805 806
    !isMorphTo && prepareShapeOrExtraTransitionFrom('shape', el, null, elOption, transFromProps, isInit);
    prepareShapeOrExtraAllPropsFinal('shape', elOption, allPropsFinal);
    !isMorphTo && prepareShapeOrExtraTransitionFrom('extra', el, null, elOption, transFromProps, isInit);
    prepareShapeOrExtraAllPropsFinal('extra', elOption, allPropsFinal);
    !isMorphTo && prepareTransformTransitionFrom(el, null, elOption, transFromProps, isInit);
    prepareTransformAllPropsFinal(elOption, allPropsFinal);
1
100pah 已提交
807 808 809 810 811 812

    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 已提交
813 814
    }

1
100pah 已提交
815 816 817
    if (el.type === 'text' && styleOpt) {
        const textOptionStyle = styleOpt as TextStyleProps;
        // Compatible with ec4: if `textFill` or `textStroke` exists use them.
818
        hasOwn(textOptionStyle, 'textFill') && (
1
100pah 已提交
819
            textOptionStyle.fill = (textOptionStyle as any).textFill
S
sushuang 已提交
820
        );
821
        hasOwn(textOptionStyle, 'textStroke') && (
1
100pah 已提交
822
            textOptionStyle.stroke = (textOptionStyle as any).textStroke
S
sushuang 已提交
823 824
        );
    }
P
pah100 已提交
825

826 827 828 829 830 831 832 833 834
    !isMorphTo && prepareStyleTransitionFrom(el, null, elOption, styleOpt, transFromProps, isInit);

    if (elDisplayable) {
        hasOwn(elOption, 'invisible') && (elDisplayable.invisible = elOption.invisible);
    }

    // If `isMorphTo`, we should not update these props to el directly, otherwise,
    // when applying morph finally, the original prop are missing for making "animation from".
    if (!isMorphTo) {
835 836
        applyPropsFinal(el, allPropsFinal, styleOpt);
        applyTransitionFrom(el, dataIndex, elOption, seriesModel, transFromProps, isInit);
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
    }

    // Merge by default.
    hasOwn(elOption, 'silent') && (el.silent = elOption.silent);
    hasOwn(elOption, 'ignore') && (el.ignore = elOption.ignore);

    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.
        hasOwn(elOption, 'info') && (inner(el).info = elOption.info);
    }

    styleOpt ? el.dirty() : el.markRedraw();

    return isMorphTo ? allPropsFinal : null;
}

855
function applyPropsFinal(
856 857 858
    el: Element,
    // Can be null/undefined
    allPropsFinal: ElementProps,
859
    styleOpt: CustomElementOption['style']
860 861
) {
    const elDisplayable = el.isGroup ? null : el as Displayable;
862

863
    if (elDisplayable && styleOpt) {
1
100pah 已提交
864 865
        // PENDING: here the input style object is used directly.
        // Good for performance but bad for compatibility control.
866
        elDisplayable.useStyle(styleOpt);
P
pah100 已提交
867

868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
        // 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 已提交
889
        }
S
sushuang 已提交
890
    }
P
pah100 已提交
891

892 893
    // Set el to the final state firstly.
    allPropsFinal && el.attr(allPropsFinal);
894
}
P
pah100 已提交
895

896 897 898 899 900 901 902 903 904
function applyTransitionFrom(
    el: Element,
    dataIndex: number,
    elOption: CustomElementOption,
    seriesModel: CustomSeriesModel,
    // Can be null/undefined
    transFromProps: ElementProps,
    isInit: boolean
): void {
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
    if (transFromProps) {
        // 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;
        const cfg = {
            dataIndex: dataIndex,
            isFrom: true,
            during: cfgDuringCall
        };
        isInit
            ? graphicUtil.initProps(el, transFromProps, seriesModel, cfg)
            : graphicUtil.updateProps(el, transFromProps, seriesModel, cfg);
923
    }
1
100pah 已提交
924 925
}

926

927
// See [STRATEGY_TRANSITION]
928
function prepareShapeOrExtraTransitionFrom(
929
    mainAttr: 'shape' | 'extra',
930
    el: Element,
931
    morphFromEl: graphicUtil.Path,
932 933 934 935 936
    elOption: CustomElementOption,
    transFromProps: LooseElementProps,
    isInit: boolean
): void {

937 938
    const attrOpt: Dictionary<unknown> & TransitionAnyOption = (elOption as any)[mainAttr];
    if (!attrOpt) {
939 940 941
        return;
    }

942 943
    const elPropsInAttr = (el as LooseElementProps)[mainAttr];
    let transFromPropsInAttr: Dictionary<unknown>;
944

945
    const enterFrom = attrOpt.enterFrom;
946
    if (isInit && enterFrom) {
947
        !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
948 949
        const enterFromKeys = keys(enterFrom);
        for (let i = 0; i < enterFromKeys.length; i++) {
950 951
            // `enterFrom` props are not necessarily also declared in `shape`/`style`/...,
            // for example, `opacity` can only declared in `enterFrom` but not in `style`.
952 953
            const key = enterFromKeys[i];
            // Do not clone, animator will perform that clone.
954
            transFromPropsInAttr[key] = enterFrom[key];
955 956 957
        }
    }

958 959 960
    if (!isInit
        && elPropsInAttr
        // Just ignore shape animation in morphing.
961
        && !(morphFromEl != null && mainAttr === 'shape')
962
    ) {
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
        if (attrOpt.transition) {
            !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
            const transitionKeys = normalizeToArray(attrOpt.transition);
            for (let i = 0; i < transitionKeys.length; i++) {
                const key = transitionKeys[i];
                const elVal = elPropsInAttr[key];
                if (__DEV__) {
                    checkNonStyleTansitionRefer(key, (attrOpt as any)[key], elVal);
                }
                // Do not clone, see `checkNonStyleTansitionRefer`.
                transFromPropsInAttr[key] = elVal;
            }
        }
        else if (indexOf(elOption.transition, mainAttr) >= 0) {
            !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
            const elPropsInAttrKeys = keys(elPropsInAttr);
            for (let i = 0; i < elPropsInAttrKeys.length; i++) {
                const key = elPropsInAttrKeys[i];
                const elVal = elPropsInAttr[key];
                if (isNonStyleTransitionEnabled((attrOpt as any)[key], elVal)) {
                    transFromPropsInAttr[key] = elVal;
                }
985 986 987 988
            }
        }
    }

989
    const leaveTo = attrOpt.leaveTo;
990 991
    if (leaveTo) {
        const leaveToProps = getOrCreateLeaveToPropsFromEl(el);
992
        const leaveToPropsInAttr: Dictionary<unknown> = leaveToProps[mainAttr] || (leaveToProps[mainAttr] = {});
993 994 995
        const leaveToKeys = keys(leaveTo);
        for (let i = 0; i < leaveToKeys.length; i++) {
            const key = leaveToKeys[i];
996
            leaveToPropsInAttr[key] = leaveTo[key];
997 998 999 1000
        }
    }
}

1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
function prepareShapeOrExtraAllPropsFinal(
    mainAttr: 'shape' | 'extra',
    elOption: CustomElementOption,
    allProps: LooseElementProps
): void {
    const attrOpt: Dictionary<unknown> & TransitionAnyOption = (elOption as any)[mainAttr];
    if (!attrOpt) {
        return;
    }
    const allPropsInAttr = allProps[mainAttr] = {} as Dictionary<unknown>;
    const keysInAttr = keys(attrOpt);
    for (let i = 0; i < keysInAttr.length; i++) {
        const key = keysInAttr[i];
        // To avoid share one object with different element, and
        // to avoid user modify the object inexpectedly, have to clone.
        allPropsInAttr[key] = cloneValue((attrOpt as any)[key]);
    }
}

1020
// See [STRATEGY_TRANSITION].
1021
function prepareTransformTransitionFrom(
1022
    el: Element,
1023
    morphFromEl: graphicUtil.Path,
1024 1025 1026 1027
    elOption: CustomElementOption,
    transFromProps: ElementProps,
    isInit: boolean
): void {
1028
    const enterFrom = elOption.enterFrom;
1029 1030 1031
    if (isInit && enterFrom) {
        const enterFromKeys = keys(enterFrom);
        for (let i = 0; i < enterFromKeys.length; i++) {
1032
            const key = enterFromKeys[i] as TransformProp;
1033
            if (__DEV__) {
1034
                checkTransformPropRefer(key, 'el.enterFrom');
1035 1036 1037 1038 1039 1040 1041
            }
            // Do not clone, animator will perform that clone.
            transFromProps[key] = enterFrom[key] as number;
        }
    }

    if (!isInit) {
1042 1043 1044
        // If morphing, force transition all transform props.
        // otherwise might have incorrect morphing animation.
        if (morphFromEl) {
1045 1046 1047 1048 1049 1050 1051 1052
            const fromTransformable = calcOldElLocalTransformBasedOnNewElParent(morphFromEl, el);
            setTransformPropToTransitionFrom(transFromProps, 'x', fromTransformable);
            setTransformPropToTransitionFrom(transFromProps, 'y', fromTransformable);
            setTransformPropToTransitionFrom(transFromProps, 'scaleX', fromTransformable);
            setTransformPropToTransitionFrom(transFromProps, 'scaleY', fromTransformable);
            setTransformPropToTransitionFrom(transFromProps, 'originX', fromTransformable);
            setTransformPropToTransitionFrom(transFromProps, 'originY', fromTransformable);
            setTransformPropToTransitionFrom(transFromProps, 'rotation', fromTransformable);
1053 1054
        }
        else if (elOption.transition) {
1055
            const transitionKeys = normalizeToArray(elOption.transition);
1056 1057
            for (let i = 0; i < transitionKeys.length; i++) {
                const key = transitionKeys[i];
1058 1059 1060
                if (key === 'style' || key === 'shape' || key === 'extra') {
                    continue;
                }
1061
                const elVal = el[key];
1062
                if (__DEV__) {
1063
                    checkTransformPropRefer(key, 'el.transition');
1064
                    checkNonStyleTansitionRefer(key, elOption[key], elVal);
1065
                }
1066
                // Do not clone, see `checkNonStyleTansitionRefer`.
1067 1068 1069 1070 1071
                transFromProps[key] = elVal;
            }
        }
        // This default transition see [STRATEGY_TRANSITION]
        else {
1072 1073
            setTransformPropToTransitionFrom(transFromProps, 'x', el);
            setTransformPropToTransitionFrom(transFromProps, 'y', el);
1074 1075 1076
        }
    }

1077
    const leaveTo = elOption.leaveTo;
1078 1079 1080 1081
    if (leaveTo) {
        const leaveToProps = getOrCreateLeaveToPropsFromEl(el);
        const leaveToKeys = keys(leaveTo);
        for (let i = 0; i < leaveToKeys.length; i++) {
1082
            const key = leaveToKeys[i] as TransformProp;
1083
            if (__DEV__) {
1084
                checkTransformPropRefer(key, 'el.leaveTo');
1085 1086 1087 1088 1089 1090
            }
            leaveToProps[key] = leaveTo[key] as number;
        }
    }
}

1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
function prepareTransformAllPropsFinal(
    elOption: CustomElementOption,
    allProps: ElementProps
): void {
    setLagecyTransformProp(elOption, allProps, 'position');
    setLagecyTransformProp(elOption, allProps, 'scale');
    setLagecyTransformProp(elOption, allProps, 'origin');
    setTransformProp(elOption, allProps, 'x');
    setTransformProp(elOption, allProps, 'y');
    setTransformProp(elOption, allProps, 'scaleX');
    setTransformProp(elOption, allProps, 'scaleY');
    setTransformProp(elOption, allProps, 'originX');
    setTransformProp(elOption, allProps, 'originY');
    setTransformProp(elOption, allProps, 'rotation');
}

1107
// See [STRATEGY_TRANSITION].
1108
function prepareStyleTransitionFrom(
1109
    el: Element,
1110
    morphFromEl: graphicUtil.Path,
1111
    elOption: CustomElementOption,
1112 1113 1114 1115 1116 1117 1118 1119
    styleOpt: CustomElementOption['style'],
    transFromProps: LooseElementProps,
    isInit: boolean
): void {
    if (!styleOpt) {
        return;
    }

1120 1121
    // At present in "many-to-one"/"one-to-many" case, to not support "many" have
    // different styles and make style transitions. That might be a rare case.
1122
    const fromEl = morphFromEl || el;
1123 1124

    const fromElStyle = (fromEl as LooseElementProps).style as LooseElementProps['style'];
1125 1126
    let transFromStyleProps: LooseElementProps['style'];

1127
    const enterFrom = styleOpt.enterFrom;
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
    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];
        }
    }

1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
    if (!isInit && fromElStyle) {
        if (styleOpt.transition) {
            const transitionKeys = normalizeToArray(styleOpt.transition);
            !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
            for (let i = 0; i < transitionKeys.length; i++) {
                const key = transitionKeys[i];
                const elVal = (fromElStyle as any)[key];
                // Do not clone, see `checkNonStyleTansitionRefer`.
                (transFromStyleProps as any)[key] = elVal;
            }
        }
        else if (
            (el as Displayable).getAnimationStyleProps
            && indexOf(elOption.transition, 'style') >= 0
        ) {
            const animationProps = (el as Displayable).getAnimationStyleProps();
            const animationStyleProps = animationProps ? animationProps.style : null;
            if (animationStyleProps) {
                !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
                const styleKeys = keys(styleOpt);
                for (let i = 0; i < styleKeys.length; i++) {
                    const key = styleKeys[i];
                    if ((animationStyleProps as Dictionary<unknown>)[key]) {
                        const elVal = (fromElStyle as any)[key];
                        (transFromStyleProps as any)[key] = elVal;
                    }
                }
1165 1166 1167 1168
            }
        }
    }

1169
    const leaveTo = styleOpt.leaveTo;
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
    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];
        }
    }
}

1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
/**
 * If make "transform"(x/y/scaleX/scaleY/orient/originX/originY) transition between
 * two path elements that have different hierarchy, before we retrieve the "from" props,
 * we have to calculate the local transition of the "oldPath" based on the parent of
 * the "newPath".
 * At present, the case only happend in "morphing". Without morphing, the transform
 * transition are all between elements in the same hierarchy, where this kind of process
 * is not needed.
 *
 * [CAVEAT]:
 * This method makes sense only if: (very tricky)
 * (1) "newEl" has been added to its final parent.
 * (2) Local transform props of "newPath.parent" are not at their final value but already
 * have been at the "from value".
 *     This is currently ensured by:
 *     (2.1) "graphicUtil.animationFrom", which will set the element to the "from value"
 *     immediately.
 *     (2.2) "morph" option is not allowed to be set on Group, so all of the groups have
 *     been finished their "updateElNormal" when calling this method in morphing process.
 */
function calcOldElLocalTransformBasedOnNewElParent(oldEl: Element, newEl: Element): Transformable {
    if (!oldEl || oldEl === newEl || oldEl.parent === newEl.parent) {
        return oldEl;
    }

    // Not sure oldEl is rendered (may have "lazyUpdate"),
    // so always call `getComputedTransform`.
    const tmpM = tmpTransformable.transform
        || (tmpTransformable.transform = matrix.identity([]));

    const oldGlobalTransform = oldEl.getComputedTransform();
    oldGlobalTransform
        ? matrix.copy(tmpM, oldGlobalTransform)
        : matrix.identity(tmpM);

    const newParent = newEl.parent;
    if (newParent) {
        newParent.getComputedTransform();
    }

    tmpTransformable.originX = oldEl.originX;
    tmpTransformable.originY = oldEl.originY;
    tmpTransformable.parent = newParent;
    tmpTransformable.decomposeTransform();

    return tmpTransformable;
}

1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
let checkNonStyleTansitionRefer: (propName: string, optVal: unknown, elVal: unknown) => void;
if (__DEV__) {
    checkNonStyleTansitionRefer = function (propName: string, optVal: unknown, elVal: unknown): void {
        if (!isArrayLike(optVal)) {
            assert(
                optVal != null && isFinite(optVal as number),
                'Prop `' + propName + '` must refer to a finite number or ArrayLike for transition.'
            );
        }
        else {
            // 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(
                optVal !== elVal,
                'Prop `' + propName + '` must use different Array object each time for transition.'
            );
        }
    };
}
1248

1249 1250 1251 1252 1253
function isNonStyleTransitionEnabled(optVal: unknown, elVal: unknown): boolean {
    // The same as `checkNonStyleTansitionRefer`.
    return !isArrayLike(optVal)
        ? (optVal != null && isFinite(optVal as number))
        : optVal !== elVal;
1254 1255
}

1256 1257 1258 1259 1260 1261 1262 1263 1264
let checkTransformPropRefer: (key: string, usedIn: string) => void;
if (__DEV__) {
    checkTransformPropRefer = function (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.'
        );
    };
1265 1266 1267 1268 1269 1270 1271
}

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

1272 1273 1274 1275 1276 1277 1278 1279
// 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.
1280
    setTransform(key: TransformProp, val: unknown) {
1281 1282 1283
        if (__DEV__) {
            assert(hasOwn(TRANSFORM_PROPS, key), 'Only ' + transformPropNamesStr + ' available in `setTransform`.');
        }
1284
        tmpDuringScope.el[key] = val as number;
1285
        return this;
1286
    },
1287
    getTransform(key: TransformProp): unknown {
1288 1289 1290
        if (__DEV__) {
            assert(hasOwn(TRANSFORM_PROPS, key), 'Only ' + transformPropNamesStr + ' available in `getTransform`.');
        }
1291 1292
        return tmpDuringScope.el[key];
    },
1293
    setShape(key: string, val: unknown) {
1294 1295 1296 1297 1298
        if (__DEV__) {
            assertNotReserved(key);
        }
        const shape = (tmpDuringScope.el as graphicUtil.Path).shape
            || ((tmpDuringScope.el as graphicUtil.Path).shape = {});
1299 1300
        shape[key] = val;
        tmpDuringScope.isShapeDirty = true;
1301
        return this;
1302 1303
    },
    getShape(key: string): unknown {
1304 1305 1306 1307
        if (__DEV__) {
            assertNotReserved(key);
        }
        const shape = (tmpDuringScope.el as graphicUtil.Path).shape;
1308 1309 1310 1311
        if (shape) {
            return shape[key];
        }
    },
1312
    setStyle(key: string, val: unknown) {
1313 1314 1315
        if (__DEV__) {
            assertNotReserved(key);
        }
1316 1317
        const style = (tmpDuringScope.el as Displayable).style;
        if (style) {
1318 1319 1320 1321 1322
            if (__DEV__) {
                if (eqNaN(val)) {
                    warn('style.' + key + ' must not be assigned with NaN.');
                }
            }
1323 1324 1325
            style[key] = val;
            tmpDuringScope.isStyleDirty = true;
        }
1326
        return this;
1327 1328
    },
    getStyle(key: string): unknown {
1329 1330 1331
        if (__DEV__) {
            assertNotReserved(key);
        }
1332 1333 1334 1335
        const style = (tmpDuringScope.el as Displayable).style;
        if (style) {
            return style[key];
        }
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
    },
    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];
        }
1354 1355 1356
    }
};

1357 1358 1359 1360 1361 1362 1363 1364
function assertNotReserved(key: string) {
    if (__DEV__) {
        if (key === 'transition' || key === 'enterFrom' || key === 'leaveTo') {
            throw new Error('key must not be "' + key + '"');
        }
    }
}

1365 1366 1367 1368 1369 1370
function duringCall(
    this: {
        el: Element;
        userDuring: CustomBaseElementOption['during']
    }
): void {
1371 1372 1373 1374 1375
    // 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.
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
    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;
    }
1397

1398
    tmpDuringScope.el = el;
1399 1400 1401
    tmpDuringScope.isShapeDirty = false;
    tmpDuringScope.isStyleDirty = false;

1402 1403
    // Give no `this` to user in "during" calling.
    scopeUserDuring(customDuringAPI);
1404

1405 1406
    if (tmpDuringScope.isShapeDirty && (el as graphicUtil.Path).dirtyShape) {
        (el as graphicUtil.Path).dirtyShape();
1407
    }
1408 1409
    if (tmpDuringScope.isStyleDirty && (el as Displayable).dirtyStyle) {
        (el as Displayable).dirtyStyle();
1410 1411
    }
    // markRedraw() will be called by default in during.
1412
    // FIXME `this.markRedraw();` directly ?
1413 1414 1415

    // 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.
1416 1417
}

1
100pah 已提交
1418 1419 1420 1421
function updateElOnState(
    state: DisplayStateNonNormal,
    el: Element,
    elStateOpt: CustomElementOptionOnState,
1422
    styleOpt: CustomElementOptionOnState['style'],
1
100pah 已提交
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
    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.
1443
            stateObj.style = styleOpt || null;
1
100pah 已提交
1444 1445 1446 1447 1448 1449 1450 1451 1452
        }
        // 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;
        }

1453
        setDefaultStateProxy(elDisplayable);
S
sushuang 已提交
1454
    }
1
100pah 已提交
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
}

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);

1478 1479
    for (let i = 0; i < STATES.length; i++) {
        updateZForEachState(elDisplayable, elOption, STATES[i]);
1
100pah 已提交
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
    }
}

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 已提交
1497
}
P
pah100 已提交
1498

1499
function setLagecyTransformProp(
1
100pah 已提交
1500
    elOption: CustomElementOption,
1501
    targetProps: Partial<Pick<Transformable, TransformProp>>,
1502
    legacyName: LegacyTransformProp,
1503
    fromTransformable?: Transformable // If provided, retrieve from the element.
1
100pah 已提交
1504 1505
): void {
    const legacyArr = (elOption as any)[legacyName];
1506 1507
    const xyName = LEGACY_TRANSFORM_PROPS[legacyName];
    if (legacyArr) {
1508 1509 1510
        if (fromTransformable) {
            targetProps[xyName[0]] = fromTransformable[xyName[0]];
            targetProps[xyName[1]] = fromTransformable[xyName[1]];
1511 1512 1513 1514 1515 1516
        }
        else {
            targetProps[xyName[0]] = legacyArr[0];
            targetProps[xyName[1]] = legacyArr[1];
        }
    }
1
100pah 已提交
1517
}
1518

1519
function setTransformProp(
1
100pah 已提交
1520
    elOption: CustomElementOption,
1521
    allProps: Partial<Pick<Transformable, TransformProp>>,
1522
    name: TransformProp,
1523
    fromTransformable?: Transformable // If provided, retrieve from the element.
1
100pah 已提交
1524
): void {
1525
    if (elOption[name] != null) {
1526
        allProps[name] = fromTransformable ? fromTransformable[name] : elOption[name];
P
pah100 已提交
1527
    }
S
sushuang 已提交
1528 1529
}

1530 1531 1532
function setTransformPropToTransitionFrom(
    transitionFrom: Partial<Pick<Transformable, TransformProp>>,
    name: TransformProp,
1533
    fromTransformable?: Transformable // If provided, retrieve from the element.
1534
): void {
1535 1536
    if (fromTransformable) {
        transitionFrom[name] = fromTransformable[name];
1537 1538 1539 1540
    }
}


1
100pah 已提交
1541 1542 1543 1544 1545 1546
function makeRenderItem(
    customSeries: CustomSeriesModel,
    data: List<CustomSeriesModel>,
    ecModel: GlobalModel,
    api: ExtensionAPI
) {
1547 1548
    const renderItem = customSeries.get('renderItem');
    const coordSys = customSeries.coordinateSystem;
1
100pah 已提交
1549
    let prepareResult = {} as ReturnType<PrepareCustomInfo>;
S
sushuang 已提交
1550 1551 1552

    if (coordSys) {
        if (__DEV__) {
1553 1554
            assert(renderItem, 'series.render is required.');
            assert(
S
sushuang 已提交
1555 1556 1557
                coordSys.prepareCustoms || prepareCustoms[coordSys.type],
                'This coordSys does not support custom series.'
            );
P
pah100 已提交
1558 1559
        }

1
100pah 已提交
1560
        // `coordSys.prepareCustoms` is used for external coord sys like bmap.
S
sushuang 已提交
1561
        prepareResult = coordSys.prepareCustoms
1
100pah 已提交
1562
            ? coordSys.prepareCustoms(coordSys)
S
sushuang 已提交
1563 1564
            : prepareCustoms[coordSys.type](coordSys);
    }
P
pah100 已提交
1565

1566
    const userAPI = defaults({
S
sushuang 已提交
1567 1568 1569 1570 1571 1572
        getWidth: api.getWidth,
        getHeight: api.getHeight,
        getZr: api.getZr,
        getDevicePixelRatio: api.getDevicePixelRatio,
        value: value,
        style: style,
1573
        ordinalRawValue: ordinalRawValue,
S
sushuang 已提交
1574 1575 1576 1577 1578
        styleEmphasis: styleEmphasis,
        visual: visual,
        barLayout: barLayout,
        currentSeriesIndices: currentSeriesIndices,
        font: font
1
100pah 已提交
1579
    }, prepareResult.api || {}) as CustomSeriesRenderItemAPI;
S
sushuang 已提交
1580

1
100pah 已提交
1581
    const userParams: CustomSeriesRenderItemParams = {
S
tweak.  
sushuang 已提交
1582 1583 1584
        // 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 已提交
1585 1586 1587 1588 1589 1590 1591 1592
        context: {},
        seriesId: customSeries.id,
        seriesName: customSeries.name,
        seriesIndex: customSeries.seriesIndex,
        coordSys: prepareResult.coordSys,
        dataInsideLength: data.count(),
        encode: wrapEncodeDef(customSeries.getData())
    };
P
pah100 已提交
1593

1
100pah 已提交
1594 1595 1596 1597
    // 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 已提交
1598
    // Do not support call `api` asynchronously without dataIndexInside input.
1
100pah 已提交
1599
    let currDataIndexInside: number;
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
    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 已提交
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
        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 已提交
1641
        currDataIndexInside = dataIndexInside;
1
100pah 已提交
1642 1643 1644
        currItemModel = null;
        currItemStyleModels = {};
        currLabelModels = {};
1645

S
sushuang 已提交
1646
        return renderItem && renderItem(
1647
            defaults({
S
sushuang 已提交
1648
                dataIndexInside: dataIndexInside,
1649 1650 1651
                dataIndex: data.getRawIndex(dataIndexInside),
                // Can be used for optimization when zoom or roam.
                actionType: payload ? payload.type : null
S
sushuang 已提交
1652 1653
            }, userParams),
            userAPI
S
sushuang 已提交
1654
        );
S
sushuang 已提交
1655
    };
P
pah100 已提交
1656

S
sushuang 已提交
1657 1658
    /**
     * @public
1
100pah 已提交
1659 1660
     * @param dim by default 0.
     * @param dataIndexInside by default `currDataIndexInside`.
S
sushuang 已提交
1661
     */
1
100pah 已提交
1662
    function value(dim?: DimensionLoose, dataIndexInside?: number): ParsedValue {
S
sushuang 已提交
1663 1664 1665
        dataIndexInside == null && (dataIndexInside = currDataIndexInside);
        return data.get(data.getDimension(dim || 0), dataIndexInside);
    }
P
pah100 已提交
1666

1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
    /**
     * @public
     * @param dim by default 0.
     * @param dataIndexInside by default `currDataIndexInside`.
     */
    function ordinalRawValue(dim?: DimensionLoose, dataIndexInside?: number): ParsedValue | OrdinalRawValue {
        dataIndexInside == null && (dataIndexInside = currDataIndexInside);
        const dimInfo = data.getDimensionInfo(dim || 0);
        if (!dimInfo) {
            return;
        }
        const val = data.get(dimInfo.name, dataIndexInside);
        const ordinalMeta = dimInfo && dimInfo.ordinalMeta;
        return ordinalMeta
            ? ordinalMeta.categories[val as number]
            : val;
    }

S
sushuang 已提交
1685
    /**
1
100pah 已提交
1686 1687 1688 1689 1690
     * @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 已提交
1691 1692 1693 1694
     * 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 已提交
1695 1696 1697 1698 1699 1700
     *
     * [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 已提交
1701
     * @public
1
100pah 已提交
1702
     * @param dataIndexInside by default `currDataIndexInside`.
S
sushuang 已提交
1703
     */
1704
    function style(userProps?: ZRStyleProps, dataIndexInside?: number): ZRStyleProps {
1
100pah 已提交
1705 1706 1707 1708
        if (__DEV__) {
            warnDeprecated('api.style', 'Please write literal style directly instead.');
        }

S
sushuang 已提交
1709
        dataIndexInside == null && (dataIndexInside = currDataIndexInside);
P
pah100 已提交
1710

1
100pah 已提交
1711 1712 1713
        const style = data.getItemVisual(dataIndexInside, 'style');
        const visualColor = style && style.fill;
        const opacity = style && style.opacity;
P
pah100 已提交
1714

1
100pah 已提交
1715 1716
        let itemStyle = getItemStyleModel(dataIndexInside, NORMAL).getItemStyle();
        visualColor != null && (itemStyle.fill = visualColor);
S
sushuang 已提交
1717
        opacity != null && (itemStyle.opacity = opacity);
P
pah100 已提交
1718

1719
        const opt = {inheritColor: isString(visualColor) ? visualColor : '#000'};
1
100pah 已提交
1720 1721 1722 1723
        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`.
1724
        const textStyle = labelStyleHelper.createTextStyle(labelModel, null, opt, false, true);
1
100pah 已提交
1725
        textStyle.text = labelModel.getShallow('show')
1726
            ? retrieve2(
1
100pah 已提交
1727
                customSeries.getFormattedLabel(dataIndexInside, NORMAL),
S
sushuang 已提交
1728 1729 1730
                getDefaultLabel(data, dataIndexInside)
            )
            : null;
P
pissang 已提交
1731
        const textConfig = labelStyleHelper.createTextConfig(labelModel, opt, false);
1
100pah 已提交
1732

1733
        preFetchFromExtra(userProps, itemStyle);
1
100pah 已提交
1734
        itemStyle = convertToEC4StyleForCustomSerise(itemStyle, textStyle, textConfig);
P
pah100 已提交
1735

1736
        userProps && applyUserPropsAfter(itemStyle, userProps);
1
100pah 已提交
1737
        (itemStyle as LegacyStyleProps).legacy = true;
1738

S
sushuang 已提交
1739 1740
        return itemStyle;
    }
P
pah100 已提交
1741

S
sushuang 已提交
1742
    /**
1
100pah 已提交
1743
     * @deprecated The reason see `api.style()`
S
sushuang 已提交
1744
     * @public
1
100pah 已提交
1745
     * @param dataIndexInside by default `currDataIndexInside`.
S
sushuang 已提交
1746
     */
1747
    function styleEmphasis(userProps?: ZRStyleProps, dataIndexInside?: number): ZRStyleProps {
1
100pah 已提交
1748 1749 1750
        if (__DEV__) {
            warnDeprecated('api.styleEmphasis', 'Please write literal style directly instead.');
        }
1751

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

1
100pah 已提交
1754 1755
        let itemStyle = getItemStyleModel(dataIndexInside, EMPHASIS).getItemStyle();
        const labelModel = getLabelModel(dataIndexInside, EMPHASIS);
1756
        const textStyle = labelStyleHelper.createTextStyle(labelModel, null, null, true, true);
1
100pah 已提交
1757
        textStyle.text = labelModel.getShallow('show')
1758
            ? retrieve3(
1
100pah 已提交
1759 1760
                customSeries.getFormattedLabel(dataIndexInside, EMPHASIS),
                customSeries.getFormattedLabel(dataIndexInside, NORMAL),
S
sushuang 已提交
1761 1762 1763
                getDefaultLabel(data, dataIndexInside)
            )
            : null;
P
pissang 已提交
1764
        const textConfig = labelStyleHelper.createTextConfig(labelModel, null, true);
1
100pah 已提交
1765

1766
        preFetchFromExtra(userProps, itemStyle);
1
100pah 已提交
1767
        itemStyle = convertToEC4StyleForCustomSerise(itemStyle, textStyle, textConfig);
P
pah100 已提交
1768

1769
        userProps && applyUserPropsAfter(itemStyle, userProps);
1
100pah 已提交
1770
        (itemStyle as LegacyStyleProps).legacy = true;
1771

S
sushuang 已提交
1772
        return itemStyle;
P
pah100 已提交
1773 1774
    }

1775
    function applyUserPropsAfter(itemStyle: ZRStyleProps, extra: ZRStyleProps): void {
1776 1777 1778 1779 1780 1781 1782
        for (const key in extra) {
            if (hasOwn(extra, key)) {
                (itemStyle as any)[key] = (extra as any)[key];
            }
        }
    }

1
100pah 已提交
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
    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 已提交
1793 1794
    /**
     * @public
1
100pah 已提交
1795
     * @param dataIndexInside by default `currDataIndexInside`.
S
sushuang 已提交
1796
     */
1
100pah 已提交
1797 1798 1799 1800
    function visual(
        visualType: keyof DefaultDataVisual,
        dataIndexInside?: number
    ): ReturnType<List['getItemVisual']> {
S
sushuang 已提交
1801
        dataIndexInside == null && (dataIndexInside = currDataIndexInside);
1
100pah 已提交
1802

1803
        if (hasOwn(STYLE_VISUAL_TYPE, visualType)) {
1
100pah 已提交
1804 1805 1806 1807 1808 1809 1810
            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.
1811
        if (hasOwn(VISUAL_PROPS, visualType)) {
1
100pah 已提交
1812 1813
            return data.getItemVisual(dataIndexInside, visualType);
        }
P
pah100 已提交
1814 1815
    }

S
sushuang 已提交
1816 1817
    /**
     * @public
1
100pah 已提交
1818
     * @return If not support, return undefined.
S
sushuang 已提交
1819
     */
1
100pah 已提交
1820 1821 1822 1823 1824
    function barLayout(
        opt: Omit<Parameters<typeof getLayoutOnAxis>[0], 'axis'>
    ): ReturnType<typeof getLayoutOnAxis> {
        if (coordSys.type === 'cartesian2d') {
            const baseAxis = coordSys.getBaseAxis() as Axis2D;
1825
            return getLayoutOnAxis(defaults({axis: baseAxis}, opt));
1826
        }
P
pah100 已提交
1827 1828
    }

S
sushuang 已提交
1829 1830 1831
    /**
     * @public
     */
1
100pah 已提交
1832
    function currentSeriesIndices(): ReturnType<GlobalModel['getCurrentSeriesIndices']> {
S
sushuang 已提交
1833
        return ecModel.getCurrentSeriesIndices();
1834 1835
    }

S
sushuang 已提交
1836 1837
    /**
     * @public
1
100pah 已提交
1838
     * @return font string
S
sushuang 已提交
1839
     */
1
100pah 已提交
1840
    function font(
1841 1842
        opt: Parameters<typeof labelStyleHelper.getFont>[0]
    ): ReturnType<typeof labelStyleHelper.getFont> {
1843
        return labelStyleHelper.getFont(opt, ecModel);
S
sushuang 已提交
1844 1845 1846
    }
}

1
100pah 已提交
1847 1848
function wrapEncodeDef(data: List<CustomSeriesModel>): Dictionary<number[]> {
    const encodeDef = {} as Dictionary<number[]>;
1849
    each(data.dimensions, function (dimName, dataDimIndex) {
1850
        const dimInfo = data.getDimensionInfo(dimName);
S
sushuang 已提交
1851
        if (!dimInfo.isExtraCoord) {
1852 1853
            const coordDim = dimInfo.coordDim;
            const dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
S
sushuang 已提交
1854 1855 1856 1857 1858 1859
            dataDims[dimInfo.coordDimIndex] = dataDimIndex;
        }
    });
    return encodeDef;
}

1860
function createOrUpdateItem(
1
100pah 已提交
1861 1862 1863 1864 1865
    el: Element,
    dataIndex: number,
    elOption: CustomElementOption,
    seriesModel: CustomSeriesModel,
    group: ViewRootGroup,
1
100pah 已提交
1866
    data: List<CustomSeriesModel>,
1867
    morphPreparation: MorphPreparation
1
100pah 已提交
1868
): Element {
1869 1870 1871 1872 1873 1874 1875 1876 1877
    // [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) {
1
100pah 已提交
1878
        removeElementDirectly(el, group);
1879 1880
        return;
    }
1881
    el = doCreateOrUpdateEl(el, dataIndex, elOption, seriesModel, group, true, morphPreparation);
S
sushuang 已提交
1882
    el && data.setItemGraphicEl(dataIndex, el);
P
pissang 已提交
1883

1884 1885
    enableHoverEmphasis(el, elOption.focus, elOption.blurScope);

P
pissang 已提交
1886
    return el;
S
sushuang 已提交
1887 1888
}

1889
function doCreateOrUpdateEl(
1
100pah 已提交
1890 1891 1892 1893 1894
    el: Element,
    dataIndex: number,
    elOption: CustomElementOption,
    seriesModel: CustomSeriesModel,
    group: ViewRootGroup,
1
100pah 已提交
1895
    isRoot: boolean,
1896
    morphPreparation: MorphPreparation
1
100pah 已提交
1897
): Element {
1898

1899 1900
    if (__DEV__) {
        assert(elOption, 'should not have an null/undefined element setting');
1
100pah 已提交
1901
    }
S
sushuang 已提交
1902

1
100pah 已提交
1903 1904 1905 1906
    let toBeReplacedIdx = -1;
    if (
        el && (
            doesElNeedRecreate(el, elOption)
1907 1908 1909 1910 1911 1912
            // || (
            //     // PENDING: even in one-to-one mapping case, if el is marked as morph,
            //     // do not sure whether the el will be mapped to another el with different
            //     // hierarchy in Group tree. So always recreate el rather than reuse the el.
            //     morphPreparation && morphPreparation.isOneToOneFrom(el)
            // )
1
100pah 已提交
1913 1914 1915 1916 1917
        )
    ) {
        // Should keep at the original index, otherwise "merge by index" will be incorrect.
        toBeReplacedIdx = group.childrenRef().indexOf(el);
        el = null;
1918 1919
    }

1
100pah 已提交
1920
    const elIsNewCreated = !el;
1
100pah 已提交
1921 1922 1923 1924 1925

    if (!el) {
        el = createEl(elOption);
    }
    else {
1926
        // FIMXE:NEXT unified clearState?
1
100pah 已提交
1927 1928 1929
        // If in some case the performance issue arised, consider
        // do not clearState but update cached normal state directly.
        el.clearStates();
1930 1931
    }

1932 1933
    const canMorph = inner(el).canMorph = (elOption as CustomZRPathOption).morph && isPath(el);
    const thisElIsMorphTo = canMorph && morphPreparation && morphPreparation.hasFrom();
1934

1
100pah 已提交
1935
    // Use update animation when morph is enabled.
1936
    const isInit = elIsNewCreated && !thisElIsMorphTo;
1
100pah 已提交
1937

1
100pah 已提交
1938
    attachedTxInfoTmp.normal.cfg = attachedTxInfoTmp.normal.conOpt =
1939 1940 1941 1942
        attachedTxInfoTmp.emphasis.cfg = attachedTxInfoTmp.emphasis.conOpt =
        attachedTxInfoTmp.blur.cfg = attachedTxInfoTmp.blur.conOpt =
        attachedTxInfoTmp.select.cfg = attachedTxInfoTmp.select.conOpt = null;

1
100pah 已提交
1943 1944 1945 1946 1947 1948
    attachedTxInfoTmp.isLegacy = false;

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

1949 1950 1951 1952
    doCreateOrUpdateClipPath(
        el, dataIndex, elOption, seriesModel, isInit
    );

1953
    const pendingAllPropsFinal = updateElNormal(
1954
        el,
1955
        thisElIsMorphTo,
1956 1957 1958 1959 1960 1961 1962 1963
        dataIndex,
        elOption,
        elOption.style,
        attachedTxInfoTmp,
        seriesModel,
        isInit,
        false
    );
1964

1965 1966 1967 1968
    if (thisElIsMorphTo) {
        morphPreparation.addTo(el as graphicUtil.Path, elOption, dataIndex, pendingAllPropsFinal);
    }

1969 1970 1971 1972 1973 1974 1975 1976
    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 已提交
1977 1978

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

1980
    if (elOption.type === 'group') {
1
100pah 已提交
1981 1982 1983
        mergeChildren(
            el as graphicUtil.Group, dataIndex, elOption as CustomGroupOption, seriesModel, morphPreparation
        );
1984 1985
    }

1986 1987 1988 1989 1990 1991
    if (toBeReplacedIdx >= 0) {
        group.replaceAt(el, toBeReplacedIdx);
    }
    else {
        group.add(el);
    }
S
sushuang 已提交
1992 1993 1994 1995

    return el;
}

1996 1997 1998
// `el` must not be null/undefined.
function doesElNeedRecreate(el: Element, elOption: CustomElementOption): boolean {
    const elInner = inner(el);
1999
    const elOptionType = elOption.type;
2000
    const elOptionShape = (elOption as CustomZRPathOption).shape;
2001
    const elOptionStyle = elOption.style;
2002
    return (
S
sushuang 已提交
2003
        // If `elOptionType` is `null`, follow the merge principle.
2004 2005
        (elOptionType != null
            && elOptionType !== elInner.customGraphicType
S
sushuang 已提交
2006 2007
        )
        || (elOptionType === 'path'
2008 2009
            && hasOwnPathData(elOptionShape)
            && getPathData(elOptionShape) !== elInner.customPathData
S
sushuang 已提交
2010 2011
        )
        || (elOptionType === 'image'
2012
            && hasOwn(elOptionStyle, 'image')
2013
            && (elOptionStyle as CustomImageOption['style']).image !== elInner.customImagePath
S
sushuang 已提交
2014
        )
2015 2016
        // // FIXME test and remove this restriction?
        // || (elOptionType === 'text'
2017
        //     && hasOwn(elOptionStyle, 'text')
2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
        //     && (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();
        }
2038
    }
2039 2040 2041 2042 2043 2044 2045 2046
    else if (clipPathOpt) {
        let clipPath = el.getClipPath();
        if (clipPath && doesElNeedRecreate(clipPath, clipPathOpt)) {
            clipPath = null;
        }
        if (!clipPath) {
            clipPath = createEl(clipPathOpt) as graphicUtil.Path;
            if (__DEV__) {
2047
                assert(
2048 2049 2050 2051 2052 2053 2054
                    clipPath instanceof graphicUtil.Path,
                    'Only any type of `path` can be used in `clipPath`, rather than ' + clipPath.type + '.'
                );
            }
            el.setClipPath(clipPath);
        }
        updateElNormal(
2055
            clipPath, null, dataIndex, clipPathOpt, null, null, seriesModel, isInit, false
2056 2057 2058 2059
        );
    }
    // If not define `clipPath` in option, do nothing unnecessary.
}
2060

1
100pah 已提交
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
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 已提交
2071
        return;
2072 2073
    }

1
100pah 已提交
2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
    // 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;
2086 2087
    const txConOptBlur = attachedTxInfo.blur.conOpt as CustomElementOptionOnState;
    const txConOptSelect = attachedTxInfo.select.conOpt as CustomElementOptionOnState;
1
100pah 已提交
2088

2089
    if (txConOptNormal != null || txConOptEmphasis != null || txConOptSelect != null || txConOptBlur != null) {
1
100pah 已提交
2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107
        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(
2108
                textContent, null, dataIndex, txConOptNormal, txConStlOptNormal, null, seriesModel, isInit, true
1
100pah 已提交
2109
            );
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
            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 已提交
2123

2124
            txConStlOptNormal ? textContent.dirty() : textContent.markRedraw();
1
100pah 已提交
2125
        }
2126
    }
1
100pah 已提交
2127
}
2128

1
100pah 已提交
2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
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 已提交
2161

1
100pah 已提交
2162 2163 2164 2165 2166 2167
    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.
2168
            txConOptNormal.type !== 'text' && assert(
1
100pah 已提交
2169 2170 2171 2172 2173 2174 2175 2176 2177
                txConOptNormal.type === 'text',
                'textContent.type must be "text"'
            );
        }
    }

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

1
100pah 已提交
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
function retrieveStateOption(
    elOption: CustomElementOption, state: DisplayStateNonNormal
): CustomElementOptionOnState {
    return !state ? elOption : elOption ? elOption[state] : null;
}

function retrieveStyleOptionOnState(
    stateOptionNormal: CustomElementOption,
    stateOption: CustomElementOptionOnState,
    state: DisplayStateNonNormal
2190
): CustomElementOptionOnState['style'] {
1
100pah 已提交
2191 2192 2193 2194 2195 2196 2197 2198
    let style = stateOption && stateOption.style;
    if (style == null && state === EMPHASIS && stateOptionNormal) {
        style = stateOptionNormal.styleEmphasis;
    }
    return style;
}


2199 2200 2201 2202 2203 2204 2205 2206 2207 2208
// 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 已提交
2209 2210
// (4) If `!elOption.children`, following the "merge" principle, nothing will happen.
//
2211 2212
// 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).
2213
// User can remove a single child by set its `ignore` as `true`.
1
100pah 已提交
2214 2215 2216 2217
function mergeChildren(
    el: graphicUtil.Group,
    dataIndex: number,
    elOption: CustomGroupOption,
1
100pah 已提交
2218 2219
    seriesModel: CustomSeriesModel,
    morphPreparation: MorphPreparation
1
100pah 已提交
2220 2221
): void {

2222 2223 2224
    const newChildren = elOption.children;
    const newLen = newChildren ? newChildren.length : 0;
    const mergeChildren = elOption.$mergeChildren;
2225
    // `diffChildrenByName` has been deprecated.
2226 2227
    const byName = mergeChildren === 'byName' || elOption.diffChildrenByName;
    const notMerge = mergeChildren === false;
2228 2229

    // For better performance on roam update, only enter if necessary.
S
tweak.  
sushuang 已提交
2230
    if (!newLen && !byName && !notMerge) {
2231 2232 2233 2234 2235 2236 2237 2238
        return;
    }

    if (byName) {
        diffGroupChildren({
            oldChildren: el.children() || [],
            newChildren: newChildren || [],
            dataIndex: dataIndex,
1
100pah 已提交
2239
            seriesModel: seriesModel,
1
100pah 已提交
2240 2241
            group: el,
            morphPreparation: morphPreparation
2242 2243 2244 2245 2246 2247 2248 2249
        });
        return;
    }

    notMerge && el.removeAll();

    // Mapping children of a group simply by index, which
    // might be better performance.
2250
    let index = 0;
2251
    for (; index < newLen; index++) {
2252
        newChildren[index] && doCreateOrUpdateEl(
2253 2254 2255
            el.childAt(index),
            dataIndex,
            newChildren[index],
1
100pah 已提交
2256
            seriesModel,
2257
            el,
1
100pah 已提交
2258
            false,
1
100pah 已提交
2259
            morphPreparation
2260 2261
        );
    }
2262
    for (let i = el.childCount() - 1; i >= index; i--) {
2263 2264 2265
        // 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.
2266
        doRemoveEl(el.childAt(i), seriesModel, el);
2267 2268 2269
    }
}

1
100pah 已提交
2270 2271 2272 2273 2274
type DiffGroupContext = {
    oldChildren: Element[],
    newChildren: CustomElementOption[],
    dataIndex: number,
    seriesModel: CustomSeriesModel,
1
100pah 已提交
2275 2276
    group: graphicUtil.Group,
    morphPreparation: MorphPreparation
1
100pah 已提交
2277 2278
};
function diffGroupChildren(context: DiffGroupContext) {
S
sushuang 已提交
2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291
    (new DataDiffer(
        context.oldChildren,
        context.newChildren,
        getKey,
        getKey,
        context
    ))
        .add(processAddUpdate)
        .update(processAddUpdate)
        .remove(processRemove)
        .execute();
}

1
100pah 已提交
2292
function getKey(item: Element, idx: number): string {
2293
    const name = item && item.name;
S
sushuang 已提交
2294 2295 2296
    return name != null ? name : GROUP_DIFF_PREFIX + idx;
}

1
100pah 已提交
2297 2298 2299 2300 2301
function processAddUpdate(
    this: DataDiffer<DiffGroupContext>,
    newIndex: number,
    oldIndex?: number
): void {
2302 2303 2304
    const context = this.context;
    const childOption = newIndex != null ? context.newChildren[newIndex] : null;
    const child = oldIndex != null ? context.oldChildren[oldIndex] : null;
S
sushuang 已提交
2305

2306
    doCreateOrUpdateEl(
S
sushuang 已提交
2307 2308 2309
        child,
        context.dataIndex,
        childOption,
1
100pah 已提交
2310
        context.seriesModel,
S
sushuang 已提交
2311
        context.group,
1
100pah 已提交
2312
        false,
1
100pah 已提交
2313
        context.morphPreparation
S
sushuang 已提交
2314 2315 2316
    );
}

1
100pah 已提交
2317
function processRemove(this: DataDiffer<DiffGroupContext>, oldIndex: number): void {
2318 2319
    const context = this.context;
    const child = context.oldChildren[oldIndex];
2320
    doRemoveEl(child, context.seriesModel, context.group);
2321 2322
}

2323
function doRemoveEl(
2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
    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);
2337 2338 2339
    }
}

1
100pah 已提交
2340 2341 2342 2343
/**
 * @return SVG Path data.
 */
function getPathData(shape: CustomSVGPathOption['shape']): string {
S
sushuang 已提交
2344 2345 2346 2347
    // "d" follows the SVG convention.
    return shape && (shape.pathData || shape.d);
}

1
100pah 已提交
2348
function hasOwnPathData(shape: CustomSVGPathOption['shape']): boolean {
2349
    return shape && (hasOwn(shape, 'pathData') || hasOwn(shape, 'd'));
S
sushuang 已提交
2350 2351
}

2352
function isPath(el: Element): el is graphicUtil.Path {
1
100pah 已提交
2353 2354 2355 2356 2357 2358
    return el && el instanceof graphicUtil.Path;
}

function removeElementDirectly(el: Element, group: ViewRootGroup): void {
    el && group.remove(el);
}
2359 2360


2361 2362 2363 2364 2365 2366 2367 2368
type MorphPreparationType = 'oneToOne' | 'oneToMany' | 'manyToOne';

/**
 * Any morph-potential el should added by `morphPreparation.addTo(el)`.
 * And they may apply morph or not when `morphPreparation.applyMorphing()`.
 * But at least, all of the "to" elements will apply all of the updates
 * as `doCreateOrUpdateItem` did.
 */
2369
class MorphPreparation {
2370
    private _type: MorphPreparationType;
2371 2372 2373 2374 2375
    private _fromList: graphicUtil.Path[] = [];
    private _toList: graphicUtil.Path[] = [];
    private _toElOptionList: CustomElementOption[] = [];
    private _allPropsFinalList: ElementProps[] = [];
    private _toDataIndices: number[] = [];
2376 2377 2378 2379
    private _transOpt: SeriesModel['__transientTransitionOpt'];
    private _seriesModel: CustomSeriesModel;
    // Key: `toDataIndex`, not `toIdx`
    private _morphConfigList: CombineSeparateConfig[] = [];
2380

2381 2382 2383 2384 2385 2386
    constructor(
        seriesModel: CustomSeriesModel,
        transOpt: SeriesModel['__transientTransitionOpt']
    ) {
        this._seriesModel = seriesModel;
        this._transOpt = transOpt;
2387
    }
2388

2389 2390
    hasFrom(): boolean {
        return !!this._fromList.length;
2391
    }
2392

2393 2394 2395 2396 2397 2398 2399 2400 2401 2402
    // isOneToOneFrom(el: Element): boolean {
    //     if (el && inner(el).canMorph) {
    //         const fromList = this._fromList;
    //         for (let i = 0; i < fromList.length; i++) {
    //             if (fromList[i] === el) {
    //                 return true;
    //             }
    //         }
    //     }
    // }
2403

2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414
    findAndAddFrom(el: Element): void {
        if (!el) {
            return;
        }
        if (inner(el).canMorph) {
            this._fromList.push(el as graphicUtil.Path);
        }
        if (el.isGroup) {
            const children = (el as graphicUtil.Group).childrenRef();
            for (let i = 0; i < children.length; i++) {
                this.findAndAddFrom(children[i]);
1
100pah 已提交
2415
            }
2416 2417
        }
    }
2418

2419 2420 2421 2422 2423 2424
    addTo(
        path: graphicUtil.Path,
        elOption: CustomElementOption,
        dataIndex: number,
        allPropsFinal: ElementProps
    ): void {
2425
        if (path) {
2426 2427 2428 2429 2430 2431
            this._toList.push(path);
            this._toElOptionList.push(elOption);
            this._toDataIndices.push(dataIndex);
            this._allPropsFinalList.push(allPropsFinal);
        }
    }
2432

2433
    applyMorphing(): void {
2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456
        // [MORPHING_LOGIC_HINT]
        // Pay attention to the order:
        // (A) Apply `allPropsFinal` and `styleOption` to "to".
        //     (Then "to" becomes to the final state.)
        // (B) Apply `morphPath`/`combine`/`separate`.
        //     (Based on the current state of "from" and the final state of "to".)
        //     (Then we may get "from.subList" or "to.subList".)
        // (C) Copy the related props from "from" to "from.subList", from "to" to "to.subList".
        // (D) Collect `transitionFromProps` for "to" and "to.subList"
        //     (Based on "from" or "from.subList".)
        // (E) Apply `transitionFromProps` to "to" and "to.subList"
        //     (It might change the prop values to the first frame value.)
        // Case_I:
        //     If (D) should be after (C), we use sequence: A - B - C - D - E
        // Case_II:
        //     If (A) should be after (D), we use sequence: D - A - B - C - E

        // [MORPHING_LOGIC_HINT]
        // zrender `morphPath`/`combine`/`separate` only manages the shape animation.
        // Other props (like transfrom, style transition) will handled in echarts).

        // [MORPHING_LOGIC_HINT]
        // Make sure `applyPropsFinal` always be called for "to".
2457

2458 2459 2460 2461 2462
        const type = this._type;
        const fromList = this._fromList;
        const toList = this._toList;
        const toListLen = toList.length;
        const fromListLen = fromList.length;
2463

2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474
        if (!fromListLen || !toListLen) {
            return;
        }

        if (type === 'oneToOne') {
            // In one-to-one case, we by default apply a simple rule:
            // map "from" and "to" one by one.
            // For this case: old_data_item_el and new_data_item_el
            // has the same hierarchy of group tree but only some path type changed.
            for (let toIdx = 0; toIdx < toListLen; toIdx++) {
                this._oneToOneForSingleTo(toIdx, toIdx);
2475 2476
            }
        }
2477

2478
        else if (type === 'manyToOne') {
2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490
            // A rough strategy: if there are more than one "to", we simply divide "fromList" equally.
            const fromSingleSegLen = Math.max(1, Math.floor(fromListLen / toListLen));
            for (
                let toIdx = 0, fromIdxStart = 0;
                toIdx < toListLen;
                toIdx++, fromIdxStart += fromSingleSegLen
            ) {
                const fromCount = toIdx + 1 >= toListLen
                    ? fromListLen - fromIdxStart
                    : fromSingleSegLen;
                this._manyToOneForSingleTo(
                    toIdx, fromIdxStart >= fromListLen ? null : fromIdxStart, fromCount
2491 2492
                );
            }
2493
        }
2494

2495
        else if (type === 'oneToMany') {
2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508
            // A rough strategy: if there are more than one "from", we simply divide "toList" equally.
            const toSingleSegLen = Math.max(1, Math.floor(toListLen / fromListLen));
            for (
                let toIdxStart = 0, fromIdx = 0;
                toIdxStart < toListLen;
                toIdxStart += toSingleSegLen, fromIdx++
            ) {
                const toCount = toIdxStart + toSingleSegLen >= toListLen
                    ? toListLen - toIdxStart
                    : toSingleSegLen;
                this._oneToManyForSingleFrom(
                    toIdxStart, toCount, fromIdx >= fromListLen ? null : fromIdx
                );
2509
            }
2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530
        }
    }

    private _oneToOneForSingleTo(
        // "to" must NOT be null/undefined.
        toIdx: number,
        // May `fromIdx >= this._fromList.length`
        fromIdx: number
    ): void {
        const to = this._toList[toIdx];
        const toElOption = this._toElOptionList[toIdx];
        const toDataIndex = this._toDataIndices[toIdx];
        const allPropsFinal = this._allPropsFinalList[toIdx];
        const from = this._fromList[fromIdx];

        const elAnimationConfig = this._getOrCreateMorphConfig(toDataIndex);
        const morphDuration = elAnimationConfig.duration;

        if (from && isCombiningPath(from)) {
            applyPropsFinal(to, allPropsFinal, toElOption.style);

1
100pah 已提交
2531
            if (morphDuration) {
2532 2533
                const combineResult = combine([from], to, elAnimationConfig, copyPropsWhenDivided);
                this._processResultIndividuals(combineResult, toIdx, null);
2534
            }
2535 2536
            // The target el will not be displayed and transition from multiple path.
            // transition on the target el does not make sense.
2537
        }
2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555
        else {
            const morphFrom = (
                morphDuration
                // from === to usually happen in scenarios where internal update like
                // "dataZoom", "legendToggle" happen. If from is not in any morphing,
                // we do not need to call `morphPath`.
                && from
                && (from !== to || isInAnyMorphing(from))
            ) ? from : null;

            // See [Case_II] above.
            // In this case, there is probably `from === to`. And the `transitionFromProps` collecting
            // does not depends on morphing. So we collect `transitionFromProps` first.
            const transFromProps = {} as ElementProps;
            prepareShapeOrExtraTransitionFrom('shape', to, morphFrom, toElOption, transFromProps, false);
            prepareShapeOrExtraTransitionFrom('extra', to, morphFrom, toElOption, transFromProps, false);
            prepareTransformTransitionFrom(to, morphFrom, toElOption, transFromProps, false);
            prepareStyleTransitionFrom(to, morphFrom, toElOption, toElOption.style, transFromProps, false);
2556

2557
            applyPropsFinal(to, allPropsFinal, toElOption.style);
2558

2559 2560 2561 2562 2563
            if (morphFrom) {
                morphPath(morphFrom, to, elAnimationConfig);
            }
            applyTransitionFrom(to, toDataIndex, toElOption, this._seriesModel, transFromProps, false);
        }
2564 2565
    }

2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587
    private _manyToOneForSingleTo(
        // "to" must NOT be null/undefined.
        toIdx: number,
        // May be null.
        fromIdxStart: number,
        fromCount: number
    ): void {
        const to = this._toList[toIdx];
        const toElOption = this._toElOptionList[toIdx];
        const allPropsFinal = this._allPropsFinalList[toIdx];

        applyPropsFinal(to, allPropsFinal, toElOption.style);

        const elAnimationConfig = this._getOrCreateMorphConfig(this._toDataIndices[toIdx]);
        if (elAnimationConfig.duration && fromIdxStart != null) {
            const combineFromList = [];
            for (let fromIdx = fromIdxStart; fromIdx < fromCount; fromIdx++) {
                combineFromList.push(this._fromList[fromIdx]);
            }
            const combineResult = combine(combineFromList, to, elAnimationConfig, copyPropsWhenDivided);
            this._processResultIndividuals(combineResult, toIdx, null);
        }
2588 2589
    }

2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611
    private _oneToManyForSingleFrom(
        // "to" must NOT be null/undefined.
        toIdxStart: number,
        toCount: number,
        // May be null
        fromIdx: number
    ): void {
        const from = fromIdx == null ? null : this._fromList[fromIdx];
        const toList = this._toList;

        const separateToList = [];
        for (let toIdx = toIdxStart; toIdx < toCount; toIdx++) {
            const to = toList[toIdx];
            applyPropsFinal(to, this._allPropsFinalList[toIdx], this._toElOptionList[toIdx].style);
            separateToList.push(to);
        }

        const elAnimationConfig = this._getOrCreateMorphConfig(this._toDataIndices[toIdxStart]);
        if (elAnimationConfig.duration && from) {
            const separateResult = separate(from, separateToList, elAnimationConfig, copyPropsWhenDivided);
            this._processResultIndividuals(separateResult, toIdxStart, toCount);
        }
2612
    }
2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642

    private _processResultIndividuals(
        combineSeparateResult: CombineSeparateResult,
        toIdxStart: number,
        toCount: number
    ): void {
        const isSeparate = toCount != null;

        for (let i = 0; i < combineSeparateResult.count; i++) {
            const fromIndividual = combineSeparateResult.fromIndividuals[i];
            const toIndividual = combineSeparateResult.toIndividuals[i];
            // Here it's a trick:
            // For "combine" case, all of the `toIndividuals` map to the same `toIdx`.
            // For "separate" case, the `toIndividuals` map to some certain segment of `_toList` accurately.
            const toIdx = toIdxStart + (isSeparate ? i : 0);

            const toElOption = this._toElOptionList[toIdx];
            const dataIndex = this._toDataIndices[toIdx];

            const transFromProps = {} as ElementProps;
            prepareTransformTransitionFrom(
                toIndividual, fromIndividual, toElOption, transFromProps, false
            );
            prepareStyleTransitionFrom(
                toIndividual, fromIndividual, toElOption, toElOption.style, transFromProps, false
            );
            applyTransitionFrom(
                toIndividual, dataIndex, toElOption, this._seriesModel, transFromProps, false
            );
        }
2643
    }
2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675

    _getOrCreateMorphConfig(dataIndex: number): CombineSeparateConfig {
        const morphConfigList = this._morphConfigList;
        let config = morphConfigList[dataIndex];
        if (config) {
            return config;
        }

        let duration: number;
        let easing: AnimationEasing;
        let delay: number;
        const seriesModel = this._seriesModel;
        const transOpt = this._transOpt;

        if (seriesModel.isAnimationEnabled()) {
            // PENDING: refactor? this is the same logic as `src/util/graphic.ts#animateOrSetProps`.
            let animationPayload: PayloadAnimationPart;
            if (seriesModel && seriesModel.ecModel) {
                const updatePayload = seriesModel.ecModel.getUpdatePayload();
                animationPayload = (updatePayload && updatePayload.animation) as PayloadAnimationPart;
            }
            if (animationPayload) {
                duration = animationPayload.duration || 0;
                easing = animationPayload.easing || 'cubicOut';
                delay = animationPayload.delay || 0;
            }
            else {
                easing = seriesModel.get('animationEasingUpdate');
                const delayOption = seriesModel.get('animationDelayUpdate');
                delay = isFunction(delayOption) ? delayOption(dataIndex) : delayOption;
                const durationOption = seriesModel.get('animationDurationUpdate');
                duration = isFunction(durationOption) ? durationOption(dataIndex) : durationOption;
2676 2677
            }
        }
2678 2679 2680 2681 2682 2683 2684 2685 2686 2687

        config = {
            duration: duration || 0,
            delay: delay,
            easing: easing,
            dividingMethod: transOpt ? transOpt.dividingMethod : null
        };
        morphConfigList[dataIndex] = config;

        return config;
2688 2689
    }

2690 2691 2692 2693 2694 2695 2696 2697
    reset(type: MorphPreparationType): void {
        // `this._morphConfigList` can be kept. It only related to `dataIndex`.
        this._type = type;
        this._fromList.length =
            this._toList.length =
            this._toElOptionList.length =
            this._allPropsFinalList.length =
            this._toDataIndices.length = 0;
2698 2699
    }
}
2700 2701 2702 2703 2704 2705

function copyPropsWhenDivided(
    srcPath: graphicUtil.Path,
    tarPath: graphicUtil.Path,
    willClone: boolean
): void {
2706 2707 2708 2709 2710 2711 2712 2713
    // Do not copy transform props.
    // Sub paths are transfrom based on their host path.
    // tarPath.x = srcPath.x;
    // tarPath.y = srcPath.y;
    // tarPath.scaleX = srcPath.scaleX;
    // tarPath.scaleY = srcPath.scaleY;
    // tarPath.originX = srcPath.originX;
    // tarPath.originY = srcPath.originY;
2714 2715 2716 2717 2718 2719 2720 2721 2722 2723

    // If just carry the style, will not be modifed, so do not copy.
    tarPath.style = willClone
        ? clone(srcPath.style)
        : srcPath.style;

    tarPath.zlevel = srcPath.zlevel;
    tarPath.z = srcPath.z;
    tarPath.z2 = srcPath.z2;
}