@maplibre/maplibre-react-native 9.1.0 → 10.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/.eslintrc.js +10 -2
  2. package/.husky/pre-commit +5 -0
  3. package/.yarn/plugins/@yarnpkg/plugin-typescript.cjs +9 -0
  4. package/.yarn/sdks/eslint/bin/eslint.js +20 -0
  5. package/.yarn/sdks/eslint/lib/api.js +20 -0
  6. package/.yarn/sdks/eslint/package.json +6 -0
  7. package/.yarn/sdks/integrations.yml +5 -0
  8. package/.yarn/sdks/prettier/index.js +20 -0
  9. package/.yarn/sdks/prettier/package.json +6 -0
  10. package/.yarn/sdks/typescript/bin/tsc +20 -0
  11. package/.yarn/sdks/typescript/bin/tsserver +20 -0
  12. package/.yarn/sdks/typescript/lib/tsc.js +20 -0
  13. package/.yarn/sdks/typescript/lib/tsserver.js +225 -0
  14. package/.yarn/sdks/typescript/lib/tsserverlibrary.js +225 -0
  15. package/.yarn/sdks/typescript/lib/typescript.js +20 -0
  16. package/.yarn/sdks/typescript/package.json +6 -0
  17. package/CHANGELOG.md +18 -0
  18. package/android/rctmgl/build.gradle +7 -7
  19. package/android/rctmgl/src/main/java/com/mapbox/rctmgl/location/LocationManager.java +2 -2
  20. package/android/rctmgl/src/main/java/com/mapbox/rctmgl/modules/RCTMGLOfflineModule.java +21 -26
  21. package/docs/Annotation.md +8 -9
  22. package/docs/BackgroundLayer.md +2 -10
  23. package/docs/Callout.md +5 -5
  24. package/docs/Camera.md +18 -47
  25. package/docs/CircleLayer.md +2 -10
  26. package/docs/FillExtrusionLayer.md +2 -10
  27. package/docs/FillLayer.md +2 -10
  28. package/docs/HeatmapLayer.md +2 -10
  29. package/docs/ImageSource.md +3 -2
  30. package/docs/Images.md +5 -3
  31. package/docs/Light.md +1 -1
  32. package/docs/LineLayer.md +2 -10
  33. package/docs/MapView.md +53 -37
  34. package/docs/MarkerView.md +4 -2
  35. package/docs/NativeUserLocation.md +2 -2
  36. package/docs/PointAnnotation.md +5 -8
  37. package/docs/RasterLayer.md +2 -10
  38. package/docs/RasterSource.md +3 -2
  39. package/docs/ShapeSource.md +12 -7
  40. package/docs/Style.md +1 -1
  41. package/docs/SymbolLayer.md +3 -10
  42. package/docs/UserLocation.md +8 -10
  43. package/docs/VectorSource.md +6 -5
  44. package/docs/coordinates.md +6 -0
  45. package/docs/docs.json +518 -1272
  46. package/docs/location.md +6 -0
  47. package/docs/snapshotManager.md +3 -3
  48. package/javascript/@types/assets.d.ts +4 -0
  49. package/javascript/MGLModule.ts +37 -0
  50. package/javascript/Maplibre.ts +65 -0
  51. package/javascript/components/AbstractLayer.tsx +107 -0
  52. package/javascript/components/AbstractSource.tsx +27 -0
  53. package/javascript/components/BackgroundLayer.tsx +43 -0
  54. package/javascript/components/{Callout.js → Callout.tsx} +67 -65
  55. package/javascript/components/{Camera.js → Camera.tsx} +266 -251
  56. package/javascript/components/CircleLayer.tsx +46 -0
  57. package/javascript/components/FillExtrusionLayer.tsx +47 -0
  58. package/javascript/components/FillLayer.tsx +41 -0
  59. package/javascript/components/{HeadingIndicator.js → HeadingIndicator.tsx} +8 -8
  60. package/javascript/components/HeatmapLayer.tsx +44 -0
  61. package/javascript/components/ImageSource.tsx +78 -0
  62. package/javascript/components/Images.tsx +134 -0
  63. package/javascript/components/Light.tsx +67 -0
  64. package/javascript/components/LineLayer.tsx +42 -0
  65. package/javascript/components/{MapView.js → MapView.tsx} +365 -354
  66. package/javascript/components/MarkerView.tsx +104 -0
  67. package/javascript/components/{NativeBridgeComponent.js → NativeBridgeComponent.tsx} +44 -13
  68. package/javascript/components/NativeUserLocation.tsx +33 -0
  69. package/javascript/components/PointAnnotation.tsx +221 -0
  70. package/javascript/components/RasterLayer.tsx +41 -0
  71. package/javascript/components/RasterSource.tsx +117 -0
  72. package/javascript/components/ShapeSource.tsx +383 -0
  73. package/javascript/components/{Style.js → Style.tsx} +129 -38
  74. package/javascript/components/SymbolLayer.tsx +72 -0
  75. package/javascript/components/{UserLocation.js → UserLocation.tsx} +111 -110
  76. package/javascript/components/VectorSource.tsx +207 -0
  77. package/javascript/components/annotations/Annotation.tsx +134 -0
  78. package/javascript/index.ts +4 -0
  79. package/javascript/modules/location/{locationManager.js → locationManager.ts} +71 -10
  80. package/javascript/modules/offline/{OfflineCreatePackOptions.js → OfflineCreatePackOptions.ts} +20 -4
  81. package/javascript/modules/offline/{OfflinePack.js → OfflinePack.ts} +23 -7
  82. package/javascript/modules/offline/{offlineManager.js → offlineManager.ts} +81 -24
  83. package/javascript/modules/snapshot/{SnapshotOptions.js → SnapshotOptions.ts} +43 -6
  84. package/javascript/modules/snapshot/{snapshotManager.js → snapshotManager.ts} +5 -5
  85. package/javascript/requestAndroidLocationPermissions.ts +29 -0
  86. package/javascript/types/BaseProps.ts +5 -0
  87. package/javascript/types/OnPressEvent.ts +13 -0
  88. package/javascript/types/index.ts +7 -0
  89. package/javascript/utils/BridgeValue.ts +90 -0
  90. package/javascript/utils/{Logger.js → Logger.ts} +37 -18
  91. package/javascript/utils/MaplibreStyles.d.ts +1486 -0
  92. package/javascript/utils/StyleValue.ts +49 -0
  93. package/javascript/utils/animated/AbstractAnimatedCoordinates.ts +134 -0
  94. package/javascript/utils/animated/AnimatedCoordinatesArray.ts +112 -0
  95. package/javascript/utils/animated/{AnimatedExtractCoordinateFromArray.js → AnimatedExtractCoordinateFromArray.ts} +5 -5
  96. package/javascript/utils/animated/{AnimatedPoint.js → AnimatedPoint.ts} +20 -12
  97. package/javascript/utils/animated/{AnimatedRouteCoordinatesArray.js → AnimatedRouteCoordinatesArray.ts} +39 -14
  98. package/javascript/utils/animated/{AnimatedShape.js → AnimatedShape.ts} +31 -10
  99. package/javascript/utils/{deprecation.js → deprecation.ts} +9 -6
  100. package/javascript/utils/filterUtils.ts +9 -0
  101. package/javascript/utils/geoUtils.ts +79 -0
  102. package/javascript/utils/{index.js → index.ts} +44 -24
  103. package/javascript/utils/styleMap.ts +264 -0
  104. package/package.json +35 -27
  105. package/plugin/build/withMapLibre.js +18 -3
  106. package/scripts/autogenHelpers/globals.js +1 -1
  107. package/scripts/autogenerate.js +14 -6
  108. package/scripts/download-style-spec.sh +1 -1
  109. package/scripts/templates/MaplibreStyles.ts.ejs +99 -0
  110. package/scripts/templates/index.d.ts.ejs +71 -42
  111. package/scripts/templates/{styleMap.js.ejs → styleMap.ts.ejs} +3 -33
  112. package/setup-jest.js +1 -10
  113. package/tsconfig.json +20 -61
  114. package/index.d.ts +0 -955
  115. package/javascript/components/AbstractLayer.js +0 -75
  116. package/javascript/components/AbstractSource.js +0 -15
  117. package/javascript/components/BackgroundLayer.js +0 -97
  118. package/javascript/components/CircleLayer.js +0 -101
  119. package/javascript/components/FillExtrusionLayer.js +0 -98
  120. package/javascript/components/FillLayer.js +0 -94
  121. package/javascript/components/HeatmapLayer.js +0 -99
  122. package/javascript/components/ImageSource.js +0 -82
  123. package/javascript/components/Images.js +0 -119
  124. package/javascript/components/Light.js +0 -47
  125. package/javascript/components/LineLayer.js +0 -94
  126. package/javascript/components/MarkerView.js +0 -87
  127. package/javascript/components/NativeUserLocation.js +0 -41
  128. package/javascript/components/PointAnnotation.js +0 -216
  129. package/javascript/components/RasterLayer.js +0 -95
  130. package/javascript/components/RasterSource.js +0 -124
  131. package/javascript/components/ShapeSource.js +0 -372
  132. package/javascript/components/SymbolLayer.js +0 -120
  133. package/javascript/components/VectorSource.js +0 -200
  134. package/javascript/components/annotations/Annotation.js +0 -122
  135. package/javascript/index.js +0 -149
  136. package/javascript/utils/BridgeValue.js +0 -81
  137. package/javascript/utils/animated/AnimatedCoordinatesArray.js +0 -191
  138. package/javascript/utils/filterUtils.js +0 -7
  139. package/javascript/utils/geoUtils.js +0 -73
  140. package/javascript/utils/styleMap.js +0 -1932
  141. /package/javascript/utils/animated/{Animated.js → Animated.ts} +0 -0
