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

S
sushuang 已提交
20
import * as zrUtil from 'zrender/src/core/util';
S
sushuang 已提交
21 22 23 24
import RoamController from './RoamController';
import * as roamHelper from '../../component/helper/roamHelper';
import {onIrrelevantElement} from '../../component/helper/cursorHelper';
import * as graphic from '../../util/graphic';
1
100pah 已提交
25 26 27 28
import {
    enableHoverEmphasis,
    DISPLAY_STATES,
    enableComponentHighDownFeatures,
1
100pah 已提交
29 30
    setDefaultStateProxy,
    SPECIAL_STATES
1
100pah 已提交
31
} from '../../util/states';
S
sushuang 已提交
32 33
import geoSourceManager from '../../coord/geo/geoSourceManager';
import {getUID} from '../../util/component';
34
import ExtensionAPI from '../../core/ExtensionAPI';
35 36 37
import GeoModel, { GeoCommonOptionMixin, GeoItemStyleOption } from '../../coord/geo/GeoModel';
import MapSeries from '../../chart/map/MapSeries';
import GlobalModel from '../../model/Global';
1
100pah 已提交
38
import { Payload, ECElement, LineStyleOption, InnerFocus } from '../../util/types';
39 40 41 42
import GeoView from '../geo/GeoView';
import MapView from '../../chart/map/MapView';
import Geo from '../../coord/geo/Geo';
import Model from '../../model/Model';
1
100pah 已提交
43
import { setLabelStyle, getLabelStatesModels, createTextConfig } from '../../label/labelStyle';
44
import { getECData } from '../../util/innerStore';
P
pissang 已提交
45
import { createOrUpdatePatternFromDecal } from '../../util/decal';
1
100pah 已提交
46
import { ViewCoordSysTransformInfoPart } from '../../coord/View';
1
100pah 已提交
47
import { GeoSVGGraphicRecord, GeoSVGResource } from '../../coord/geo/GeoSVGResource';
48
import Displayable from 'zrender/src/graphic/Displayable';
1
100pah 已提交
49
import Element, { ElementTextConfig } from 'zrender/src/Element';
50
import List from '../../data/List';
1
100pah 已提交
51
import { GeoJSONRegion } from '../../coord/geo/Region';
1
100pah 已提交
52
import { SVGNodeTagLower } from 'zrender/src/tool/parseSVG';
53 54 55 56


interface RegionsGroup extends graphic.Group {
}
S
sushuang 已提交
57

1
100pah 已提交
58 59 60 61
type RegionModel = ReturnType<GeoModel['getRegionModel']> | ReturnType<MapSeries['getRegionModel']>;

type MapOrGeoModel = GeoModel | MapSeries;

62 63 64 65 66 67 68 69 70 71
interface ViewBuildContext {
    api: ExtensionAPI;
    geo: Geo;
    mapOrGeoModel: GeoModel | MapSeries;
    data: List;
    isVisualEncodedByVisualMap: boolean;
    isGeo: boolean;
    transformInfoRaw: ViewCoordSysTransformInfoPart;
}

1
100pah 已提交
72 73 74 75
interface GeoStyleableOption {
    itemStyle?: GeoItemStyleOption;
    lineStyle?: LineStyleOption;
}
1
100pah 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
type RegionName = string;

/**
 * Only these tags enable use `itemStyle` if they are named in SVG.
 * Other tags like <text> <tspan> <image> might not suitable for `itemStyle`.
 * They will not be considered to be styled until some requirements come.
 */
const OPTION_STYLE_ENABLED_TAGS: SVGNodeTagLower[] = [
    'rect', 'circle', 'line', 'ellipse', 'polygon', 'polyline', 'path'
];
const OPTION_STYLE_ENABLED_TAG_MAP = zrUtil.createHashMap<number, SVGNodeTagLower>(
    OPTION_STYLE_ENABLED_TAGS
);
const STATE_TRIGGER_TAG_MAP = zrUtil.createHashMap<number, SVGNodeTagLower>(
    OPTION_STYLE_ENABLED_TAGS.concat(['g']) as SVGNodeTagLower[]
);
const LABEL_HOST_MAP = zrUtil.createHashMap<number, SVGNodeTagLower>(
    OPTION_STYLE_ENABLED_TAGS.concat(['g']) as SVGNodeTagLower[]
);

