-
Notifications
You must be signed in to change notification settings - Fork 50
/
index.js
94 lines (75 loc) · 2.21 KB
/
index.js
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
// @flow
import { PureComponent, createElement } from 'react';
import type MapboxMap from 'mapbox-gl/src/ui/map';
import type { FilterSpecification } from 'mapbox-gl/src/style-spec/types';
import MapContext from '../MapContext';
import isArraysEqual from '../../utils/isArraysEqual';
type Props = {|
/** Mapbox GL Layer id */
layerId: string,
/**
* The filter, conforming to the Mapbox Style Specification's
* filter definition. (see https://docs.mapbox.com/mapbox-gl-js/style-spec/#other-filter)
* If null or undefined is provided, the function removes any existing filter
* from the layer.
* */
filter: FilterSpecification,
/**
* Whether to check if the filter conforms to the Mapbox GL
* Style Specification. Disabling validation is a performance optimization
* that should only be used if you have previously validated the values you
* will be passing to this function.
* */
validate?: boolean
|};
class Filter extends PureComponent<Props> {
_map: MapboxMap;
static defaultProps = {
validate: true
};
componentDidMount() {
this._setFilter();
}
componentDidUpdate(prevProps: Props) {
const prevFilter = prevProps.filter;
const prevValidate = prevProps.validate;
const { filter, validate } = this.props;
const shouldUpdate =
!isArraysEqual(prevFilter, filter) || prevValidate !== validate;
if (shouldUpdate) {
this._setFilter();
}
}
componentWillUnmount() {
if (!this._map || !this._map.getStyle()) {
return;
}
const { layerId } = this.props;
const targetLayer = this._map.getLayer(layerId);
if (targetLayer === undefined) {
return;
}
this._map.setFilter(layerId, undefined);
}
_setFilter() {
const { layerId, filter, validate } = this.props;
const targetLayer = this._map.getLayer(layerId);
if (targetLayer === undefined) {
return;
}
if (!Array.isArray(filter)) {
this._map.setFilter(layerId, undefined);
} else {
this._map.setFilter(layerId, filter, { validate });
}
}
render() {
return createElement(MapContext.Consumer, {}, (map) => {
if (map) {
this._map = map;
}
return null;
});
}
}
export default Filter;