@@ -0,0 +1,383 @@
1
+ import {ExpressionField, FilterExpression} from '../utils/MaplibreStyles';
2
+ import {getFilter} from '../utils/filterUtils';
3
+ import {
4
+ toJSONString,
5
+ cloneReactChildrenWithProps,
6
+ isFunction,
7
+ isAndroid,
8
+ } from '../utils';
9
+ import {copyPropertiesAsDeprecated} from '../utils/deprecation';
10
+ import OnPressEvent from '../types/OnPressEvent';
11
+ import BaseProps from '../types/BaseProps';
12
+
13
+ import AbstractSource from './AbstractSource';
14
+ import NativeBridgeComponent from './NativeBridgeComponent';
15
+
16
+ import React, {Component, ReactElement} from 'react';
17
+ import {
18
+ NativeMethods,
19
+ NativeModules,
20
+ NativeSyntheticEvent,
21
+ requireNativeComponent,
22
+ } from 'react-native';
23
+ import {Feature, FeatureCollection} from '@turf/helpers';
24
+
25
+ const MapLibreGL = NativeModules.MGLModule;
26
+
27
+ export const NATIVE_MODULE_NAME = 'RCTMGLShapeSource';
28
+
29
+ interface ShapeSourceProps extends BaseProps {
30
+ /**
31
+ * A string that uniquely identifies the source.
32
+ */
33
+ id: string;
34
+ /**
35
+ * An HTTP(S) URL, absolute file URL, or local file URL relative to the current application’s resource bundle.
36
+ */
37
+ url?: string;
38
+ /**
39
+ * The contents of the source. A shape can represent a GeoJSON geometry, a feature, or a feature colllection.
40
+ */
41
+ shape?:
42
+ | GeoJSON.GeometryCollection
43
+ | GeoJSON.Feature
44
+ | GeoJSON.FeatureCollection
45
+ | GeoJSON.Geometry;
46
+ /**
47
+ * Enables clustering on the source for point shapes.
48
+ */
49
+ cluster?: boolean;
50
+ /**
51
+ * Specifies the radius of each cluster if clustering is enabled.
52
+ * A value of 512 produces a radius equal to the width of a tile.
53
+ * The default value is 50.
54
+ */
55
+ clusterRadius?: number;
56
+ /**
57
+ * Specifies the maximum zoom level at which to cluster points if clustering is enabled.
58
+ * Defaults to one zoom level less than the value of maxZoomLevel so that, at the maximum zoom level,
59
+ * the shapes are not clustered.
60
+ */
61
+ clusterMaxZoomLevel?: number;
62
+ /**
63
+ * Specifies custom properties on the generated clusters if clustering
64
+ * is enabled, aggregating values from clustered points.
65
+ *
66
+ * Has the form `{ "property_name": [operator, map_expression]}`, where
67
+ * `operator` is a custom reduce expression that references a special `["accumulated"]` value -
68
+ * it accumulates the property value from clusters/points the cluster contains
69
+ * `map_expression` produces the value of a single point
70
+ *
71
+ * Example: `{ "resultingSum": [["+", ["accumulated"], ["get", "resultingSum"]], ["get", "scalerank"]] }`
72
+ *
73
+ */
74
+ clusterProperties?: {[propertyName: string]: ExpressionField};
75
+ /**
76
+ * Specifies the maximum zoom level at which to create vector tiles.
77
+ * A greater value produces greater detail at high zoom levels.
78
+ * The default value is 18.
79
+ */
80
+ maxZoomLevel?: number;
81
+ /**
82
+ * Specifies the size of the tile buffer on each side.
83
+ * A value of 0 produces no buffer. A value of 512 produces a buffer as wide as the tile itself.
84
+ * Larger values produce fewer rendering artifacts near tile edges and slower performance.
85
+ * The default value is 128.
86
+ */
87
+ buffer?: number;
88
+ /**
89
+ * Specifies the Douglas-Peucker simplification tolerance.
90
+ * A greater value produces simpler geometries and improves performance.
91
+ * The default value is 0.375.
92
+ */
93
+ tolerance?: number;
94
+ /**
95
+ * Whether to calculate line distance metrics.
96
+ * This is required for line layers that specify lineGradient values.
97
+ * The default value is false.
98
+ */
99
+ lineMetrics?: boolean;
100
+ /**
101
+ * Source press listener, gets called when a user presses one of the children layers only
102
+ * if that layer has a higher z-index than another source layers
103
+ *
104
+ * @param {Object} event
105
+ * @param {Object[]} event.features - the geojson features that have hit by the press (might be multiple)
106
+ * @param {Object} event.coordinates - the coordinates of the click
107
+ * @param {Object} event.point - the point of the click
108
+ * @return void
109
+ */
110
+ onPress?: (event: OnPressEvent) => void;
111
+ /**
112
+ * Overrides the default touch hitbox(44x44 pixels) for the source layers
113
+ */
114
+ hitbox?: {
115
+ /**
116
+ * `width` of hitbox
117
+ */
118
+ width: number;
119
+ /**
120
+ * `height` of hitbox
121
+ */
122
+ height: number;
123
+ };
124
+
125
+ children?: ReactElement | ReactElement[];
126
+ }
127
+
128
+ interface NativeProps {
129
+ shape?: string;
130
+ }
131
+
132
+ /**
133
+ * ShapeSource is a map content source that supplies vector shapes to be shown on the map.
134
+ * The shape may be a url or a GeoJSON object
135
+ */
136
+ class ShapeSource extends NativeBridgeComponent(
137
+ AbstractSource<ShapeSourceProps, NativeProps>,
138
+ NATIVE_MODULE_NAME,
139
+ ) {
140
+ static NATIVE_ASSETS_KEY = 'assets';
141
+
142
+ static defaultProps = {
143
+ id: MapLibreGL.StyleSource.DefaultSourceID,
144
+ };
145
+
146
+ constructor(props: ShapeSourceProps) {
147
+ super(props);
148
+ }
149
+
150
+ _setNativeRef(
151
+ nativeRef: Component<NativeProps> & Readonly<NativeMethods>,
152
+ ): void {
153
+ this.setNativeRef(nativeRef);
154
+ super._runPendingNativeCommands(nativeRef);
155
+ }
156
+
157
+ /**
158
+ * Returns all features from the source that match the query parameters regardless of whether or not the feature is
159
+ * currently rendered on the map.
160
+ *
161
+ * @example
162
+ * shapeSource.features()
163
+ *
164
+ * @param {Array=} filter - an optional filter statement to filter the returned Features.
165
+ * @return {FeatureCollection}
166
+ */
167
+ async features(filter?: FilterExpression): Promise<FeatureCollection> {
168
+ const res: {data: string | FeatureCollection} =
169
+ await this._runNativeCommand('features', this._nativeRef, [
170
+ getFilter(filter),
171
+ ]);
172
+
173
+ if (isAndroid()) {
174
+ return JSON.parse(res.data as string);
175
+ }
176
+
177
+ return res.data as FeatureCollection;
178
+ }
179
+
180
+ /**
181
+ * Returns the zoom needed to expand the cluster.
182
+ *
183
+ * @example
184
+ * const zoom = await shapeSource.getClusterExpansionZoom(clusterId);
185
+ *
186
+ * @param {Feature} feature - The feature cluster to expand.
187
+ * @return {number}
188
+ */
189
+ async getClusterExpansionZoom(feature: Feature): Promise<number> {
190
+ if (typeof feature === 'number') {
191
+ console.warn(
192
+ 'Using cluster_id is deprecated and will be removed from the future releases. Please use cluster as an argument instead.',
193
+ );
194
+ const res: {data: number} = await this._runNativeCommand(
195
+ 'getClusterExpansionZoomById',
196
+ this._nativeRef,
197
+ [feature],
198
+ );
199
+ return res.data;
200
+ }
201
+
202
+ const res: {data: number} = await this._runNativeCommand(
203
+ 'getClusterExpansionZoom',
204
+ this._nativeRef,
205
+ [JSON.stringify(feature)],
206
+ );
207
+ return res.data;
208
+ }
209
+
210
+ /**
211
+ * Returns the FeatureCollection from the cluster.
212
+ *
213
+ * @example
214
+ * const collection = await shapeSource.getClusterLeaves(clusterId, limit, offset);
215
+ *
216
+ * @param {Feature} feature - The feature cluster to expand.
217
+ * @param {number} limit - The number of points to return.
218
+ * @param {number} offset - The amount of points to skip (for pagination).
219
+ * @return {FeatureCollection}
220
+ */
221
+ async getClusterLeaves(
222
+ feature: Feature,
223
+ limit: number,
224
+ offset: number,
225
+ ): Promise<FeatureCollection> {
226
+ if (typeof feature === 'number') {
227
+ console.warn(
228
+ 'Using cluster_id is deprecated and will be removed from the future releases. Please use cluster as an argument instead.',
229
+ );
230
+ const res: {data: string | FeatureCollection} =
231
+ await this._runNativeCommand('getClusterLeavesById', this._nativeRef, [
232
+ feature,
233
+ limit,
234
+ offset,
235
+ ]);
236
+
237
+ if (isAndroid()) {
238
+ return JSON.parse(res.data as string);
239
+ }
240
+
241
+ return res.data as FeatureCollection;
242
+ }
243
+
244
+ const res: {data: string | FeatureCollection} =
245
+ await this._runNativeCommand('getClusterLeaves', this._nativeRef, [
246
+ JSON.stringify(feature),
247
+ limit,
248
+ offset,
249
+ ]);
250
+
251
+ if (isAndroid()) {
252
+ return JSON.parse(res.data as string);
253
+ }
254
+
255
+ return res.data as FeatureCollection;
256
+ }
257
+
258
+ /**
259
+ * Returns the FeatureCollection from the cluster (on the next zoom level).
260
+ *
261
+ * @example
262
+ * const collection = await shapeSource.getClusterChildren(clusterId);
263
+ *
264
+ * @param {Feature} feature - The feature cluster to expand.
265
+ * @return {FeatureCollection}
266
+ */
267
+ async getClusterChildren(feature: Feature): Promise<FeatureCollection> {
268
+ if (typeof feature === 'number') {
269
+ console.warn(
270
+ 'Using cluster_id is deprecated and will be removed from the future releases. Please use cluster as an argument instead.',
271
+ );
272
+ const res: {data: string | FeatureCollection} =
273
+ await this._runNativeCommand(
274
+ 'getClusterChildrenById',
275
+ this._nativeRef,
276
+ [feature],
277
+ );
278
+
279
+ if (isAndroid()) {
280
+ return JSON.parse(res.data as string);
281
+ }
282
+
283
+ return res.data as FeatureCollection;
284
+ }
285
+
286
+ const res: {data: string | FeatureCollection} =
287
+ await this._runNativeCommand('getClusterChildren', this._nativeRef, [
288
+ JSON.stringify(feature),
289
+ ]);
290
+
291
+ if (isAndroid()) {
292
+ return JSON.parse(res.data as string);
293
+ }
294
+
295
+ return res.data as FeatureCollection;
296
+ }
297
+
298
+ setNativeProps(props: NativeProps): void {
299
+ const shallowProps = Object.assign({}, props);
300
+
301
+ // Adds support for Animated
302
+ if (shallowProps.shape && typeof shallowProps !== 'string') {
303
+ shallowProps.shape = JSON.stringify(shallowProps.shape);
304
+ }
305
+
306
+ super.setNativeProps(shallowProps);
307
+ }
308
+
309
+ _getShape(): string | undefined {
310
+ if (!this.props.shape) {
311
+ return;
312
+ }
313
+ return toJSONString(this.props.shape);
314
+ }
315
+
316
+ onPress(event: NativeSyntheticEvent<{payload: OnPressEvent}>): void {
317
+ const {
318
+ nativeEvent: {
319
+ payload: {features, coordinates, point},
320
+ },
321
+ } = event;
322
+ let newEvent = {
323
+ features,
324
+ coordinates,
325
+ point,
326
+ };
327
+ newEvent = copyPropertiesAsDeprecated(
328
+ event,
329
+ newEvent,
330
+ (key: string): void => {
331
+ console.warn(
332
+ `event.${key} is deprecated on ShapeSource#onPress, please use event.features`,
333
+ );
334
+ },
335
+ {
336
+ nativeEvent: (
337
+ origNativeEvent: NativeSyntheticEvent<{payload: OnPressEvent}>,
338
+ ) => ({
339
+ ...origNativeEvent,
340
+ payload: features[0],
341
+ }),
342
+ },
343
+ );
344
+ if (this.props.onPress) {
345
+ this.props.onPress(newEvent);
346
+ }
347
+ }
348
+
349
+ render(): ReactElement {
350
+ const props = {
351
+ id: this.props.id,
352
+ url: this.props.url,
353
+ shape: this._getShape(),
354
+ hitbox: this.props.hitbox,
355
+ hasPressListener: isFunction(this.props.onPress),
356
+ onMapboxShapeSourcePress: this.onPress.bind(this),
357
+ cluster: this.props.cluster ? 1 : 0,
358
+ clusterRadius: this.props.clusterRadius,
359
+ clusterMaxZoomLevel: this.props.clusterMaxZoomLevel,
360
+ clusterProperties: this.props.clusterProperties,
361
+ maxZoomLevel: this.props.maxZoomLevel,
362
+ buffer: this.props.buffer,
363
+ tolerance: this.props.tolerance,
364
+ lineMetrics: this.props.lineMetrics,
365
+ onPress: undefined,
366
+ ref: this.setNativeRef,
367
+ onAndroidCallback: isAndroid() ? this._onAndroidCallback : undefined,
368
+ };
369
+
370
+ return (
371
+ <RCTMGLShapeSource {...props}>
372
+ {cloneReactChildrenWithProps(this.props.children, {
373
+ sourceID: this.props.id,
374
+ })}
375
+ </RCTMGLShapeSource>
376
+ );
377
+ }
378
+ }
379
+
380
+ const RCTMGLShapeSource =
381
+ requireNativeComponent<NativeProps>(NATIVE_MODULE_NAME);
382
+
383
+ export default ShapeSource;
@@ -1,3 +1,5 @@
1
+ import {ExpressionField, FilterExpression} from '../utils/MaplibreStyles';
2
+
1
3
  import CircleLayer from './CircleLayer';