1
100pah 已提交
96

97
function getFixedItemStyle(model: Model<GeoItemStyleOption>) {
98 99
    const itemStyle = model.getItemStyle();
    const areaColor = model.get('areaColor');
S
sushuang 已提交
100 101 102 103 104

    // If user want the color not to be changed when hover,
    // they should both set areaColor and color to be null.
    if (areaColor != null) {
        itemStyle.fill = areaColor;
L
lang 已提交
105 106
    }

S
sushuang 已提交
107 108
    return itemStyle;
}
109
class MapDraw {
110

111
    private uid: string;
S
sushuang 已提交
112

113
    private _controller: RoamController;
114

115
    private _controllerHost: {
P
pissang 已提交
116
        target: graphic.Group;
117 118 119
        zoom?: number;
        zoomLimit?: GeoCommonOptionMixin['scaleLimit'];
    };
L
lang 已提交
120

121
    readonly group: graphic.Group;
L
lang 已提交
122 123


S
sushuang 已提交
124 125 126 127 128
    /**
     * This flag is used to make sure that only one among
     * `pan`, `zoom`, `click` can occurs, otherwise 'selected'
     * action may be triggered when `pan`, which is unexpected.
     */
129
    private _mouseDownFlag: boolean;
S
sushuang 已提交
130

131 132
    private _regionsGroup: RegionsGroup;

1
100pah 已提交
133 134
    private _regionsGroupByName: zrUtil.HashMap<RegionsGroup>;

1
100pah 已提交
135 136
    private _svgMapName: string;

1
100pah 已提交
137
    private _svgGroup: graphic.Group;
S
sushuang 已提交
138

1
100pah 已提交
139
    private _svgGraphicRecord: GeoSVGGraphicRecord;
140

1
100pah 已提交
141 142 143 144
    // A name may correspond to multiple graphics.
    // Used as event dispatcher.
    private _svgDispatcherMap: zrUtil.HashMap<Element[], RegionName>;

145

P
pissang 已提交
146
    constructor(api: ExtensionAPI) {
147
        const group = new graphic.Group();
148 149
        this.uid = getUID('ec_map_draw');
        this._controller = new RoamController(api.getZr());
P
pissang 已提交
150
        this._controllerHost = { target: group };
151
        this.group = group;
L
lang 已提交
152

153
        group.add(this._regionsGroup = new graphic.Group() as RegionsGroup);
1
100pah 已提交
154
        group.add(this._svgGroup = new graphic.Group());
155
    }
L
lang 已提交
156

157 158 159 160
    draw(
        mapOrGeoModel: GeoModel | MapSeries,
        ecModel: GlobalModel,
        api: ExtensionAPI,
1
100pah 已提交
161 162
        fromView: MapView | GeoView,
        payload: Payload
163
    ): void {
L
lang 已提交
164

165
        const isGeo = mapOrGeoModel.mainType === 'geo';
L
lang 已提交
166

S
sushuang 已提交
167 168
        // Map series has data. GEO model that controlled by map series
        // will be assigned with map data. Other GEO model has no data.
169
        let data = (mapOrGeoModel as MapSeries).getData && (mapOrGeoModel as MapSeries).getData();
170
        isGeo && ecModel.eachComponent({mainType: 'series', subType: 'map'}, function (mapSeries: MapSeries) {
S
sushuang 已提交
171 172
            if (!data && mapSeries.getHostGeoModel() === mapOrGeoModel) {
                data = mapSeries.getData();
L
lang 已提交
173
            }
S
sushuang 已提交
174 175
        });

176
        const geo = mapOrGeoModel.coordinateSystem;
S
sushuang 已提交
177

178 179
        const regionsGroup = this._regionsGroup;
        const group = this.group;
L
lang 已提交
180

181
        const transformInfo = geo.getTransformInfo();
182 183
        const transformInfoRaw = transformInfo.raw;
        const transformInfoRoam = transformInfo.roam;
184 185 186

        // No animation when first draw or in action
        const isFirstDraw = !regionsGroup.childAt(0) || payload;
187

188
        if (isFirstDraw) {
189 190 191 192
            group.x = transformInfoRoam.x;
            group.y = transformInfoRoam.y;
            group.scaleX = transformInfoRoam.scaleX;
            group.scaleY = transformInfoRoam.scaleY;
193 194 195
            group.dirty();
        }
        else {
196
            graphic.updateProps(group, transformInfoRoam, mapOrGeoModel);
197
        }
L
lang 已提交
198

P
pissang 已提交
199 200 201
        const isVisualEncodedByVisualMap = data
            && data.getVisual('visualMeta')
            && data.getVisual('visualMeta').length > 0;
202

203 204 205 206 207 208 209 210 211 212
        const viewBuildCtx = {
            api,
            geo,
            mapOrGeoModel,
            data,
            isVisualEncodedByVisualMap,
            isGeo,
            transformInfoRaw
        };

1
100pah 已提交
213 214 215 216 217 218
        if (geo.resourceType === 'geoJSON') {
            this._buildGeoJSON(viewBuildCtx);
        }
        else if (geo.resourceType === 'geoSVG') {
            this._buildSVG(viewBuildCtx);
        }
219 220 221 222 223 224 225

        this._updateController(mapOrGeoModel, ecModel, api);

        this._updateMapSelectHandler(mapOrGeoModel, regionsGroup, api, fromView);
    }

