states.ts 23.3 KB
Newer Older
1 2 3 4 5 6 7
import { Dictionary } from 'zrender/src/core/types';
import LRU from 'zrender/src/core/LRU';
import Displayable, { DisplayableState } from 'zrender/src/graphic/Displayable';
import { PatternObject } from 'zrender/src/graphic/Pattern';
import { GradientObject } from 'zrender/src/graphic/Gradient';
import Element, { ElementEvent } from 'zrender/src/Element';
import Model from '../model/Model';
8
import { DisplayState, ECElement, ColorString, BlurScope, InnerFocus, Payload, ZRColor, HighlightPayload, DownplayPayload } from './types';
9
import { extend, indexOf, isArrayLike, isObject, keys, isArray, each } from 'zrender/src/core/util';
10
import { getECData } from './graphic';
11
import * as colorTool from 'zrender/src/tool/color';
12
import { EChartsType } from '../echarts';
13
import List from '../data/List';
14 15
import SeriesModel from '../model/Series';
import { CoordinateSystemMaster, CoordinateSystem } from '../coord/CoordinateSystem';
16
import { queryDataIndex, makeInner } from './model';
17
import Path, { PathStyleProps } from 'zrender/src/graphic/Path';
P
pissang 已提交
18
import GlobalModel from '../model/Global';
19 20

// Reserve 0 as default.
21 22 23
let _highlightNextDigit = 1;

const _highlightKeyMap: Dictionary<number> = {};
24

25 26 27 28 29 30 31
const getSavedStates = makeInner<{
    normalFill: ZRColor
    normalStroke: ZRColor
    selectFill?: ZRColor
    selectStroke?: ZRColor
}, Path>();

32 33 34 35
export const HOVER_STATE_NORMAL: 0 = 0;
export const HOVER_STATE_BLUR: 1 = 1;
export const HOVER_STATE_EMPHASIS: 2 = 2;

P
pissang 已提交
36 37 38
export const SPECIAL_STATES = ['emphasis', 'blur', 'select'] as const;
export const DISPLAY_STATES = ['normal', 'emphasis', 'blur', 'select'] as const;

39 40 41
export const Z2_EMPHASIS_LIFT = 10;
export const Z2_SELECT_LIFT = 9;

42
export const HIGHLIGHT_ACTION_TYPE = 'highlight';
P
pissang 已提交
43
export const DOWNPLAY_ACTION_TYPE = 'downplay';
44 45 46 47 48

export const SELECT_ACTION_TYPE = 'select';
export const UNSELECT_ACTION_TYPE = 'unselect';
export const TOGGLE_SELECT_ACTION_TYPE = 'toggleSelect';

49 50 51 52 53 54 55 56 57 58
type ExtendedProps = {
    __highByOuter: number

    __highDownSilentOnTouch: boolean

    __highDownDispatcher: boolean
};
type ExtendedElement = Element & ExtendedProps;
type ExtendedDisplayable = Displayable & ExtendedProps;

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
function hasFillOrStroke(fillOrStroke: string | PatternObject | GradientObject) {
    return fillOrStroke != null && fillOrStroke !== 'none';
}
// Most lifted color are duplicated.
const liftedColorCache = new LRU<string>(100);
function liftColor(color: string): string {
    if (typeof color !== 'string') {
        return color;
    }
    let liftedColor = liftedColorCache.get(color);
    if (!liftedColor) {
        liftedColor = colorTool.lift(color, -0.1);
        liftedColorCache.put(color, liftedColor);
    }
    return liftedColor;
}

76 77 78 79 80
function doChangeHoverState(el: ECElement, stateName: DisplayState, hoverStateEnum: 0 | 1 | 2) {
    if (el.onHoverStateChange) {
        if ((el.hoverState || 0) !== hoverStateEnum) {
            el.onHoverStateChange(stateName);
        }
81
    }
82
    el.hoverState = hoverStateEnum;
83 84 85
}

function singleEnterEmphasis(el: ECElement) {
86 87
    // Only mark the flag.
    // States will be applied in the echarts.ts in next frame.
88
    doChangeHoverState(el, 'emphasis', HOVER_STATE_EMPHASIS);
89 90
}

91
function singleLeaveEmphasis(el: ECElement) {
92 93
    // Only mark the flag.
    // States will be applied in the echarts.ts in next frame.
94
    doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
95 96
}

97
function singleEnterBlur(el: ECElement) {
98
    doChangeHoverState(el, 'blur', HOVER_STATE_BLUR);
99 100 101
}