2
4
  import RasterLayer from './RasterLayer';
3
5
  import SymbolLayer from './SymbolLayer';
@@ -10,11 +12,17 @@ import VectorSource from './VectorSource';
10
12
  import RasterSource from './RasterSource';
11
13
  import ImageSource from './ImageSource';
12
14
  import ShapeSource from './ShapeSource';
15
+ import {BaseLayerProps} from './AbstractLayer';
13
16
 
14
- import PropTypes from 'prop-types';
15
- import React, {useMemo, useState, useEffect} from 'react';
17
+ import React, {
18
+ useMemo,
19
+ useState,
20
+ useEffect,
21
+ ReactElement,
22
+ ComponentType,
23
+ } from 'react';
16
24
 
17
- function toCamelCase(s) {
25
+ function toCamelCase(s: string): string {
18
26
  return s.replace(/([-_][a-z])/gi, $1 => {
19
27
  return $1.toUpperCase().replace('-', '').replace('_', '');
20
28
  });
@@ -22,11 +30,13 @@ function toCamelCase(s) {
22
30
 
23
31
  // Patches the Mapbox Style Specification keys into the style props attributes:
24
32
  // icon-allow-overlap -> iconAllowOverlap
25
- function toCamelCaseKeys(oldObj) {
33
+ function toCamelCaseKeys(
34
+ oldObj: Record<string, unknown>,
35
+ ): Record<string, unknown> {
26
36
  if (!oldObj) {
27
37
  return {};
28
38
  }
29
- const newObj = {};
39
+ const newObj: Record<string, unknown> = {};
30
40
  Object.keys(oldObj).forEach(key => {
31
41
  const value = oldObj[key];
32
42
  if (key.includes('-')) {
@@ -38,7 +48,9 @@ function toCamelCaseKeys(oldObj) {
38
48
  return newObj;
39
49
  }
40
50
 
41
- function getLayerComponentType(layer) {
51
+ function getLayerComponentType(
52
+ layer: MaplibreJSONLayer,
53
+ ): ComponentType<BaseLayerProps> | null {
42
54
  const {type} = layer;
43
55
 
44
56
  switch (type) {
@@ -65,8 +77,23 @@ function getLayerComponentType(layer) {
65
77
  return null;
66
78
  }
67
79
 
68
- function asLayerComponent(layer) {
80
+ interface MaplibreJSONLayer {
81
+ type: string;
82
+ paint: {[k: string]: unknown};
83
+ layout: {[k: string]: unknown};
84
+ source?: string;
85
+ 'source-layer'?: string;
86
+ minzoom?: number;
87
+ maxzoom?: number;
88
+ filter?: FilterExpression;
89
+ id: string;
90
+ }
91
+
92
+ function asLayerComponent(
93
+ layer: MaplibreJSONLayer,
94
+ ): ReactElement<BaseLayerProps> | null {
69
95
  const LayerComponent = getLayerComponentType(layer);
96
+
70
97
  if (!LayerComponent) {
71
98
  return null;
72
99
  }
@@ -76,7 +103,7 @@ function asLayerComponent(layer) {
76
103
  ...toCamelCaseKeys(layer.layout),
77
104
  };
78
105
 
79
- const layerProps = {};
106
+ const layerProps: Partial<BaseLayerProps> = {};
80
107
 
81
108
  if (layer.source) {
82
109
  layerProps.sourceID = layer.source;
@@ -100,8 +127,46 @@ function asLayerComponent(layer) {
100
127
  return <LayerComponent key={layer.id} id={layer.id} {...layerProps} />;
101
128
  }
102
129
 
103
- function getTileSourceProps(source) {
104
- const sourceProps = {};
130
+ interface MaplibreJSONSource {
131
+ type: string;
132
+ url?: string;
133
+ tiles?: string[];
134
+ minzoom?: number;
135
+ maxzoom?: number;
136
+ attribution?: string;
137
+ scheme?: 'xyz' | 'tms';
138
+ bounds?: number[];
139
+ buffer?: number;
140
+ tileSize?: number;
141
+ coordinates?: [
142
+ [number, number],
143
+ [number, number],
144
+ [number, number],
145
+ [number, number],
146
+ ];
147
+ cluster?: boolean;
148
+ clusterMaxZoom?: number;
149
+ clusterMinPoints?: number;
150
+ clusterRadius?: number;
151
+ clusterProperties?: {[propertyName: string]: ExpressionField};
152
+ data?: string | object;
153
+ filter?: FilterExpression;
154
+ generateId?: boolean;
155
+ lineMetrics?: boolean;
156
+ tolerance?: number;
157
+ }
158
+
159
+ type SourceProps = {
160
+ url?: string;
161
+ tileUrlTemplates?: string[];
162
+ minZoomLevel?: number;
163
+ maxZoomLevel?: number;
164
+ attribution?: string;
165
+ tms?: boolean;
166
+ };
167
+
168
+ function getTileSourceProps(source: MaplibreJSONSource): SourceProps {
169
+ const sourceProps: Partial<SourceProps> = {};
105
170
  if (source.url) {
106
171
  sourceProps.url = source.url;
107
172
  }
@@ -123,20 +188,22 @@ function getTileSourceProps(source) {
123
188
  return sourceProps;
124
189
  }
125
190
 
126
- function getVectorSource(id, source) {
191
+ function getVectorSource(id: string, source: MaplibreJSONSource): ReactElement {
127
192
  const sourceProps = {...getTileSourceProps(source)};
128
193
  return <VectorSource key={id} id={id} {...sourceProps} />;
129
194
  }
130
195
 
131
- function getRasterSource(id, source) {
132
- const sourceProps = {...getTileSourceProps(source)};
196
+ function getRasterSource(id: string, source: MaplibreJSONSource): ReactElement {
197
+ const sourceProps: SourceProps & {tileSize?: number} = {
198
+ ...getTileSourceProps(source),
199
+ };
133
200
  if (source.tileSize) {
134
201
  sourceProps.tileSize = source.tileSize;
135
202
  }
136
203
  return <RasterSource key={id} id={id} {...sourceProps} />;
137
204
  }
138
205
 
139
- function getImageSource(id, source) {
206
+ function getImageSource(id: string, source: MaplibreJSONSource): ReactElement {
140
207
  const sourceProps = {
141
208
  url: source.url,
142
209
  coordinates: source.coordinates,
@@ -144,12 +211,23 @@ function getImageSource(id, source) {
144
211
  return <ImageSource key={id} id={id} {...sourceProps} />;
145
212
  }
146
213
 
147
- function getShapeSource(id, source) {
148
- const sourceProps = {};
214
+ type ShapeSourceShape = (typeof ShapeSource.prototype.props)['shape'];
215
+
216
+ function getShapeSource(id: string, source: MaplibreJSONSource): ReactElement {
217
+ const sourceProps: SourceProps & {
218
+ shape?: ShapeSourceShape;
219
+ cluster?: boolean;
220
+ clusterRadius?: number;
221
+ clusterMaxZoomLevel?: number;
222
+ clusterProperties?: {[propertyName: string]: ExpressionField};
223
+ buffer?: number;
224
+ tolerance?: number;
225
+ lineMetrics?: boolean;
226
+ } = {};
149
227
  if (source.data && typeof source.data === 'string') {
150
228
  sourceProps.url = source.data;
151
229
  } else if (source.data && typeof source.data === 'object') {
152
- sourceProps.shape = source.data;
230
+ sourceProps.shape = source.data as ShapeSourceShape;
153
231
  }
154
232
  if (source.cluster !== undefined) {
155
233
  sourceProps.cluster = source.cluster;
@@ -178,7 +256,10 @@ function getShapeSource(id, source) {
178
256
  return <ShapeSource key={id} id={id} {...sourceProps} />;
179
257
  }
180
258
 
181
- function asSourceComponent(id, source) {
259
+ function asSourceComponent(
260
+ id: string,
261
+ source: MaplibreJSONSource,
262
+ ): ReactElement | null {
182
263
  switch (source.type) {
183
264
  case 'vector':
184
265
  return getVectorSource(id, source);
@@ -190,11 +271,23 @@ function asSourceComponent(id, source) {
190
271
  return getShapeSource(id, source);
191
272
  }
192
273
 
193
- console.warn(`Mapbox source type '${source.type}' is not supported/`);
274
+ console.warn(`Maplibre source type '${source.type}' is not supported`);
194
275
 
195
276
  return null;
196
277
  }
197
278
 
279
+ interface MaplibreJSON {
280
+ layers?: MaplibreJSONLayer[];
281
+ sources?: {[key: string]: MaplibreJSONSource};
282
+ }
283
+
284
+ interface StyleProps {
285
+ /**
286
+ * A JSON object conforming to the schema described in the MapLibre Style Specification, or a URL to such JSON.
287
+ */
288
+ json?: MaplibreJSON | URL;
289
+ }
290
+
198
291
  /**
199
292
  * Style is a component that automatically adds sources / layers to the map using MapLibre Style Spec.
200
293
  * Only [`sources`](https://maplibre.org/maplibre-gl-js-docs/style-spec/sources/) & [`layers`](https://maplibre.org/maplibre-gl-js-docs/style-spec/layers/) are supported.
@@ -202,21 +295,23 @@ function asSourceComponent(id, source) {
202
295
  *
203
296
  * TODO: Maintainer forking this project does not understand the above comment regarding what is supported.
204
297
  */
205
- const Style = props => {
298
+ const Style = (props: StyleProps): ReactElement => {
206
299
  const [fetchedJson, setFetchedJson] = useState({});
207
- const json = typeof props.json === 'object' ? props.json : fetchedJson;
300
+ const json: MaplibreJSON =
301
+ typeof props.json === 'object' ? props.json : fetchedJson;
208
302
 
209
303
  // Fetch style when props.json is a URL
210
304
  useEffect(() => {
211
305
  const abortController = new AbortController();
212
- const fetchStyleJson = async () => {
306
+ const fetchStyleJson = async (url: string): Promise<void> => {
213
307
  try {
214
- const response = await fetch(props.json, {
308
+ const response = await fetch(url, {
215
309
  signal: abortController.signal,
216
310
  });
217
311
  const responseJson = await response.json();
218
312
  setFetchedJson(responseJson);
219
- } catch (e) {
313
+ } catch (error: unknown) {
314
+ const e = error as {name?: string};
220
315
  if (e.name === 'AbortError') {
221
316
  return;
222
317
  }
@@ -224,9 +319,9 @@ const Style = props => {
224
319
  }
225
320
  };
226
321
  if (typeof props.json === 'string') {
227
- fetchStyleJson();
322
+ fetchStyleJson(props.json);
228
323
  }
229
- return function cleanup() {
324
+ return function cleanup(): void {
230
325
  abortController.abort();
231
326
  };
232
327
  }, [props.json]);
@@ -236,18 +331,21 @@ const Style = props => {
236
331
  if (!json.layers) {
237
332
  return [];
238
333
  }
239
- return json.layers.map(asLayerComponent).filter(x => !!x);
334
+ return json.layers
335
+ .map(asLayerComponent)
336
+ .filter((x: ReactElement | null) => !!x);
240
337
  }, [json.layers]);
241
338
 
242
339
  // Extract source components from json
243
340
  const sourceComponents = useMemo(() => {
244
- if (!json.sources || !Object.keys(json.sources)) {
341
+ const {sources} = json;
342
+ if (!sources || !Object.keys(sources)) {
245
343
  return [];
246
344
  }
247
- return Object.keys(json.sources)
248
- .map(id => asSourceComponent(id, json.sources[id]))
345
+ return Object.keys(sources)
346
+ .map(id => asSourceComponent(id, sources[id]))
249
347
  .filter(x => !!x);
250
- }, [json.sources]);
348
+ }, [json]);
251
349
 
252
350
  return (
253
351
  <>
@@ -257,11 +355,4 @@ const Style = props => {
257
355
  );
258
356
  };
259
357
 
260
- Style.propTypes = {
261
- /**
262
- * A JSON object conforming to the schema described in the MapLibre Style Specification, or a URL to such JSON.
263
- */
264
- json: PropTypes.any,
265
- };
266
-
267
358
  export default Style;