@maplibre/maplibre-react-native 9.0.1 → 10.0.0-alpha.1

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 (146) 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 +15 -1
  18. package/android/build.gradle +2 -2
  19. package/android/rctmgl/build.gradle +2 -4
  20. package/android/rctmgl/src/main/java/com/mapbox/rctmgl/components/styles/sources/RCTMGLShapeSource.java +14 -0
  21. package/android/rctmgl/src/main/java/com/mapbox/rctmgl/components/styles/sources/RCTMGLShapeSourceManager.java +26 -0
  22. package/android/rctmgl/src/main/java/com/mapbox/rctmgl/utils/ClusterPropertyEntry.java +13 -0
  23. package/docs/Annotation.md +8 -9
  24. package/docs/BackgroundLayer.md +2 -10
  25. package/docs/Callout.md +5 -5
  26. package/docs/Camera.md +18 -47
  27. package/docs/CircleLayer.md +2 -10
  28. package/docs/FillExtrusionLayer.md +2 -10
  29. package/docs/FillLayer.md +2 -10
  30. package/docs/HeatmapLayer.md +2 -10
  31. package/docs/ImageSource.md +3 -2
  32. package/docs/Images.md +5 -3
  33. package/docs/Light.md +1 -1
  34. package/docs/LineLayer.md +2 -10
  35. package/docs/MapView.md +53 -37
  36. package/docs/MarkerView.md +4 -2
  37. package/docs/NativeUserLocation.md +2 -2
  38. package/docs/PointAnnotation.md +5 -8
  39. package/docs/RasterLayer.md +2 -10
  40. package/docs/RasterSource.md +3 -2
  41. package/docs/ShapeSource.md +12 -6
  42. package/docs/Style.md +1 -1
  43. package/docs/SymbolLayer.md +3 -10
  44. package/docs/UserLocation.md +8 -10
  45. package/docs/VectorSource.md +6 -5
  46. package/docs/coordinates.md +6 -0
  47. package/docs/docs.json +561 -1308
  48. package/docs/location.md +6 -0
  49. package/docs/snapshotManager.md +3 -3
  50. package/ios/RCTMGL/RCTMGLShapeSource.h +1 -0
  51. package/ios/RCTMGL/RCTMGLShapeSource.m +14 -0
  52. package/ios/RCTMGL/RCTMGLShapeSourceManager.m +1 -0
  53. package/ios/RCTMGL.xcodeproj/project.pbxproj +1 -0
  54. package/javascript/@types/assets.d.ts +4 -0
  55. package/javascript/MGLModule.ts +37 -0
  56. package/javascript/Maplibre.ts +65 -0
  57. package/javascript/components/AbstractLayer.tsx +107 -0
  58. package/javascript/components/AbstractSource.tsx +27 -0
  59. package/javascript/components/BackgroundLayer.tsx +43 -0
  60. package/javascript/components/{Callout.js → Callout.tsx} +67 -65
  61. package/javascript/components/{Camera.js → Camera.tsx} +266 -251
  62. package/javascript/components/CircleLayer.tsx +46 -0
  63. package/javascript/components/FillExtrusionLayer.tsx +47 -0
  64. package/javascript/components/FillLayer.tsx +41 -0
  65. package/javascript/components/{HeadingIndicator.js → HeadingIndicator.tsx} +8 -8
  66. package/javascript/components/HeatmapLayer.tsx +44 -0
  67. package/javascript/components/ImageSource.tsx +78 -0
  68. package/javascript/components/Images.tsx +134 -0
  69. package/javascript/components/Light.tsx +67 -0
  70. package/javascript/components/LineLayer.tsx +42 -0
  71. package/javascript/components/{MapView.js → MapView.tsx} +365 -354
  72. package/javascript/components/MarkerView.tsx +104 -0
  73. package/javascript/components/{NativeBridgeComponent.js → NativeBridgeComponent.tsx} +44 -13
  74. package/javascript/components/NativeUserLocation.tsx +33 -0
  75. package/javascript/components/PointAnnotation.tsx +221 -0
  76. package/javascript/components/RasterLayer.tsx +41 -0
  77. package/javascript/components/RasterSource.tsx +117 -0
  78. package/javascript/components/ShapeSource.tsx +383 -0
  79. package/javascript/components/{Style.js → Style.tsx} +132 -38
  80. package/javascript/components/SymbolLayer.tsx +72 -0
  81. package/javascript/components/{UserLocation.js → UserLocation.tsx} +111 -110
  82. package/javascript/components/VectorSource.tsx +207 -0
  83. package/javascript/components/annotations/Annotation.tsx +134 -0
  84. package/javascript/index.ts +4 -0
  85. package/javascript/modules/location/{locationManager.js → locationManager.ts} +71 -10
  86. package/javascript/modules/offline/{OfflineCreatePackOptions.js → OfflineCreatePackOptions.ts} +20 -4
  87. package/javascript/modules/offline/{OfflinePack.js → OfflinePack.ts} +23 -7
  88. package/javascript/modules/offline/{offlineManager.js → offlineManager.ts} +81 -24
  89. package/javascript/modules/snapshot/{SnapshotOptions.js → SnapshotOptions.ts} +43 -6
  90. package/javascript/modules/snapshot/{snapshotManager.js → snapshotManager.ts} +5 -5
  91. package/javascript/requestAndroidLocationPermissions.ts +29 -0
  92. package/javascript/types/BaseProps.ts +5 -0
  93. package/javascript/types/OnPressEvent.ts +13 -0
  94. package/javascript/types/index.ts +7 -0
  95. package/javascript/utils/BridgeValue.ts +90 -0
  96. package/javascript/utils/{Logger.js → Logger.ts} +37 -18
  97. package/javascript/utils/MaplibreStyles.d.ts +1486 -0
  98. package/javascript/utils/StyleValue.ts +49 -0
  99. package/javascript/utils/animated/AbstractAnimatedCoordinates.ts +134 -0
  100. package/javascript/utils/animated/AnimatedCoordinatesArray.ts +112 -0
  101. package/javascript/utils/animated/{AnimatedExtractCoordinateFromArray.js → AnimatedExtractCoordinateFromArray.ts} +5 -5
  102. package/javascript/utils/animated/{AnimatedPoint.js → AnimatedPoint.ts} +20 -12
  103. package/javascript/utils/animated/{AnimatedRouteCoordinatesArray.js → AnimatedRouteCoordinatesArray.ts} +39 -14
  104. package/javascript/utils/animated/{AnimatedShape.js → AnimatedShape.ts} +31 -10
  105. package/javascript/utils/{deprecation.js → deprecation.ts} +9 -6
  106. package/javascript/utils/filterUtils.ts +9 -0
  107. package/javascript/utils/geoUtils.ts +79 -0
  108. package/javascript/utils/{index.js → index.ts} +44 -24
  109. package/javascript/utils/styleMap.ts +264 -0
  110. package/package.json +43 -34
  111. package/plugin/build/withMapLibre.js +3 -2
  112. package/scripts/autogenHelpers/globals.js +1 -1
  113. package/scripts/autogenerate.js +14 -6
  114. package/scripts/templates/MaplibreStyles.ts.ejs +99 -0
  115. package/scripts/templates/index.d.ts.ejs +71 -42
  116. package/scripts/templates/{styleMap.js.ejs → styleMap.ts.ejs} +3 -33
  117. package/setup-jest.js +3 -10
  118. package/tsconfig.json +20 -61
  119. package/index.d.ts +0 -954
  120. package/javascript/components/AbstractLayer.js +0 -75
  121. package/javascript/components/AbstractSource.js +0 -15
  122. package/javascript/components/BackgroundLayer.js +0 -97
  123. package/javascript/components/CircleLayer.js +0 -101
  124. package/javascript/components/FillExtrusionLayer.js +0 -98
  125. package/javascript/components/FillLayer.js +0 -94
  126. package/javascript/components/HeatmapLayer.js +0 -99
  127. package/javascript/components/ImageSource.js +0 -82
  128. package/javascript/components/Images.js +0 -119
  129. package/javascript/components/Light.js +0 -47
  130. package/javascript/components/LineLayer.js +0 -94
  131. package/javascript/components/MarkerView.js +0 -87
  132. package/javascript/components/NativeUserLocation.js +0 -41
  133. package/javascript/components/PointAnnotation.js +0 -216
  134. package/javascript/components/RasterLayer.js +0 -95
  135. package/javascript/components/RasterSource.js +0 -124
  136. package/javascript/components/ShapeSource.js +0 -357
  137. package/javascript/components/SymbolLayer.js +0 -120
  138. package/javascript/components/VectorSource.js +0 -200
  139. package/javascript/components/annotations/Annotation.js +0 -122
  140. package/javascript/index.js +0 -149
  141. package/javascript/utils/BridgeValue.js +0 -81
  142. package/javascript/utils/animated/AnimatedCoordinatesArray.js +0 -191
  143. package/javascript/utils/filterUtils.js +0 -7
  144. package/javascript/utils/geoUtils.js +0 -73
  145. package/javascript/utils/styleMap.js +0 -1932
  146. /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;