function singleLeaveBlur(el: ECElement) {
102 103 104 105 106 107 108 109
    doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
}

function singleEnterSelect(el: ECElement) {
    el.selected = true;
}
function singleLeaveSelect(el: ECElement) {
    el.selected = false;
110 111
}

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
function updateElementState<T>(
    el: ExtendedElement,
    updater: (this: void, el: Element, commonParam?: T) => void,
    commonParam?: T
) {
    updater(el, commonParam);
}

function traverseUpdateState<T>(
    el: ExtendedElement,
    updater: (this: void, el: Element, commonParam?: T) => void,
    commonParam?: T
) {
    updateElementState(el, updater, commonParam);
    el.isGroup && el.traverse(function (child: ExtendedElement) {
        updateElementState(child, updater, commonParam);
    });
}
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146

export function setStatesFlag(el: ECElement, stateName: DisplayState) {
    switch (stateName) {
        case 'emphasis':
            el.hoverState = HOVER_STATE_EMPHASIS;
            break;
        case 'normal':
            el.hoverState = HOVER_STATE_NORMAL;
            break;
        case 'blur':
            el.hoverState = HOVER_STATE_BLUR;
            break;
        case 'select':
            el.selected = true;
    }
}

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
/**
 * If we reuse elements when rerender.
 * DONT forget to clearStates before we update the style and shape.
 * Or we may update on the wrong state instead of normal state.
 */
export function clearStates(el: Element) {
    if (el.isGroup) {
        el.traverse(function (child) {
            child.clearStates();
        });
    }
    else {
        el.clearStates();
    }
}
162

163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
function getFromStateStyle(
    el: Displayable,
    props: (keyof PathStyleProps)[],
    toStateName: string,
    defaultValue?: PathStyleProps
): PathStyleProps {
    const style = el.style;
    const fromState: PathStyleProps = {};
    for (let i = 0; i < props.length; i++) {
        const propName = props[i];
        const val = style[propName];
        (fromState as any)[propName] = val == null ? (defaultValue && defaultValue[propName]) : val;
    }
    for (let i = 0; i < el.animators.length; i++) {
        const animator = el.animators[i];
        if (animator.__fromStateTransition
            // Dont consider the animation to emphasis state.
            && animator.__fromStateTransition.indexOf(toStateName) < 0
            && animator.targetName === 'style') {
P
pissang 已提交
182
            animator.saveFinalToTarget(fromState, props);
183 184 185 186 187
        }
    }
    return fromState;
}

188 189 190
function createEmphasisDefaultState(
    el: Displayable,
    stateName: 'emphasis',
P
pissang 已提交
191
    targetStates: string[],
192 193
    state: Displayable['states'][number]
) {
194
    const hasSelect = targetStates && indexOf(targetStates, 'select') >= 0;
195
    let cloned = false;
196
    if (el instanceof Path) {
197 198 199 200
        const store = getSavedStates(el);
        const fromFill = hasSelect ? (store.selectFill || store.normalFill) : store.normalFill;
        const fromStroke = hasSelect ? (store.selectStroke || store.normalStroke) : store.normalStroke;
        if (hasFillOrStroke(fromFill) || hasFillOrStroke(fromStroke)) {
201 202 203
            state = state || {};
            // Apply default color lift
            let emphasisStyle = state.style || {};
204
            if (!hasFillOrStroke(emphasisStyle.fill) && hasFillOrStroke(fromFill)) {
205 206 207 208 209
                cloned = true;
                // Not modify the original value.
                state = extend({}, state);
                emphasisStyle = extend({}, emphasisStyle);
                // Already being applied 'emphasis'. DON'T lift color multiple times.
210
                emphasisStyle.fill = liftColor(fromFill as ColorString);
211
            }
212
            // Not highlight stroke if fill has been highlighted.
213
            else if (!hasFillOrStroke(emphasisStyle.stroke) && hasFillOrStroke(fromStroke)) {
214
                if (!cloned) {
215 216 217
                    state = extend({}, state);
                    emphasisStyle = extend({}, emphasisStyle);
                }
218
                emphasisStyle.stroke = liftColor(fromStroke as ColorString);
219
            }
220
            state.style = emphasisStyle;
221
        }
222 223 224 225 226 227
    }
    if (state) {
        // TODO Share with textContent?
        if (state.z2 == null) {
            if (!cloned) {
                state = extend({}, state);
228
            }
229 230
            const z2EmphasisLift = (el as ECElement).z2EmphasisLift;
            state.z2 = el.z2 + (z2EmphasisLift != null ? z2EmphasisLift : Z2_EMPHASIS_LIFT);
231
        }
232
    }
233 234 235 236 237 238 239 240
    return state;
}

