-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
map-container.tsx
1130 lines (1011 loc) · 36.3 KB
/
map-container.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
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
338
339
340
341
342
343
344
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
398
399
400
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
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
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
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
// libraries
import React, {Component, createRef, useMemo} from 'react';
import styled, {withTheme} from 'styled-components';
import {Map, MapRef} from 'react-map-gl';
import {PickInfo} from '@deck.gl/core/lib/deck';
import DeckGL from '@deck.gl/react';
import {createSelector, Selector} from 'reselect';
import {useDroppable} from '@dnd-kit/core';
import debounce from 'lodash.debounce';
import {VisStateActions, MapStateActions, UIStateActions} from '@kepler.gl/actions';
// components
import MapPopoverFactory from './map/map-popover';
import MapControlFactory from './map/map-control';
import {
StyledMapContainer,
StyledAttrbution,
EndHorizontalFlexbox
} from './common/styled-components';
import EditorFactory from './editor/editor';
// utils
import {
generateMapboxLayers,
updateMapboxLayers,
LayerBaseConfig,
VisualChannelDomain,
EditorLayerUtils,
AggregatedBin
} from '@kepler.gl/layers';
import {MapState, MapControls, Viewport, SplitMap, SplitMapLayers} from '@kepler.gl/types';
import {
errorNotification,
setLayerBlending,
isStyleUsingMapboxTiles,
transformRequest,
observeDimensions,
unobserveDimensions,
hasMobileWidth,
getMapLayersFromSplitMaps,
onViewPortChange,
getViewportFromMapState,
normalizeEvent,
rgbToHex,
computeDeckEffects,
getApplicationConfig
} from '@kepler.gl/utils';
import {breakPointValues} from '@kepler.gl/styles';
// default-settings
import {
FILTER_TYPES,
GEOCODER_LAYER_ID,
THROTTLE_NOTIFICATION_TIME,
DEFAULT_PICKING_RADIUS,
NO_MAP_ID,
EMPTY_MAPBOX_STYLE,
DROPPABLE_MAP_CONTAINER_TYPE
} from '@kepler.gl/constants';
// Contexts
import {MapViewStateContext} from './map-view-state-context';
import ErrorBoundary from './common/error-boundary';
import {DatasetAttribution} from './types';
import {LOCALE_CODES} from '@kepler.gl/localization';
import {MapView} from '@deck.gl/core';
import {
MapStyle,
computeDeckLayers,
getLayerHoverProp,
LayerHoverProp,
prepareLayersForDeck,
prepareLayersToRender,
LayersToRender
} from '@kepler.gl/reducers';
import {VisState} from '@kepler.gl/schemas';
// Debounce the propagation of viewport change and mouse moves to redux store.
// This is to avoid too many renders of other components when the map is
// being panned/zoomed (leading to laggy basemap/deck syncing).
const DEBOUNCE_VIEWPORT_PROPAGATE = 10;
const DEBOUNCE_MOUSE_MOVE_PROPAGATE = 10;
/** @type {{[key: string]: React.CSSProperties}} */
const MAP_STYLE: {[key: string]: React.CSSProperties} = {
container: {
display: 'inline-block',
position: 'relative',
width: '100%',
height: '100%'
},
top: {
position: 'absolute',
top: 0,
width: '100%',
height: '100%',
pointerEvents: 'none'
}
};
const LOCALE_CODES_ARRAY = Object.keys(LOCALE_CODES);
interface StyledMapContainerProps {
mixBlendMode?: string;
}
const StyledMap = styled(StyledMapContainer)<StyledMapContainerProps>(
({mixBlendMode = 'normal'}) => `
#default-deckgl-overlay {
mix-blend-mode: ${mixBlendMode};
};
*[${getApplicationConfig().mapLibCssClass}-children] {
position: absolute;
}
`
);
const MAPBOXGL_STYLE_UPDATE = 'style.load';
const MAPBOXGL_RENDER = 'render';
const nop = () => {
return;
};
const MapLibLogo = () => (
<div className="attrition-logo">
Basemap by:
<a
style={{marginLeft: '5px'}}
className={`${getApplicationConfig().mapLibCssClass}-ctrl-logo`}
target="_blank"
rel="noopener noreferrer"
href={getApplicationConfig().mapLibUrl}
aria-label={`${getApplicationConfig().mapLibName} logo`}
/>
</div>
);
interface StyledDroppableProps {
isOver: boolean;
}
const StyledDroppable = styled.div<StyledDroppableProps>`
background-color: ${props => (props.isOver ? props.theme.dndOverBackgroundColor : 'none')};
width: 100%;
height: 100%;
position: absolute;
pointer-events: none;
z-index: 1;
`;
export const isSplitSelector = props =>
props.visState.splitMaps && props.visState.splitMaps.length > 1;
export const Droppable = ({containerId}) => {
const {isOver, setNodeRef} = useDroppable({
id: containerId,
data: {type: DROPPABLE_MAP_CONTAINER_TYPE, index: containerId},
disabled: !containerId
});
return <StyledDroppable ref={setNodeRef} isOver={isOver} />;
};
interface StyledDatasetAttributionsContainerProps {
isPalm: boolean;
}
const StyledDatasetAttributionsContainer = styled.div<StyledDatasetAttributionsContainerProps>`
max-width: ${props => (props.isPalm ? '130px' : '180px')};
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
color: ${props => props.theme.labelColor};
margin-right: 2px;
line-height: ${props => (props.isPalm ? '1em' : '1.4em')};
&:hover {
white-space: inherit;
}
`;
const DatasetAttributions = ({
datasetAttributions,
isPalm
}: {
datasetAttributions: DatasetAttribution[];
isPalm: boolean;
}) => (
<>
{datasetAttributions?.length ? (
<StyledDatasetAttributionsContainer isPalm={isPalm}>
{datasetAttributions.map((ds, idx) => (
<a
{...(ds.url ? {href: ds.url} : null)}
target="_blank"
rel="noopener noreferrer"
key={`${ds.title}_${idx}`}
>
{ds.title}
{idx !== datasetAttributions.length - 1 ? ', ' : null}
</a>
))}
</StyledDatasetAttributionsContainer>
) : null}
</>
);
export const Attribution: React.FC<{
showMapboxLogo: boolean;
showOsmBasemapAttribution: boolean;
datasetAttributions: DatasetAttribution[];
}> = ({showMapboxLogo = true, showOsmBasemapAttribution = false, datasetAttributions}) => {
const isPalm = hasMobileWidth(breakPointValues);
const memoizedComponents = useMemo(() => {
if (!showMapboxLogo) {
return (
<StyledAttrbution>
<EndHorizontalFlexbox>
<DatasetAttributions datasetAttributions={datasetAttributions} isPalm={isPalm} />
{showOsmBasemapAttribution ? (
<div className="attrition-link">
{datasetAttributions?.length ? <span className="pipe-separator">|</span> : null}
<a
href="http://www.openstreetmap.org/copyright"
target="_blank"
rel="noopener noreferrer"
>
© OpenStreetMap
</a>
</div>
) : null}
</EndHorizontalFlexbox>
</StyledAttrbution>
);
}
return (
<StyledAttrbution>
<EndHorizontalFlexbox>
<DatasetAttributions datasetAttributions={datasetAttributions} isPalm={isPalm} />
<div className="attrition-link">
{datasetAttributions?.length ? <span className="pipe-separator">|</span> : null}
{isPalm ? <MapLibLogo /> : null}
<a href="https://kepler.gl/policy/" target="_blank" rel="noopener noreferrer">
© kepler.gl |{' '}
</a>
{!isPalm ? <MapLibLogo /> : null}
</div>
</EndHorizontalFlexbox>
</StyledAttrbution>
);
}, [showMapboxLogo, showOsmBasemapAttribution, datasetAttributions, isPalm]);
return memoizedComponents;
};
MapContainerFactory.deps = [MapPopoverFactory, MapControlFactory, EditorFactory];
type MapboxStyle = string | object | undefined;
type PropSelector<R> = Selector<MapContainerProps, R>;
type GetMapRef = ReturnType<ReturnType<typeof getApplicationConfig>['getMap']>;
export interface MapContainerProps {
visState: VisState;
mapState: MapState;
mapControls: MapControls;
mapStyle: {bottomMapStyle?: MapboxStyle; topMapStyle?: MapboxStyle} & MapStyle;
mapboxApiAccessToken: string;
mapboxApiUrl: string;
visStateActions: typeof VisStateActions;
mapStateActions: typeof MapStateActions;
uiStateActions: typeof UIStateActions;
// optional
primary?: boolean; // primary one will be reporting its size to appState
readOnly?: boolean;
isExport?: boolean;
// onMapStyleLoaded?: (map: maplibregl.Map | ReturnType<MapRef['getMap']> | null) => void;
onMapStyleLoaded?: (map: GetMapRef | null) => void;
onMapRender?: (map: GetMapRef | null) => void;
getMapboxRef?: (mapbox?: MapRef | null, index?: number) => void;
index?: number;
deleteMapLabels?: (containerId: string, layerId: string) => void;
containerId?: number;
locale?: any;
theme?: any;
editor?: any;
MapComponent?: typeof Map;
deckGlProps?: any;
onDeckInitialized?: (a: any, b: any) => void;
onViewStateChange?: (viewport: Viewport) => void;
topMapContainerProps: any;
bottomMapContainerProps: any;
transformRequest?: any;
datasetAttributions?: DatasetAttribution[];
generateMapboxLayers?: typeof generateMapboxLayers;
generateDeckGLLayers?: typeof computeDeckLayers;
onMouseMove?: (event: React.MouseEvent & {lngLat?: [number, number]}) => void;
children?: React.ReactNode;
deckRenderCallbacks?: {
onDeckLoad?: () => void;
onDeckRender?: (deckProps: Record<string, unknown>) => Record<string, unknown> | null;
onDeckAfterRender?: (deckProps: Record<string, unknown>) => any;
};
}
export default function MapContainerFactory(
MapPopover: ReturnType<typeof MapPopoverFactory>,
MapControl: ReturnType<typeof MapControlFactory>,
Editor: ReturnType<typeof EditorFactory>
): React.ComponentType<MapContainerProps> {
class MapContainer extends Component<MapContainerProps> {
displayName = 'MapContainer';
static contextType = MapViewStateContext;
declare context: React.ContextType<typeof MapViewStateContext>;
static defaultProps = {
MapComponent: Map,
deckGlProps: {},
index: 0,
primary: true
};
constructor(props) {
super(props);
}
state = {
// Determines whether attribution should be visible based the result of loading the map style
showMapboxAttribution: true
};
componentDidMount() {
if (!this._ref.current) {
return;
}
observeDimensions(this._ref.current, this._handleResize);
}
componentWillUnmount() {
// unbind mapboxgl event listener
if (this._map) {
this._map?.off(MAPBOXGL_STYLE_UPDATE, nop);
this._map?.off(MAPBOXGL_RENDER, nop);
}
if (!this._ref.current) {
return;
}
unobserveDimensions(this._ref.current);
}
_deck: any = null;
_map: GetMapRef | null = null;
_ref = createRef<HTMLDivElement>();
_deckGLErrorsElapsed: {[id: string]: number} = {};
previousLayers = {
// [layers.id]: mapboxLayerConfig
};
_handleResize = dimensions => {
const {primary, index} = this.props;
if (primary) {
const {mapStateActions} = this.props;
if (dimensions && dimensions.width > 0 && dimensions.height > 0) {
mapStateActions.updateMap(dimensions, index);
}
}
};
layersSelector: PropSelector<VisState['layers']> = props => props.visState.layers;
layerDataSelector: PropSelector<VisState['layers']> = props => props.visState.layerData;
splitMapSelector: PropSelector<SplitMap[]> = props => props.visState.splitMaps;
splitMapIndexSelector: PropSelector<number | undefined> = props => props.index;
mapLayersSelector: PropSelector<SplitMapLayers | null | undefined> = createSelector(
this.splitMapSelector,
this.splitMapIndexSelector,
getMapLayersFromSplitMaps
);
layerOrderSelector: PropSelector<VisState['layerOrder']> = props => props.visState.layerOrder;
layersToRenderSelector: PropSelector<LayersToRender> = createSelector(
this.layersSelector,
this.layerDataSelector,
this.mapLayersSelector,
prepareLayersToRender
);
layersForDeckSelector = createSelector(
this.layersSelector,
this.layerDataSelector,
prepareLayersForDeck
);
filtersSelector = props => props.visState.filters;
polygonFiltersSelector = createSelector(this.filtersSelector, filters =>
filters.filter(f => f.type === FILTER_TYPES.polygon && f.enabled !== false)
);
featuresSelector = props => props.visState.editor.features;
selectedFeatureSelector = props => props.visState.editor.selectedFeature;
featureCollectionSelector = createSelector(
this.polygonFiltersSelector,
this.featuresSelector,
(polygonFilters, features) => ({
type: 'FeatureCollection',
features: features.concat(polygonFilters.map(f => f.value))
})
);
// @ts-ignore - No overload matches this call
selectedPolygonIndexSelector = createSelector(
this.featureCollectionSelector,
this.selectedFeatureSelector,
(collection, selectedFeature) =>
collection.features.findIndex(f => f.id === selectedFeature?.id)
);
selectedFeatureIndexArraySelector = createSelector(
(value: number) => value,
value => {
return value < 0 ? [] : [value];
}
);
generateMapboxLayerMethodSelector = props => props.generateMapboxLayers ?? generateMapboxLayers;
mapboxLayersSelector = createSelector(
this.layersSelector,
this.layerDataSelector,
this.layerOrderSelector,
this.layersToRenderSelector,
this.generateMapboxLayerMethodSelector,
(layer, layerData, layerOrder, layersToRender, generateMapboxLayerMethod) =>
generateMapboxLayerMethod(layer, layerData, layerOrder, layersToRender)
);
// merge in a background-color style if the basemap choice is NO_MAP_ID
// used by <StyledMap> inline style prop
mapStyleTypeSelector = props => props.mapStyle.styleType;
mapStyleBackgroundColorSelector = props => props.mapStyle.backgroundColor;
styleSelector = createSelector(
this.mapStyleTypeSelector,
this.mapStyleBackgroundColorSelector,
(styleType, backgroundColor) => ({
...MAP_STYLE.container,
...(styleType === NO_MAP_ID ? {backgroundColor: rgbToHex(backgroundColor)} : {})
})
);
/* component private functions */
_onCloseMapPopover = () => {
this.props.visStateActions.onLayerClick(null);
};
_onLayerHover = (_idx: number, info: PickInfo<any> | null) => {
this.props.visStateActions.onLayerHover(info, this.props.index);
};
_onLayerSetDomain = (
idx: number,
value: {domain: VisualChannelDomain; aggregatedBins: AggregatedBin[]}
) => {
this.props.visStateActions.layerConfigChange(this.props.visState.layers[idx], {
colorDomain: value.domain,
aggregatedBins: value.aggregatedBins
} as Partial<LayerBaseConfig>);
};
_onLayerFilteredItemsChange = (idx, event) => {
this.props.visStateActions.layerFilteredItemsChange(this.props.visState.layers[idx], event);
};
_handleMapToggleLayer = layerId => {
const {index: mapIndex = 0, visStateActions} = this.props;
visStateActions.toggleLayerForMap(mapIndex, layerId);
};
_onMapboxStyleUpdate = update => {
// force refresh mapboxgl layers
this.previousLayers = {};
this._updateMapboxLayers();
if (update && update.style) {
// No attributions are needed if the style doesn't reference Mapbox sources
this.setState({showMapboxAttribution: isStyleUsingMapboxTiles(update.style)});
}
if (typeof this.props.onMapStyleLoaded === 'function') {
this.props.onMapStyleLoaded(this._map);
}
};
_setMapRef = mapRef => {
if (!this._map && mapRef) {
this._map = getApplicationConfig().getMap(mapRef);
// i noticed in certain context we don't access the actual map element
if (!this._map) {
return;
}
// bind mapboxgl event listener
this._map.on(MAPBOXGL_STYLE_UPDATE, this._onMapboxStyleUpdate);
this._map.on(MAPBOXGL_RENDER, () => {
if (typeof this.props.onMapRender === 'function') {
this.props.onMapRender(this._map);
}
});
}
if (this.props.getMapboxRef) {
// The parent component can gain access to our MapboxGlMap by
// providing this callback. Note that 'mapbox' will be null when the
// ref is unset (e.g. when a split map is closed).
this.props.getMapboxRef(mapRef, this.props.index);
}
};
_onDeckInitialized(gl) {
if (this.props.onDeckInitialized) {
this.props.onDeckInitialized(this._deck, gl);
}
}
/**
* 1) Allow effects only for the first view.
* 2) Prevent effect:preRender call without valid generated viewports.
* @param viewIndex View index.
* @returns Returns true if effects can be used.
*/
_isOKToRenderEffects(viewIndex?: number): boolean {
return !viewIndex && Boolean(this._deck?.viewManager?._viewports?.length);
}
_onBeforeRender = ({gl}) => {
setLayerBlending(gl, this.props.visState.layerBlending);
};
_onDeckError = (error, layer) => {
const errorMessage = error?.message || 'unknown-error';
const layerMessage = layer?.id ? ` in ${layer.id} layer` : '';
const errorMessageFull =
errorMessage === 'WebGL context is lost'
? 'Your GPU was disconnected. This can happen if your computer goes to sleep. It can also occur for other reasons, such as if you are running too many GPU applications.'
: `An error in deck.gl: ${errorMessage}${layerMessage}.`;
// Throttle error notifications, as React doesn't like too many state changes from here.
const lastShown = this._deckGLErrorsElapsed[errorMessageFull];
if (!lastShown || lastShown < Date.now() - THROTTLE_NOTIFICATION_TIME) {
this._deckGLErrorsElapsed[errorMessageFull] = Date.now();
// Mark layer as invalid
let extraLayerMessage = '';
const {visStateActions} = this.props;
if (layer) {
let topMostLayer = layer;
while (topMostLayer.parent) {
topMostLayer = topMostLayer.parent;
}
if (topMostLayer.props?.id) {
visStateActions.layerSetIsValid(topMostLayer, false);
extraLayerMessage = 'The layer has been disabled and highlighted.';
}
}
// Create new error notification or update existing one with same id.
// Update is required to preserve the order of notifications as they probably are going to "jump" based on order of errors.
const {uiStateActions} = this.props;
uiStateActions.addNotification(
errorNotification({
message: `${errorMessageFull} ${extraLayerMessage}`,
id: errorMessageFull // treat the error message as id
})
);
}
};
/* component render functions */
/* eslint-disable complexity */
_renderMapPopover() {
// this check is for limiting the display of the `<MapPopover>` to the `<MapContainer>` the user is interacting with
// the DeckGL onHover event handler adds a `mapIndex` property which is available in the `hoverInfo` object of `visState`
if (this.props.index !== this.props.visState.hoverInfo?.mapIndex) {
return null;
}
// TODO: move this into reducer so it can be tested
const {
mapState,
visState: {
hoverInfo,
clicked,
datasets,
interactionConfig,
animationConfig,
layers,
mousePos: {mousePosition, coordinate, pinned}
}
} = this.props;
const layersToRender = this.layersToRenderSelector(this.props);
if (!mousePosition || !interactionConfig.tooltip) {
return null;
}
const layerHoverProp = getLayerHoverProp({
animationConfig,
interactionConfig,
hoverInfo,
layers,
layersToRender,
datasets
});
const compareMode = interactionConfig.tooltip.config
? interactionConfig.tooltip.config.compareMode
: false;
let pinnedPosition = {x: 0, y: 0};
let layerPinnedProp: LayerHoverProp | null = null;
if (pinned || clicked) {
// project lnglat to screen so that tooltip follows the object on zoom
const viewport = getViewportFromMapState(mapState);
const lngLat = clicked ? clicked.coordinate : pinned.coordinate;
pinnedPosition = this._getHoverXY(viewport, lngLat);
layerPinnedProp = getLayerHoverProp({
animationConfig,
interactionConfig,
hoverInfo: clicked,
layers,
layersToRender,
datasets
});
if (layerHoverProp && layerPinnedProp) {
layerHoverProp.primaryData = layerPinnedProp.data;
layerHoverProp.compareType = interactionConfig.tooltip.config.compareType;
}
}
const commonProp = {
onClose: this._onCloseMapPopover,
zoom: mapState.zoom,
container: this._deck ? this._deck.canvas : undefined
};
return (
<ErrorBoundary>
{layerPinnedProp && (
<MapPopover
{...pinnedPosition}
{...commonProp}
layerHoverProp={layerPinnedProp}
coordinate={interactionConfig.coordinate.enabled && (pinned || {}).coordinate}
frozen={true}
isBase={compareMode}
onSetFeatures={this.props.visStateActions.setFeatures}
setSelectedFeature={this.props.visStateActions.setSelectedFeature}
// @ts-ignore Argument of type 'Readonly<MapContainerProps>' is not assignable to parameter of type 'never'
featureCollection={this.featureCollectionSelector(this.props)}
/>
)}
{layerHoverProp && (!layerPinnedProp || compareMode) && (
<MapPopover
x={mousePosition[0]}
y={mousePosition[1]}
{...commonProp}
layerHoverProp={layerHoverProp}
frozen={false}
coordinate={interactionConfig.coordinate.enabled && coordinate}
onSetFeatures={this.props.visStateActions.setFeatures}
setSelectedFeature={this.props.visStateActions.setSelectedFeature}
// @ts-ignore Argument of type 'Readonly<MapContainerProps>' is not assignable to parameter of type 'never'
featureCollection={this.featureCollectionSelector(this.props)}
/>
)}
</ErrorBoundary>
);
}
/* eslint-enable complexity */
_getHoverXY(viewport, lngLat) {
const screenCoord = !viewport || !lngLat ? null : viewport.project(lngLat);
return screenCoord && {x: screenCoord[0], y: screenCoord[1]};
}
_renderDeckOverlay(
layersForDeck,
options: {primaryMap: boolean; isInteractive?: boolean; children?: React.ReactNode} = {
primaryMap: false
}
) {
const {
mapStyle,
visState,
mapState,
visStateActions,
mapboxApiAccessToken,
mapboxApiUrl,
deckGlProps,
index,
mapControls,
deckRenderCallbacks,
theme,
generateDeckGLLayers,
onMouseMove
} = this.props;
const {hoverInfo, editor} = visState;
const {primaryMap, isInteractive, children} = options;
// disable double click zoom when editor is in any draw mode
const {mapDraw} = mapControls;
const {active: editorMenuActive = false} = mapDraw || {};
const isEditorDrawingMode = EditorLayerUtils.isDrawingActive(editorMenuActive, editor.mode);
const internalViewState = this.context?.getInternalViewState(index);
const internalMapState = {...mapState, ...internalViewState};
const viewport = getViewportFromMapState(internalMapState);
const editorFeatureSelectedIndex = this.selectedPolygonIndexSelector(this.props);
const {setFeatures, onLayerClick, setSelectedFeature} = visStateActions;
const generateDeckGLLayersMethod = generateDeckGLLayers ?? computeDeckLayers;
const deckGlLayers = generateDeckGLLayersMethod(
{
visState,
mapState: internalMapState,
mapStyle
},
{
mapIndex: index,
primaryMap,
mapboxApiAccessToken,
mapboxApiUrl,
layersForDeck,
editorInfo: primaryMap
? {
editor,
editorMenuActive,
onSetFeatures: setFeatures,
setSelectedFeature,
// @ts-ignore Argument of type 'Readonly<MapContainerProps>' is not assignable to parameter of type 'never'
featureCollection: this.featureCollectionSelector(this.props),
selectedFeatureIndexes: this.selectedFeatureIndexArraySelector(
// @ts-ignore Argument of type 'unknown' is not assignable to parameter of type 'number'.
editorFeatureSelectedIndex
),
viewport
}
: undefined
},
{
onLayerHover: this._onLayerHover,
onSetLayerDomain: this._onLayerSetDomain,
onFilteredItemsChange: this._onLayerFilteredItemsChange
},
deckGlProps
);
const extraDeckParams: {
getTooltip?: (info: any) => object | null;
getCursor?: ({isDragging}: {isDragging: boolean}) => string;
} = {};
if (primaryMap) {
extraDeckParams.getTooltip = info =>
EditorLayerUtils.getTooltip(info, {
editorMenuActive,
editor,
theme
});
extraDeckParams.getCursor = ({isDragging}: {isDragging: boolean}) => {
const editorCursor = EditorLayerUtils.getCursor({
editorMenuActive,
editor,
hoverInfo
});
if (editorCursor) return editorCursor;
if (isDragging) return 'grabbing';
if (hoverInfo?.layer) return 'pointer';
return 'grab';
};
}
const effects = this._isOKToRenderEffects(index)
? computeDeckEffects({visState, mapState})
: [];
const views = deckGlProps?.views
? deckGlProps?.views()
: new MapView({legacyMeterSizes: true});
let allDeckGlProps = {
...deckGlProps,
pickingRadius: DEFAULT_PICKING_RADIUS,
views,
layers: deckGlLayers,
effects
};
if (typeof deckRenderCallbacks?.onDeckRender === 'function') {
allDeckGlProps = deckRenderCallbacks.onDeckRender(allDeckGlProps);
if (!allDeckGlProps) {
// if onDeckRender returns null, do not render deck.gl
return null;
}
}
return (
<div
{...(isInteractive
? {
onMouseMove: primaryMap
? event => {
onMouseMove?.(event);
this._onMouseMoveDebounced(event, viewport);
}
: undefined
}
: {style: {pointerEvents: 'none'}})}
>
<DeckGL
id="default-deckgl-overlay"
onLoad={() => {
if (typeof deckRenderCallbacks?.onDeckLoad === 'function') {
deckRenderCallbacks.onDeckLoad();
}
}}
{...allDeckGlProps}
controller={
isInteractive
? {
doubleClickZoom: !isEditorDrawingMode,
dragRotate: this.props.mapState.dragRotate
}
: false
}
initialViewState={internalViewState}
onBeforeRender={this._onBeforeRender}
onViewStateChange={isInteractive ? this._onViewportChange : undefined}
{...extraDeckParams}
onHover={
isInteractive
? data => {
const res = EditorLayerUtils.onHover(data, {
editorMenuActive,
editor,
hoverInfo
});
if (res) return;
this._onLayerHoverDebounced(data, index);
}
: null
}
onClick={(data, event) => {
// @ts-ignore
normalizeEvent(event.srcEvent, viewport);
const res = EditorLayerUtils.onClick(data, event, {
editorMenuActive,
editor,
onLayerClick,
setSelectedFeature,
mapIndex: index
});
if (res) return;
visStateActions.onLayerClick(data);
}}
onError={this._onDeckError}
ref={comp => {
// @ts-ignore
if (comp && comp.deck && !this._deck) {
// @ts-ignore
this._deck = comp.deck;
}
}}
onWebGLInitialized={gl => this._onDeckInitialized(gl)}
onAfterRender={() => {
if (typeof deckRenderCallbacks?.onDeckAfterRender === 'function') {
deckRenderCallbacks.onDeckAfterRender(allDeckGlProps);
}
}}
>
{children}
</DeckGL>
</div>
);
}
_updateMapboxLayers() {
const mapboxLayers = this.mapboxLayersSelector(this.props);
if (!Object.keys(mapboxLayers).length && !Object.keys(this.previousLayers).length) {
return;
}
updateMapboxLayers(this._map, mapboxLayers, this.previousLayers);
this.previousLayers = mapboxLayers;
}
_renderMapboxOverlays() {
if (this._map && this._map.isStyleLoaded()) {
this._updateMapboxLayers();
}
}
_onViewportChangePropagateDebounced = debounce(() => {
const viewState = this.context?.getInternalViewState(this.props.index);
onViewPortChange(
viewState,
this.props.mapStateActions.updateMap,
this.props.onViewStateChange,
this.props.primary,
this.props.index
);
}, DEBOUNCE_VIEWPORT_PROPAGATE);
_onViewportChange = viewport => {
const {viewState} = viewport;
if (this.props.isExport) {
// Image export map shouldn't be interactive (otherwise this callback can
// lead to inadvertent changes to the state of the main map)
return;
}
const {setInternalViewState} = this.context;
setInternalViewState(viewState, this.props.index);
this._onViewportChangePropagateDebounced();
};
_onLayerHoverDebounced = debounce((data, index) => {
this.props.visStateActions.onLayerHover(data, index);
}, DEBOUNCE_MOUSE_MOVE_PROPAGATE);
_onMouseMoveDebounced = debounce((event, viewport) => {
this.props.visStateActions.onMouseMove(normalizeEvent(event, viewport));
}, DEBOUNCE_MOUSE_MOVE_PROPAGATE);
_toggleMapControl = panelId => {
const {index, uiStateActions} = this.props;
uiStateActions.toggleMapControl(panelId, Number(index));
};
/* eslint-disable complexity */
_renderMap() {
const {
visState,
mapState,
mapStyle,
mapStateActions,
MapComponent = Map,
mapboxApiAccessToken,
mapboxApiUrl,
mapControls,
isExport,
locale,
uiStateActions,
visStateActions,
index,
primary,
bottomMapContainerProps,
topMapContainerProps,
theme,
datasetAttributions = [],
containerId = 0
} = this.props;
const {layers, datasets, editor, interactionConfig} = visState;
const layersToRender = this.layersToRenderSelector(this.props);
const layersForDeck = this.layersForDeckSelector(this.props);
// Current style can be a custom style, from which we pull the mapbox API acccess token
const currentStyle = mapStyle.mapStyles?.[mapStyle.styleType];
const internalViewState = this.context?.getInternalViewState(index);
const mapProps = {
...internalViewState,
preserveDrawingBuffer: true,
mapboxAccessToken: currentStyle?.accessToken || mapboxApiAccessToken,
baseApiUrl: mapboxApiUrl,
mapLib: getApplicationConfig().getMapLib(),
transformRequest:
this.props.transformRequest ||
transformRequest(currentStyle?.accessToken || mapboxApiAccessToken)
};