@@ -163,6 +241,9 @@ function getShapeSource(id, source) {
163
241
  if (source.clusterMaxZoom !== undefined) {
164
242
  sourceProps.clusterMaxZoomLevel = source.clusterMaxZoom;
165
243
  }
244
+ if (source.clusterProperties !== undefined) {
245
+ sourceProps.clusterProperties = source.clusterProperties;
246
+ }
166
247
  if (source.buffer !== undefined) {
167
248
  sourceProps.buffer = source.buffer;
168
249
  }
@@ -175,7 +256,10 @@ function getShapeSource(id, source) {
175
256
  return <ShapeSource key={id} id={id} {...sourceProps} />;
176
257
  }
177
258
 
178
- function asSourceComponent(id, source) {
259
+ function asSourceComponent(
260
+ id: string,
261
+ source: MaplibreJSONSource,
262
+ ): ReactElement | null {
179
263
  switch (source.type) {
180
264
  case 'vector':
181
265
  return getVectorSource(id, source);
@@ -187,11 +271,23 @@ function asSourceComponent(id, source) {
187
271
  return getShapeSource(id, source);
188
272
  }
189
273
 
190
- console.warn(`Mapbox source type '${source.type}' is not supported/`);
274
+ console.warn(`Maplibre source type '${source.type}' is not supported`);
191
275
 
192
276
  return null;
193
277
  }
194
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
+
195
291
  /**
196
292
  * Style is a component that automatically adds sources / layers to the map using MapLibre Style Spec.
197
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.
@@ -199,21 +295,23 @@ function asSourceComponent(id, source) {
199
295
  *
200
296
  * TODO: Maintainer forking this project does not understand the above comment regarding what is supported.
201
297
  */
202
- const Style = props => {
298
+ const Style = (props: StyleProps): ReactElement => {
203
299
  const [fetchedJson, setFetchedJson] = useState({});
204
- const json = typeof props.json === 'object' ? props.json : fetchedJson;
300
+ const json: MaplibreJSON =
301
+ typeof props.json === 'object' ? props.json : fetchedJson;
205
302
 
206
303
  // Fetch style when props.json is a URL
207
304
  useEffect(() => {
208
305
  const abortController = new AbortController();
209
- const fetchStyleJson = async () => {
306
+ const fetchStyleJson = async (url: string): Promise<void> => {
210
307
  try {
211
- const response = await fetch(props.json, {
308
+ const response = await fetch(url, {
212
309
  signal: abortController.signal,
213
310
  });
214
311
  const responseJson = await response.json();
215
312
  setFetchedJson(responseJson);
216
- } catch (e) {
313
+ } catch (error: unknown) {
314
+ const e = error as {name?: string};
217
315
  if (e.name === 'AbortError') {
218
316
  return;
219
317
  }
@@ -221,9 +319,9 @@ const Style = props => {
221
319
  }
222
320
  };
223
321
  if (typeof props.json === 'string') {
224
- fetchStyleJson();
322
+ fetchStyleJson(props.json);
225
323
  }
226
- return function cleanup() {
324
+ return function cleanup(): void {
227
325
  abortController.abort();
228
326
  };
229
327
  }, [props.json]);
@@ -233,18 +331,21 @@ const Style = props => {
233
331
  if (!json.layers) {
234
332
  return [];
235
333
  }
236
- return json.layers.map(asLayerComponent).filter(x => !!x);
334
+ return json.layers
335
+ .map(asLayerComponent)
336
+ .filter((x: ReactElement | null) => !!x);
237
337
  }, [json.layers]);
238
338
 
239
339
  // Extract source components from json
240
340
  const sourceComponents = useMemo(() => {
241
- if (!json.sources || !Object.keys(json.sources)) {
341
+ const {sources} = json;
342
+ if (!sources || !Object.keys(sources)) {
242
343
  return [];
243
344
  }
244
- return Object.keys(json.sources)
245
- .map(id => asSourceComponent(id, json.sources[id]))
345
+ return Object.keys(sources)
346
+ .map(id => asSourceComponent(id, sources[id]))
246
347
  .filter(x => !!x);
247
- }, [json.sources]);
348
+ }, [json]);
248
349
 
249
350
  return (
250
351
  <>
@@ -254,11 +355,4 @@ const Style = props => {
254
355
  );
255
356
  };
256
357
 
257
- Style.propTypes = {
258
- /**
259
- * A JSON object conforming to the schema described in the MapLibre Style Specification, or a URL to such JSON.
260
- */
261
- json: PropTypes.any,
262
- };
263
-
264
358
  export default Style;