function createSelectDefaultState(
    el: Displayable,
    stateName: 'select',
    state: Displayable['states'][number]
) {
241
    // const hasSelect = indexOf(el.currentStates, stateName) >= 0;
242 243
    if (state) {
        // TODO Share with textContent?
244
        if (state.z2 == null) {
245
            state = extend({}, state);
246 247
            const z2SelectLift = (el as ECElement).z2SelectLift;
            state.z2 = el.z2 + (z2SelectLift != null ? z2SelectLift : Z2_SELECT_LIFT);
248
        }
249 250 251 252 253 254 255 256 257 258 259
    }
    return state;
}

function createBlurDefaultState(
    el: Displayable,
    stateName: 'blur',
    state: Displayable['states'][number]
) {
    const hasBlur = indexOf(el.currentStates, stateName) >= 0;
    const currentOpacity = el.style.opacity;
260 261

    const fromState = !hasBlur
262
        ? getFromStateStyle(el, ['opacity'], stateName, {
263 264 265
            opacity: 1
        })
        : null;
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281

    state = state || {};
    let blurStyle = state.style || {};
    if (blurStyle.opacity == null) {
        // clone state
        state = extend({}, state);
        blurStyle = extend({
            // Already being applied 'emphasis'. DON'T mul opacity multiple times.
            opacity: hasBlur ? currentOpacity : (fromState.opacity * 0.1)
        }, blurStyle);
        state.style = blurStyle;
    }

    return state;
}

282
function elementStateProxy(this: Displayable, stateName: string, targetStates?: string[]): DisplayableState {
283 284 285
    const state = this.states[stateName];
    if (this.style) {
        if (stateName === 'emphasis') {
286
            return createEmphasisDefaultState(this, stateName, targetStates, state);
287 288 289
        }
        else if (stateName === 'blur') {
            return createBlurDefaultState(this, stateName, state);
290
        }
291 292 293
        else if (stateName === 'select') {
            return createSelectDefaultState(this, stateName, state);
        }
294 295 296 297 298 299 300 301
    }
    return state;
}
/**FI
 * Set hover style (namely "emphasis style") of element.
 * @param el Should not be `zrender/graphic/Group`.
 * @param focus 'self' | 'selfInSeries' | 'series'
 */
302
export function setDefaultStateProxy(el: Displayable) {
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
    el.stateProxy = elementStateProxy;
    const textContent = el.getTextContent();
    const textGuide = el.getTextGuideLine();
    if (textContent) {
        textContent.stateProxy = elementStateProxy;
    }
    if (textGuide) {
        textGuide.stateProxy = elementStateProxy;
    }
}

export function enterEmphasisWhenMouseOver(el: Element, e: ElementEvent) {
    !shouldSilent(el, e)
        // "emphasis" event highlight has higher priority than mouse highlight.
        && !(el as ExtendedElement).__highByOuter
        && traverseUpdateState((el as ExtendedElement), singleEnterEmphasis);
}

export function leaveEmphasisWhenMouseOut(el: Element, e: ElementEvent) {
    !shouldSilent(el, e)
        // "emphasis" event highlight has higher priority than mouse highlight.
        && !(el as ExtendedElement).__highByOuter
        && traverseUpdateState((el as ExtendedElement), singleLeaveEmphasis);
}

export function enterEmphasis(el: Element, highlightDigit?: number) {
    (el as ExtendedElement).__highByOuter |= 1 << (highlightDigit || 0);
    traverseUpdateState((el as ExtendedElement), singleEnterEmphasis);
}

export function leaveEmphasis(el: Element, highlightDigit?: number) {
    !((el as ExtendedElement).__highByOuter &= ~(1 << (highlightDigit || 0)))
        && traverseUpdateState((el as ExtendedElement), singleLeaveEmphasis);
}

P
pissang 已提交
338 339 340 341 342 343 344 345
export function enterBlur(el: Element) {
    traverseUpdateState(el as ExtendedElement, singleEnterBlur);
}

export function leaveBlur(el: Element) {
    traverseUpdateState(el as ExtendedElement, singleLeaveBlur);
}

346 347 348 349 350 351 352 353
export function enterSelect(el: Element) {
    traverseUpdateState(el as ExtendedElement, singleEnterSelect);
}