    private _buildGeoJSON(viewBuildCtx: ViewBuildContext): void {
1
100pah 已提交
226
        const nameMap = this._regionsGroupByName = zrUtil.createHashMap<RegionsGroup>();
227 228
        const regionsGroup = this._regionsGroup;
        const transformInfoRaw = viewBuildCtx.transformInfoRaw;
1
100pah 已提交
229 230
        const mapOrGeoModel = viewBuildCtx.mapOrGeoModel;
        const data = viewBuildCtx.data;
231 232 233 234 235 236 237 238 239

        const transformPoint = function (point: number[]): number[] {
            return [
                point[0] * transformInfoRaw.scaleX + transformInfoRaw.x,
                point[1] * transformInfoRaw.scaleY + transformInfoRaw.y
            ];
        };

        regionsGroup.removeAll();
1
100pah 已提交
240

241
        // Only when the resource is GeoJSON, there is `geo.regions`.
1
100pah 已提交
242
        zrUtil.each(viewBuildCtx.geo.regions, function (region: GeoJSONRegion) {
1
100pah 已提交
243 244 245
            const regionName = region.name;
            const regionModel = mapOrGeoModel.getRegionModel(regionName);
            const dataIdx = data ? data.indexOfName(regionName) : null;
1
100pah 已提交
246

S
sushuang 已提交
247 248 249 250 251
            // Consider in GeoJson properties.name may be duplicated, for example,
            // there is multiple region named "United Kindom" or "France" (so many
            // colonies). And it is not appropriate to merge them in geo, which
            // will make them share the same label and bring trouble in label
            // location calculation.
1
100pah 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
            let regionGroup = nameMap.get(regionName);

            if (!regionGroup) {
                regionGroup = nameMap.set(regionName, new graphic.Group() as RegionsGroup);
                regionsGroup.add(regionGroup);

                resetEventTriggerForRegion(
                    viewBuildCtx, regionGroup, regionName, regionModel, mapOrGeoModel, dataIdx
                );
                resetTooltipForRegion(
                    viewBuildCtx, regionGroup, regionName, regionModel, mapOrGeoModel
                );
                resetStateTriggerForRegion(
                    viewBuildCtx, regionGroup, regionName, regionModel, mapOrGeoModel
                );
            }
S
sushuang 已提交
268

269
            const compoundPath = new graphic.CompoundPath({
270
                segmentIgnoreThreshold: 1,
S
sushuang 已提交
271 272 273 274 275 276 277 278 279 280
                shape: {
                    paths: []
                }
            });
            regionGroup.add(compoundPath);

            zrUtil.each(region.geometries, function (geometry) {
                if (geometry.type !== 'polygon') {
                    return;
                }
281
                const points = [];
1
100pah 已提交
282
                for (let i = 0; i < geometry.exterior.length; ++i) {
283
                    points.push(transformPoint(geometry.exterior[i]));
284
                }
S
sushuang 已提交
285
                compoundPath.shape.paths.push(new graphic.Polygon({
286
                    segmentIgnoreThreshold: 1,
S
sushuang 已提交
287
                    shape: {
288
                        points: points
L
lang 已提交
289
                    }
S
sushuang 已提交
290 291
                }));

1
100pah 已提交
292
                for (let i = 0; i < (geometry.interiors ? geometry.interiors.length : 0); ++i) {
293 294
                    const interior = geometry.interiors[i];
                    const points = [];
295
                    for (let j = 0; j < interior.length; ++j) {
296 297
                        points.push(transformPoint(interior[j]));
                    }
L
lang 已提交
298
                    compoundPath.shape.paths.push(new graphic.Polygon({
299
                        segmentIgnoreThreshold: 1,
L
lang 已提交
300
                        shape: {
301
                            points: points
L
lang 已提交
302
                        }
L
lang 已提交
303
                    }));
S
sushuang 已提交
304 305
                }
            });
L
lang 已提交
306

1
100pah 已提交
307 308 309 310 311 312 313 314
            applyOptionStyleForRegion(
                viewBuildCtx, compoundPath, dataIdx, regionModel
            );

            if (compoundPath instanceof Displayable) {
                compoundPath.culling = true;
            }

1
100pah 已提交
315
            const centerPt = transformPoint(region.getCenter());
1
100pah 已提交
316 317 318
            resetLabelForRegion(
                viewBuildCtx, compoundPath, regionName, regionModel, mapOrGeoModel, dataIdx, centerPt
            );
P
pissang 已提交
319

320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
        }, this);
    }