export function leaveSelect(el: Element) {
    traverseUpdateState(el as ExtendedElement, singleLeaveSelect);
}

354 355 356 357
function shouldSilent(el: Element, e: ElementEvent) {
    return (el as ExtendedElement).__highDownSilentOnTouch && e.zrByTouch;
}

P
pissang 已提交
358 359 360 361 362 363 364 365 366 367 368 369 370
function allLeaveBlur(ecIns: EChartsType) {
    const model = ecIns.getModel();
    model.eachComponent(function (componentType, componentModel) {
        const view = componentType === 'series'
            ? ecIns.getViewOfSeriesModel(componentModel as SeriesModel)
            : ecIns.getViewOfComponentModel(componentModel);
        // Leave blur anyway
        view.group.traverse(function (child) {
            singleLeaveBlur(child);
        });
    });
}

371
export function toggleSeriesBlurState(
372
    targetSeriesIndex: number,
373
    focus: InnerFocus,
374 375 376 377
    blurScope: BlurScope,
    ecIns: EChartsType,
    isBlur: boolean
) {
P
pissang 已提交
378 379 380 381 382 383 384 385
    const ecModel = ecIns.getModel();
    blurScope = blurScope || 'coordinateSystem';

    function leaveBlurOfIndices(data: List, dataIndices: ArrayLike<number>) {
        for (let i = 0; i < dataIndices.length; i++) {
            const itemEl = data.getItemGraphicEl(dataIndices[i]);
            itemEl && leaveBlur(itemEl);
        }
386 387
    }

P
pissang 已提交
388 389 390 391
    if (!isBlur) {
        allLeaveBlur(ecIns);
        return;
    }
392

P
pissang 已提交
393
    if (targetSeriesIndex == null) {
394 395
        return;
    }
396

P
pissang 已提交
397 398
    if (!focus || focus === 'none') {
        return;
399 400
    }

P
pissang 已提交
401
    const targetSeriesModel = ecModel.getSeriesByIndex(targetSeriesIndex);
402 403 404 405 406
    let targetCoordSys: CoordinateSystemMaster | CoordinateSystem = targetSeriesModel.coordinateSystem;
    if (targetCoordSys && (targetCoordSys as CoordinateSystem).master) {
        targetCoordSys = (targetCoordSys as CoordinateSystem).master;
    }

P
pissang 已提交
407 408 409 410
    const blurredSeries: SeriesModel[] = [];

    ecModel.eachSeries(function (seriesModel) {

411 412 413 414 415
        const sameSeries = targetSeriesModel === seriesModel;
        let coordSys: CoordinateSystemMaster | CoordinateSystem = seriesModel.coordinateSystem;
        if (coordSys && (coordSys as CoordinateSystem).master) {
            coordSys = (coordSys as CoordinateSystem).master;
        }
416 417 418
        const sameCoordSys = coordSys && targetCoordSys
            ? coordSys === targetCoordSys
            : sameSeries;   // If there is no coordinate system. use sameSeries instead.
419
        if (!(
420 421 422
            // Not blur other series if blurScope series
            blurScope === 'series' && !sameSeries
            // Not blur other coordinate system if blurScope is coordinateSystem
P
pissang 已提交
423
            || blurScope === 'coordinateSystem' && !sameCoordSys
424
            // Not blur self series if focus is series.
P
pissang 已提交
425 426
            || focus === 'series' && sameSeries
            // TODO blurScope: coordinate system
427 428 429
        )) {
            const view = ecIns.getViewOfSeriesModel(seriesModel);
            view.group.traverse(function (child) {
P
pissang 已提交
430
                singleEnterBlur(child);
431
            });
432

P
pissang 已提交
433 434 435 436 437 438 439
            if (isArrayLike(focus)) {
                leaveBlurOfIndices(seriesModel.getData(), focus as ArrayLike<number>);
            }
            else if (isObject(focus)) {
                const dataTypes = keys(focus);
                for (let d = 0; d < dataTypes.length; d++) {
                    leaveBlurOfIndices(seriesModel.getData(dataTypes[d]), focus[dataTypes[d]]);
440 441
                }
            }
P
pissang 已提交
442 443 444 445 446 447 448 449 450 451 452 453

            blurredSeries.push(seriesModel);
        }
    });

    ecModel.eachComponent(function (componentType, componentModel) {
        if (componentType === 'series') {
            return;
        }
        const view = ecIns.getViewOfComponentModel(componentModel);
        if (view && view.blurSeries) {
            view.blurSeries(blurredSeries, ecModel);
454
        }
455 456 457
    });
}

458 459 460 461 462
export function toggleSeriesBlurStateFromPayload(
    seriesModel: SeriesModel,
    payload: Payload,
    ecIns: EChartsType
) {
463
    if (!isHighDownPayload(payload)) {
464 465 466
        return;
    }

467
    const isHighlight = payload.type === HIGHLIGHT_ACTION_TYPE;
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
    const seriesIndex = seriesModel.seriesIndex;
    const data = seriesModel.getData(payload.dataType);
    let dataIndex = queryDataIndex(data, payload);
    // Pick the first one if there is multiple/none exists.
    dataIndex = (isArray(dataIndex) ? dataIndex[0] : dataIndex) || 0;
    let el = data.getItemGraphicEl(dataIndex as number);
    if (!el) {
        const count = data.count();
        let current = 0;
        // If data on dataIndex is NaN.
        while (!el && current < count) {
            el = data.getItemGraphicEl(current++);
        }
    }
    if (el) {
        const ecData = getECData(el);
        toggleSeriesBlurState(
            seriesIndex, ecData.focus, ecData.blurScope, ecIns, isHighlight
        );
    }
    else {
        // If there is no element put on the data. Try getting it from raw option
        // TODO Should put it on seriesModel?
        const focus = seriesModel.get(['emphasis', 'focus']);
        const blurScope = seriesModel.get(['emphasis', 'blurScope']);
        if (focus != null) {
            toggleSeriesBlurState(seriesIndex, focus, blurScope, ecIns, isHighlight);
        }
    }
}

export function toggleSelectionFromPayload(
    seriesModel: SeriesModel,
    payload: Payload,
    ecIns: EChartsType
) {
504
    if (!(isSelectChangePayload(payload))) {
505 506
        return;
    }
507 508
    const dataType = payload.dataType;
    const data = seriesModel.getData(dataType);
509 510 511 512 513
    let dataIndex = queryDataIndex(data, payload);
    if (!isArray(dataIndex)) {
        dataIndex = [dataIndex];
    }

514 515 516 517
    seriesModel[
        payload.type === TOGGLE_SELECT_ACTION_TYPE ? 'toggleSelect'
            : payload.type === SELECT_ACTION_TYPE ? 'select' : 'unselect'
    ](dataIndex, dataType);
518 519 520 521
}


export function updateSeriesElementSelection(seriesModel: SeriesModel) {
522 523 524 525 526
    const allData = seriesModel.getAllData();
    each(allData, function ({ data, type }) {
        data.eachItemGraphicEl(function (el, idx) {
            seriesModel.isSelected(idx, type) ? enterSelect(el) : leaveSelect(el);
        });
527 528 529
    });
}

P
pissang 已提交
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
export function getAllSelectedIndices(ecModel: GlobalModel) {
    const ret: {
        seriesIndex: number
        dataType?: string
        dataIndex: number[]
    }[] = [];
    ecModel.eachSeries(function (seriesModel) {
        const allData = seriesModel.getAllData();
        each(allData, function ({ data, type }) {
            const dataIndices = seriesModel.getSelectedDataIndices();
            if (dataIndices.length > 0) {
                const item: typeof ret[number] = {
                    dataIndex: dataIndices,
                    seriesIndex: seriesModel.seriesIndex
                };
                if (type != null) {
                    item.dataType = type;
                }
                ret.push(item);

            }
        });
    });
    return ret;
}

556 557 558
/**
 * Enable the function that mouseover will trigger the emphasis state.
 *
559 560 561
 * NOTE:
 * This function should be used on the element with dataIndex, seriesIndex.
 *
562
 */
563
export function enableHoverEmphasis(el: Element, focus?: InnerFocus, blurScope?: BlurScope) {
564
    setAsHighDownDispatcher(el, true);
565
    traverseUpdateState(el as ExtendedElement, setDefaultStateProxy);
566 567 568 569

    enableHoverFocus(el, focus, blurScope);
}

570
export function enableHoverFocus(el: Element, focus: InnerFocus, blurScope: BlurScope) {
571 572
    if (focus != null) {
        const ecData = getECData(el);
573 574 575 576 577 578 579 580 581 582
        // TODO dataIndex may be set after this function. This check is not useful.
        // if (ecData.dataIndex == null) {
        //     if (__DEV__) {
        //         console.warn('focus can only been set on element with dataIndex');
        //     }
        // }
        // else {
        ecData.focus = focus;
        ecData.blurScope = blurScope;
        // }
583
    }
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
}