    private _buildSVG(viewBuildCtx: ViewBuildContext): void {
        const mapName = viewBuildCtx.geo.map;
        const transformInfoRaw = viewBuildCtx.transformInfoRaw;

        this._svgGroup.x = transformInfoRaw.x;
        this._svgGroup.y = transformInfoRaw.y;
        this._svgGroup.scaleX = transformInfoRaw.scaleX;
        this._svgGroup.scaleY = transformInfoRaw.scaleY;

        if (this._svgResourceChanged(mapName)) {
            this._freeSVG();
            this._useSVG(mapName);
        }
P
pah100 已提交
336

1
100pah 已提交
337 338
        const svgDispatcherMap = this._svgDispatcherMap = zrUtil.createHashMap<Element[], RegionName>();

1
100pah 已提交
339
        let focusSelf = false;
1
100pah 已提交
340
        zrUtil.each(this._svgGraphicRecord.named, function (namedItem) {
341 342 343 344
            // Note that we also allow different elements have the same name.
            // For example, a glyph of a city and the label of the city have
            // the same name and their tooltip info can be defined in a single
            // region option.
1
100pah 已提交
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397

            const regionName = namedItem.name;
            const mapOrGeoModel = viewBuildCtx.mapOrGeoModel;
            const data = viewBuildCtx.data;
            const svgNodeTagLower = namedItem.svgNodeTagLower;
            const el = namedItem.el;

            const dataIdx = data ? data.indexOfName(regionName) : null;
            const regionModel = mapOrGeoModel.getRegionModel(regionName);

            if (OPTION_STYLE_ENABLED_TAG_MAP.get(svgNodeTagLower) != null
                && (el instanceof Displayable)
            ) {
                applyOptionStyleForRegion(viewBuildCtx, el, dataIdx, regionModel);
            }

            if (el instanceof Displayable) {
                el.culling = true;
            }

            // We do not know how the SVG like so we'd better not to change z2.
            // Otherwise it might bring some unexpected result. For example,
            // an area hovered that make some inner city can not be clicked.
            (el as ECElement).z2EmphasisLift = 0;

            // If self named, that is, if tag is inside a named <g> (where `namedFrom` does not exists):
            if (!namedItem.namedFrom) {
                // label should batter to be displayed based on the center of <g>
                // if it is named rather than displayed on each child.
                if (LABEL_HOST_MAP.get(svgNodeTagLower) != null) {
                    resetLabelForRegion(
                        viewBuildCtx, el, regionName, regionModel, mapOrGeoModel, dataIdx, [0, 0]
                    );
                }

                resetEventTriggerForRegion(
                    viewBuildCtx, el, regionName, regionModel, mapOrGeoModel, dataIdx
                );

                resetTooltipForRegion(
                    viewBuildCtx, el, regionName, regionModel, mapOrGeoModel
                );

                if (STATE_TRIGGER_TAG_MAP.get(svgNodeTagLower) != null) {
                    const focus = resetStateTriggerForRegion(
                        viewBuildCtx, el, regionName, regionModel, mapOrGeoModel
                    );
                    if (focus === 'self') {
                        focusSelf = true;
                    }
                    const els = svgDispatcherMap.get(regionName) || svgDispatcherMap.set(regionName, []);
                    els.push(el);
                }
1
100pah 已提交
398
            }
1
100pah 已提交
399

400
        }, this);
1
100pah 已提交
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427

        // It's a little complicated to support blurring the entire geoSVG in series-map.
        // So do not suport it until some requirements come.
        // At present, in series-map, only regions can be blurred.
        if (focusSelf && viewBuildCtx.isGeo) {
            const blurStyle = (viewBuildCtx.mapOrGeoModel as GeoModel).getModel(['blur', 'itemStyle']).getItemStyle();
            // Only suport `opacity` here. Because not sure that other props are suitable for
            // all of the elements generated by SVG (especially for Text/TSpan/Image/... ).
            const opacity = blurStyle.opacity;
            this._svgGraphicRecord.root.traverse(el => {
                if (!el.isGroup) {
                    // PENDING: clear those settings to SVG elements when `_freeSVG`.
                    // (Currently it happen not to be needed.)
                    setDefaultStateProxy(el as Displayable);
                    const style = (el as Displayable).ensureState('blur').style || {};
                    // Do not overwrite the region style that already set from region option.
                    if (style.opacity == null && opacity != null) {
                        style.opacity = opacity;
                    }
                    // If opacity not set, but `ensureState('blur').style` set, there will
                    // be default opacity.

                    // Enable `stateTransition` (animation).
                    (el as Displayable).ensureState('emphasis');
                }
            });
        }
428 429
    }

430
    remove(): void {
S
sushuang 已提交
431
        this._regionsGroup.removeAll();
1
100pah 已提交
432
        this._regionsGroupByName = null;
1
100pah 已提交
433
        this._svgGroup.removeAll();
434
        this._freeSVG();
1
100pah 已提交
435
        this._controller.dispose();
P
pissang 已提交
436
        this._controllerHost = null;
437
    }
438

1
100pah 已提交
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
    findHighDownDispatchers(name: string, geoModel: GeoModel): Element[] {
        if (name == null) {
            return [];
        }

        const geo = geoModel.coordinateSystem;

        if (geo.resourceType === 'geoJSON') {
            const regionsGroupByName = this._regionsGroupByName;
            if (regionsGroupByName) {
                const regionGroup = regionsGroupByName.get(name);
                return regionGroup ? [regionGroup] : [];
            }
        }
        else if (geo.resourceType === 'geoSVG') {
1
100pah 已提交
454
            return this._svgDispatcherMap && this._svgDispatcherMap.get(name) || [];
1
100pah 已提交
455 456 457
        }
    }

458 459
    private _svgResourceChanged(mapName: string): boolean {
        return this._svgMapName !== mapName;
1
100pah 已提交
460
    }
S
sushuang 已提交
461

462
    private _useSVG(mapName: string): void {
1
100pah 已提交
463
        const resource = geoSourceManager.getGeoResource(mapName);
1
100pah 已提交
464
        if (resource && resource.type === 'geoSVG') {
1
100pah 已提交
465 466
            const svgGraphic = (resource as GeoSVGResource).useGraphic(this.uid);
            this._svgGroup.add(svgGraphic.root);
1
100pah 已提交
467
            this._svgGraphicRecord = svgGraphic;
468
            this._svgMapName = mapName;
1
100pah 已提交
469 470 471
        }
    }

472 473
    private _freeSVG(): void {
        const mapName = this._svgMapName;
1
100pah 已提交
474 475 476
        if (mapName == null) {
            return;
        }
1
100pah 已提交
477

1
100pah 已提交
478
        const resource = geoSourceManager.getGeoResource(mapName);
1
100pah 已提交
479
        if (resource && resource.type === 'geoSVG') {
1
100pah 已提交
480 481
            (resource as GeoSVGResource).freeGraphic(this.uid);
        }
1
100pah 已提交
482
        this._svgGraphicRecord = null;
1
100pah 已提交
483
        this._svgDispatcherMap = null;
484 485
        this._svgGroup.removeAll();
        this._svgMapName = null;
486
    }
S
sushuang 已提交
487

488
    private _updateController(
1
100pah 已提交
489
        this: MapDraw, mapOrGeoModel: GeoModel | MapSeries, ecModel: GlobalModel, api: ExtensionAPI
490
    ): void {
491 492 493
        const geo = mapOrGeoModel.coordinateSystem;
        const controller = this._controller;
        const controllerHost = this._controllerHost;
494

495
        // @ts-ignore FIXME:TS
S
sushuang 已提交
496 497
        controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit');
        controllerHost.zoom = geo.getZoom();
P
pah100 已提交
498

S
sushuang 已提交
499
        // roamType is will be set default true if it is null
500
        // @ts-ignore FIXME:TS
S
sushuang 已提交
501
        controller.enable(mapOrGeoModel.get('roam') || false);
502
        const mainType = mapOrGeoModel.mainType;
503

504
        function makeActionBase(): Payload {
505
            const action = {
S
sushuang 已提交
506 507
                type: 'geoRoam',
                componentType: mainType
508
            } as Payload;
S
sushuang 已提交
509 510 511
            action[mainType + 'Id'] = mapOrGeoModel.id;
            return action;
        }
512

1
100pah 已提交
513
        controller.off('pan').on('pan', function (e) {
S
sushuang 已提交
514
            this._mouseDownFlag = false;
P
pah100 已提交
515

516
            roamHelper.updateViewOnPan(controllerHost, e.dx, e.dy);
517

S
sushuang 已提交
518
            api.dispatchAction(zrUtil.extend(makeActionBase(), {
519 520
                dx: e.dx,
                dy: e.dy
S
sushuang 已提交
521 522
            }));
        }, this);
L
lang 已提交
523

1
100pah 已提交
524
        controller.off('zoom').on('zoom', function (e) {
S
sushuang 已提交
525 526
            this._mouseDownFlag = false;

527
            roamHelper.updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
S
sushuang 已提交
528 529

            api.dispatchAction(zrUtil.extend(makeActionBase(), {
530 531 532
                zoom: e.scale,
                originX: e.originX,
                originY: e.originY
S
sushuang 已提交
533 534 535 536 537
            }));

        }, this);

        controller.setPointerChecker(function (e, x, y) {
1
100pah 已提交
538
            return geo.containPoint([x, y])
S
sushuang 已提交
539
                && !onIrrelevantElement(e, api, mapOrGeoModel);
S
sushuang 已提交
540 541
        });
    }
542 543 544 545 546 547 548

    private _updateMapSelectHandler(
        mapOrGeoModel: GeoModel | MapSeries,
        regionsGroup: RegionsGroup,
        api: ExtensionAPI,
        fromView: MapView | GeoView
    ): void {
549
        const mapDraw = this;
550 551

        regionsGroup.off('mousedown');
1
100pah 已提交
552
        regionsGroup.off('click');
553 554 555 556 557 558 559 560 561

        // @ts-ignore FIXME:TS resolve type conflict
        if (mapOrGeoModel.get('selectedMode')) {

            regionsGroup.on('mousedown', function () {
                mapDraw._mouseDownFlag = true;
            });

            regionsGroup.on('click', function (e) {
562
                if (!mapDraw._mouseDownFlag) {
563 564
                    return;
                }
565
                mapDraw._mouseDownFlag = false;
566 567 568 569
            });
        }
    }

S
sushuang 已提交
570
};
L
lang 已提交
571

1
100pah 已提交
572 573 574 575 576 577 578 579 580 581 582 583 584
function labelTextAfterUpdate(this: graphic.Text) {
    // Make the label text do not scale but perform translate
    // based on its host el.
    const m = this.transform;
    const scaleX = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
    const scaleY = Math.sqrt(m[2] * m[2] + m[3] * m[3]);

    m[0] /= scaleX;
    m[1] /= scaleX;
    m[2] /= scaleY;
    m[3] /= scaleY;
}