const OTHER_STATES = ['emphasis', 'blur', 'select'] as const;
const styleGetterMap: Dictionary<'getItemStyle' | 'getLineStyle' | 'getAreaStyle'> = {
    itemStyle: 'getItemStyle',
    lineStyle: 'getLineStyle',
    areaStyle: 'getAreaStyle'
};
/**
 * Set emphasis/blur/selected states of element.
 */
export function setStatesStylesFromModel(
    el: Displayable,
    itemModel: Model<Partial<Record<'emphasis' | 'blur' | 'select', any>>>,
    styleType?: string, // default itemStyle
    getterType?: 'getItemStyle' | 'getLineStyle' | 'getAreaStyle'
) {
    styleType = styleType || 'itemStyle';
    for (let i = 0; i < OTHER_STATES.length; i++) {
        const stateName = OTHER_STATES[i];
        const model = itemModel.getModel([stateName, styleType]);
        const state = el.ensureState(stateName);
        // Let it throw error if getterType is not found.
        state.style = model[getterType || styleGetterMap[styleType]]();
    }
}

611

612
/**
613 614
 * @parame el
 * @param el.highDownSilentOnTouch
615 616 617 618 619 620 621 622 623
 *        In touch device, mouseover event will be trigger on touchstart event
 *        (see module:zrender/dom/HandlerProxy). By this mechanism, we can
 *        conveniently use hoverStyle when tap on touch screen without additional
 *        code for compatibility.
 *        But if the chart/component has select feature, which usually also use
 *        hoverStyle, there might be conflict between 'select-highlight' and
 *        'hover-highlight' especially when roam is enabled (see geo for example).
 *        In this case, `highDownSilentOnTouch` should be used to disable
 *        hover-highlight on touch device.
624
 * @param asDispatcher If `false`, do not set as "highDownDispatcher".
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
 */
export function setAsHighDownDispatcher(el: Element, asDispatcher: boolean) {
    const disable = asDispatcher === false;
    const extendedEl = el as ExtendedElement;
    // Make `highDownSilentOnTouch` and `onStateChange` only work after
    // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
    if ((el as ECElement).highDownSilentOnTouch) {
        extendedEl.__highDownSilentOnTouch = (el as ECElement).highDownSilentOnTouch;
    }
    // Simple optimize, since this method might be
    // called for each elements of a group in some cases.
    if (!disable || extendedEl.__highDownDispatcher) {
        // Emphasis, normal can be triggered manually by API or other components like hover link.
        // el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
        // Also keep previous record.
        extendedEl.__highByOuter = extendedEl.__highByOuter || 0;
        extendedEl.__highDownDispatcher = !disable;
    }
}

export function isHighDownDispatcher(el: Element): boolean {
    return !!(el && (el as ExtendedDisplayable).__highDownDispatcher);
}

/**
 * Support hightlight/downplay record on each elements.
 * For the case: hover highlight/downplay (legend, visualMap, ...) and
 * user triggerred hightlight/downplay should not conflict.
 * Only all of the highlightDigit cleared, return to normal.
 * @param {string} highlightKey
 * @return {number} highlightDigit
 */
export function getHighlightDigit(highlightKey: number) {
    let highlightDigit = _highlightKeyMap[highlightKey];
    if (highlightDigit == null && _highlightNextDigit <= 32) {
        highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
    }
    return highlightDigit;
663 664 665 666 667 668 669 670 671
}

export function isSelectChangePayload(payload: Payload) {
    const payloadType = payload.type;
    return payloadType === SELECT_ACTION_TYPE
        || payloadType === UNSELECT_ACTION_TYPE
        || payloadType === TOGGLE_SELECT_ACTION_TYPE;
}

672
export function isHighDownPayload(payload: Payload): payload is HighlightPayload | DownplayPayload {
673 674 675
    const payloadType = payload.type;
    return payloadType === HIGHLIGHT_ACTION_TYPE
        || payloadType === DOWNPLAY_ACTION_TYPE;
676 677 678 679 680 681 682 683 684 685
}

export function savePathStates(el: Path) {
    const store = getSavedStates(el);
    store.normalFill = el.style.fill;
    store.normalStroke = el.style.stroke;

    const selectState = el.states.select || {};
    store.selectFill = (selectState.style && selectState.style.fill) || null;
    store.selectStroke = (selectState.style && selectState.style.stroke) || null;
686
}