1
100pah 已提交
585 586
function applyOptionStyleForRegion(
    viewBuildCtx: ViewBuildContext,
1
100pah 已提交
587
    el: Displayable,
1
100pah 已提交
588
    dataIndex: number,
1
100pah 已提交
589 590 591 592 593 594 595
    regionModel: Model<
        GeoStyleableOption & {
            emphasis?: GeoStyleableOption;
            select?: GeoStyleableOption;
            blur?: GeoStyleableOption;
        }
    >
1
100pah 已提交
596 597 598 599 600 601 602 603 604 605 606 607 608
): void {
    // All of the path are using `itemStyle`, becuase
    // (1) Some SVG also use fill on polyline (The different between
    // polyline and polygon is "open" or "close" but not fill or not).
    // (2) For the common props like opacity, if some use itemStyle
    // and some use `lineStyle`, it might confuse users.
    // (3) Most SVG use <path>, where can not detect wether draw a "line"
    // or a filled shape, so use `itemStyle` for <path>.

    const normalStyleModel = regionModel.getModel('itemStyle');
    const emphasisStyleModel = regionModel.getModel(['emphasis', 'itemStyle']);
    const blurStyleModel = regionModel.getModel(['blur', 'itemStyle']);
    const selectStyleModel = regionModel.getModel(['select', 'itemStyle']);
1
100pah 已提交
609 610 611

    // NOTE: DONT use 'style' in visual when drawing map.
    // This component is used for drawing underlying map for both geo component and map series.
1
100pah 已提交
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
    const normalStyle = getFixedItemStyle(normalStyleModel);
    const emphasisStyle = getFixedItemStyle(emphasisStyleModel);
    const selectStyle = getFixedItemStyle(selectStyleModel);
    const blurStyle = getFixedItemStyle(blurStyleModel);

    // Update the itemStyle if has data visual
    const data = viewBuildCtx.data;
    if (data) {
        // Only visual color of each item will be used. It can be encoded by visualMap
        // But visual color of series is used in symbol drawing

        // Visual color for each series is for the symbol draw
        const style = data.getItemVisual(dataIndex, 'style');
        const decal = data.getItemVisual(dataIndex, 'decal');
        if (viewBuildCtx.isVisualEncodedByVisualMap && style.fill) {
            normalStyle.fill = style.fill;
        }
        if (decal) {
            normalStyle.decal = createOrUpdatePatternFromDecal(decal, viewBuildCtx.api);
        }
1
100pah 已提交
632
    }
1
100pah 已提交
633 634 635

    // SVG text, tspan and image can be named but not supporeted
    // to be styled by region option yet.
1
100pah 已提交
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 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
    el.setStyle(normalStyle);
    el.style.strokeNoScale = true;
    el.ensureState('emphasis').style = emphasisStyle;
    el.ensureState('select').style = selectStyle;
    el.ensureState('blur').style = blurStyle;
}

function resetLabelForRegion(
    viewBuildCtx: ViewBuildContext,
    el: Element,
    regionName: string,
    regionModel: RegionModel,
    mapOrGeoModel: MapOrGeoModel,
    // Exist only if `viewBuildCtx.data` exists.
    dataIdx: number,
    labelXY: number[]
): void {
    const data = viewBuildCtx.data;
    const isGeo = viewBuildCtx.isGeo;

    let showLabel = false;
    for (let i = 0; i < DISPLAY_STATES.length; i++) {
        const stateName = DISPLAY_STATES[i];
        // @ts-ignore FIXME:TS fix the "compatible with each other"?
        if (regionModel.get(
            stateName === 'normal' ? ['label', 'show'] : [stateName, 'label', 'show']
        )) {
            showLabel = true;
            break;
        }
    }

    const isDataNaN = data && isNaN(data.get(data.mapDimension('value'), dataIdx) as number);
    const itemLayout = data && data.getItemLayout(dataIdx);

    // In the following cases label will be drawn
    // 1. In map series and data value is NaN
    // 2. In geo component
    // 3. Region has no series legendSymbol, which will be add a showLabel flag in mapSymbolLayout
    if (
        ((isGeo || isDataNaN) && showLabel)
        || (itemLayout && itemLayout.showLabel)
    ) {
        const query = !isGeo ? dataIdx : regionName;
        let labelFetcher;

        // Consider dataIdx not found.
        if (!data || dataIdx >= 0) {
            labelFetcher = mapOrGeoModel;
        }

        const textEl = new graphic.Text({
            x: labelXY[0],
            y: labelXY[1],
            z2: 10,
            silent: true
        });
        textEl.afterUpdate = labelTextAfterUpdate;

        const labelStateModels = getLabelStatesModels(regionModel);
        setLabelStyle<typeof query>(
            textEl,
            labelStateModels,
            {
                labelFetcher: labelFetcher,
                labelDataIndex: query,
                defaultText: regionName
            },
            { normal: {
                align: 'center',
                verticalAlign: 'middle'
            } }
        );

        // PENDING: use `setLabelStyle` entirely.
        el.setTextContent(textEl);

        const textConfig = createTextConfig(labelStateModels.normal, null, false);
        // Need to apply the `translate`.
        textConfig.local = true;
        textConfig.insideFill = textEl.style.fill;
        el.setTextConfig(textConfig);

        for (let i = 0; i < SPECIAL_STATES.length; i++) {
            const stateName = SPECIAL_STATES[i];
            // Hover label only work when `emphasis` state ensured.
            const state = el.ensureState(stateName);

            const textConfig = state.textConfig = createTextConfig(labelStateModels[stateName], null, true);
            // Need to apply the `translate`.
            textConfig.local = true;
            textConfig.insideFill = textEl.style.fill;
        }

        (el as ECElement).disableLabelAnimation = true;
    }
    else {
        el.removeTextContent();
        el.removeTextConfig();
        (el as ECElement).disableLabelAnimation = null;
    }
}

function resetEventTriggerForRegion(
    viewBuildCtx: ViewBuildContext,
    eventTrigger: Element,
    regionName: string,
    regionModel: RegionModel,
    mapOrGeoModel: MapOrGeoModel,
    // Exist only if `viewBuildCtx.data` exists.
    dataIdx: number
): void {
    // setItemGraphicEl, setHoverStyle after all polygons and labels
    // are added to the rigionGroup
    if (viewBuildCtx.data) {
        // FIXME: when series-map use a SVG map, and there are duplicated name specified
        // on different SVG elements, after `data.setItemGraphicEl(...)`:
        // (1) all of them will be mounted with `dataIndex`, `seriesIndex`, so that tooltip
        // can be triggered only mouse hover. That's correct.
        // (2) only the last element will be kept in `data`, so that if trigger tooltip
        // by `dispatchAction`, only the last one can be found and triggered. That might be
        // not correct. We will fix it in future if anyone demanding that.
        viewBuildCtx.data.setItemGraphicEl(dataIdx, eventTrigger);
    }
    // series-map will not trigger "geoselectchange" no matter it is
    // based on a declared geo component. Becuause series-map will
    // trigger "selectchange". If it trigger both the two events,
    // If users call `chart.dispatchAction({type: 'toggleSelect'})`,
    // it not easy to also fire event "geoselectchanged".
    else {
        // Package custom mouse event for geo component
        getECData(eventTrigger).eventData = {
            componentType: 'geo',
            componentIndex: mapOrGeoModel.componentIndex,
            geoIndex: mapOrGeoModel.componentIndex,
            name: regionName,
            region: (regionModel && regionModel.option) || {}
        };
    }
}

function resetTooltipForRegion(
    viewBuildCtx: ViewBuildContext,
    el: Element,
    regionName: string,
    regionModel: RegionModel,
    mapOrGeoModel: MapOrGeoModel
): void {
    if (!viewBuildCtx.data) {
        graphic.setTooltipConfig({
            el: el,
            componentModel: mapOrGeoModel,
            itemName: regionName,
            // @ts-ignore FIXME:TS fix the "compatible with each other"?
            itemTooltipOption: regionModel.get('tooltip')
        });
    }
}

function resetStateTriggerForRegion(
    viewBuildCtx: ViewBuildContext,
    el: Element,
    regionName: string,
    regionModel: RegionModel,
    mapOrGeoModel: MapOrGeoModel
): InnerFocus {
    // @ts-ignore FIXME:TS fix the "compatible with each other"?
    el.highDownSilentOnTouch = !!mapOrGeoModel.get('selectedMode');
    // @ts-ignore FIXME:TS fix the "compatible with each other"?
    const emphasisModel = regionModel.getModel('emphasis');
    const focus = emphasisModel.get('focus');
    enableHoverEmphasis(
        el, focus, emphasisModel.get('blurScope')
    );
    if (viewBuildCtx.isGeo) {
        enableComponentHighDownFeatures(el, mapOrGeoModel as GeoModel, regionName);
    }

    return focus;
1
100pah 已提交
815 816
}

817
export default MapDraw;
1
100pah 已提交
818 819 820


// @ts-ignore FIXME:TS fix the "compatible with each other"?