-
Notifications
You must be signed in to change notification settings - Fork 2
/
App.tsx
661 lines (635 loc) · 16.6 KB
/
App.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
/**
* React Native Mapbox geometry editor library example
*/
import { useMemo, useRef, useState } from 'react';
import {
Alert,
LogBox,
SafeAreaView,
StyleSheet,
View,
Pressable,
Text,
} from 'react-native';
import { DarkTheme } from 'react-native-paper';
import MapboxGL from '@react-native-mapbox-gl/maps';
import token from '../mapbox_token.json';
import sampleFeatures from './sample.json';
import type { FeatureCollection } from 'geojson';
/**
* A way to get the `performance.now()` interface, for timing code,
* in both debug and release mode
* See https://github.com/MaxGraey/react-native-console-time-polyfill/blob/master/index.js
*/
const getTimeMilliseconds =
((global as any).performance && (global as any).performance.now) ||
(global as any).performanceNow ||
(global as any).nativePerformanceNow;
if (!getTimeMilliseconds) {
throw new Error('Failed to find performance.now() or an equivalent.');
}
/**
* Hide known issue in the library (refer to the README)
*/
LogBox.ignoreLogs([
"[mobx] Derivation 'observer_StoreProvider' is created/updated without reading any observable value.",
]);
/**
* Polyfill for React Native needed by 'react-native-mapbox-geometry-editor'
* See https://github.com/uuidjs/uuid#getrandomvalues-not-supported
*/
import 'react-native-get-random-values';
import {
defaultStyleGeneratorMap,
FeatureLifecycleStage,
featureLifecycleStageColor,
GeometryEditorUI,
CoordinateRole,
validateMetadata,
MetadataSchemaGeneratorMap,
} from 'react-native-mapbox-geometry-editor';
import type {
CameraControls,
DraggablePointStyle,
EditableFeature,
GeometryIORef,
InteractionEventProps,
MetadataSchema,
SemanticGeometryType,
StyleGeneratorMap,
} from 'react-native-mapbox-geometry-editor';
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'green',
},
libraryContainer: {
margin: 10,
borderRadius: 15,
overflow: 'hidden',
flex: 1,
backgroundColor: 'blue',
},
map: {
margin: 10,
borderRadius: 5,
overflow: 'hidden',
},
ioControlsContainer: {
position: 'relative',
alignSelf: 'flex-end',
},
button: {
marginBottom: 10,
marginRight: 10,
padding: 3,
borderRadius: 10,
},
text: {
textAlign: 'center',
},
});
/* Set the Mapbox API access token
* Changes to the token might only take effect after closing and reopening the app.
* (see https://github.com/react-native-mapbox-gl/maps/issues/933)
*/
MapboxGL.setAccessToken(token.accessToken);
/**
* Example enumeration used for an option select
* geometry metadata field
*
* Also used for data-driven geometry styling
*/
enum VehicleType {
Car = 'CAR',
Train = 'TRAIN',
Boat = 'BOAT',
Bicycle = 'BICYCLE',
}
/**
* Default colours for vehicle types
* @param stage The vehicle type
* @return A specific or a default colour, depending on whether `type` is defined
*/
function vehicleTypeColor(type?: VehicleType): string {
switch (type) {
case VehicleType.Car:
return '#ff1493'; // Deep pink
case VehicleType.Train:
return '#adff2f'; // Green yellow
case VehicleType.Boat:
return '#0000cd'; // Medium blue
case VehicleType.Bicycle:
return '#f4a460'; // Sandy brown
default:
return '#ffffff'; // White
}
}
/**
* Enumeration for data-driven styling of polygons
*/
enum ZoneType {
Parking = 'PARKING',
Restricted = 'RESTRICTED',
}
/**
* Default colours for [[ZoneType]] types
* @param stage The zone type
* @return A specific or a default colour, depending on whether `type` is defined
*/
function zoneTypeColor(type?: ZoneType): string {
switch (type) {
case ZoneType.Parking:
return '#696969'; // Dim grey
case ZoneType.Restricted:
return '#ff69b4'; // Hot pink
default:
return '#ffffff'; // White
}
}
/**
* Limits for custom line widths
*/
const LINE_WIDTH_LIMITS = {
min: 1,
max: 12,
};
/**
* Custom rendering styles for geometry displayed on the map
*/
const styleGeneratorMap: StyleGeneratorMap = {
/**
* Style for draggable point annotations
*/
draggablePoint: (
role: CoordinateRole,
feature: EditableFeature
): DraggablePointStyle => {
let style = defaultStyleGeneratorMap.draggablePoint(role, feature);
if (feature.geometry.type === 'Point') {
style.color = vehicleTypeColor(feature.properties?.vehicleType);
}
return style;
},
/**
* Style for selected vertices of shapes being edited
*/
selectedVertex: defaultStyleGeneratorMap.selectedVertex,
/**
* Style for point geometry, non-clusters
*/
point: () => {
let style = defaultStyleGeneratorMap.point();
/**
* Data-driven styling by vehicle type
*/
style.circleColor = [
'match',
['get', 'vehicleType'],
VehicleType.Car,
vehicleTypeColor(VehicleType.Car),
VehicleType.Train,
vehicleTypeColor(VehicleType.Train),
VehicleType.Boat,
vehicleTypeColor(VehicleType.Boat),
VehicleType.Bicycle,
vehicleTypeColor(VehicleType.Bicycle),
vehicleTypeColor(), // Default
];
return style;
},
/**
* Style for vertices of non-point geometry
*/
vertex: defaultStyleGeneratorMap.vertex,
/**
* Style for polylines describing the edges of non-polyline geometry
*/
edge: defaultStyleGeneratorMap.edge,
/**
* Style for polygon geometry
*/
polygon: () => {
let style = defaultStyleGeneratorMap.polygon();
/**
* Data-driven styling by geometry lifecycle stage and zone type
*/
style.fillColor = [
'match',
['get', 'rnmgeStage'],
FeatureLifecycleStage.NewShape,
featureLifecycleStageColor(FeatureLifecycleStage.NewShape),
FeatureLifecycleStage.EditShape,
featureLifecycleStageColor(FeatureLifecycleStage.EditShape),
FeatureLifecycleStage.EditMetadata,
featureLifecycleStageColor(FeatureLifecycleStage.EditMetadata),
FeatureLifecycleStage.SelectMultiple,
featureLifecycleStageColor(FeatureLifecycleStage.SelectMultiple),
FeatureLifecycleStage.SelectSingle,
featureLifecycleStageColor(FeatureLifecycleStage.SelectSingle),
FeatureLifecycleStage.View,
[
'match',
['get', 'zoneType'],
ZoneType.Parking,
zoneTypeColor(ZoneType.Parking),
ZoneType.Restricted,
zoneTypeColor(ZoneType.Restricted),
zoneTypeColor(), // Default
],
zoneTypeColor(), // Default
];
return style;
},
/**
* Style for polyline geometry
*/
polyline: () => {
let style = defaultStyleGeneratorMap.polyline();
/**
* Data-driven styling: Set the width of the line to the value given
* by its custom 'width' property, clipped to the range 1-12.
*/
style.lineWidth = [
'interpolate',
['linear'],
['get', 'width'],
LINE_WIDTH_LIMITS.min,
LINE_WIDTH_LIMITS.min,
LINE_WIDTH_LIMITS.max,
LINE_WIDTH_LIMITS.max,
];
return style;
},
/**
* Style for clustered point geometry
*/
cluster: () => {
let style = defaultStyleGeneratorMap.cluster();
style.circleStrokeColor = 'tan';
style.circleStrokeWidth = 4;
return style;
},
/**
* Style for symbols rendered on top of clusters
* (defaults to cluster point counts rendered as text)
*/
clusterSymbol: () => {
return defaultStyleGeneratorMap.clusterSymbol();
},
};
/**
* Custom metadata fields for point geometry
*/
const POINT_SCHEMA = [
['yup.object'],
['yup.required'],
[
'yup.meta',
{
titleFieldKey: 'model',
title: 'No model',
showIfEmpty: false,
},
],
[
'yup.shape',
{
vehicleType: [
['yup.mixed'],
['yup.label', 'Type of vehicle'],
['yup.required'],
['yup.oneOf', Object.values(VehicleType)],
[
'yup.meta',
{
inPreview: true,
},
],
],
model: [['yup.string'], ['yup.required', 'A model is required']], // An enumeration may be better, as the user could input arbitrary strings
age: [
['yup.number'],
['yup.label', 'Age (years)'],
['yup.required', 'How old is it?'],
['yup.positive', 'Age must be greater than zero'],
],
description: [
['yup.string'],
['yup.label', 'Description'],
['yup.optional'],
[
'yup.meta',
{
inPreview: true,
},
],
],
needsRepair: [
['yup.boolean'],
['yup.label', 'Needs repair?'],
['yup.required'],
],
fieldWithPermissions: [
['yup.string'],
['yup.label', 'Immutable comment'],
['yup.optional'],
[
'yup.meta',
{
permissions: {
edit: false,
},
showIfEmpty: true,
},
],
],
},
],
];
/**
* Function defining the metadata fields available for editing.
* The library would provide a default function if none is provided.
* @param type Type of geometry object whose metadata will be edited
*/
function metadataSchemaGenerator(
type: SemanticGeometryType
): MetadataSchema | null {
if (type === 'Point') {
return POINT_SCHEMA;
} else if (type === 'Polygon') {
return [
['yup.object'],
['yup.required'],
[
'yup.meta',
{
titleFieldKey: 'zoneType',
title: 'Unknown region',
},
],
[
'yup.shape',
{
zoneType: [
['yup.mixed'],
['yup.label', 'Type of region'],
['yup.required'],
['yup.oneOf', Object.values(ZoneType)],
[
'yup.meta',
{
inPreview: true,
},
],
],
openAtNight: [
['yup.boolean'],
['yup.label', 'Overnight use permitted?'],
['yup.required'],
],
},
],
];
} else if (type === 'LineString') {
return [
['yup.object'],
['yup.required'],
[
'yup.meta',
{
titleFieldKey: 'name',
title: 'Unnamed polyline',
},
],
[
'yup.shape',
{
name: [['yup.string'], ['yup.label', 'Name'], ['yup.optional']],
width: [
['yup.number'],
['yup.label', 'Width (pixels)'],
['yup.required', 'Line width is required'],
[
'yup.min',
LINE_WIDTH_LIMITS.min,
'Width must be at least ${min}.',
],
['yup.max', LINE_WIDTH_LIMITS.max, 'Width must be at most ${max}.'],
],
},
],
];
} else {
return null;
}
}
/**
* In this simple example, the same metadata schema generation
* function is used for both new and existing geometry.
*/
const metadataSchemaGeneratorMap: MetadataSchemaGeneratorMap = {
newGeometry: metadataSchemaGenerator,
existingGeometry: metadataSchemaGenerator,
};
/**
* For development purposes, validate the metadata schema
*/
const validationResult = validateMetadata(POINT_SCHEMA, {
vehicleType: 'BICYCLE',
model: 'classic',
age: 'five',
extraProperties: {
wheelDiameter: 26,
},
});
if (validationResult.schemaErrors) {
console.warn(
'Example metadata schema errors: ',
validationResult.schemaErrors
);
}
if (validationResult.dataErrors) {
console.warn(
'Example metadata data validation errors: ',
validationResult.dataErrors
);
}
/**
* The time interval over which camera transitions will occur.
*/
const cameraMoveTime = 200; // Milliseconds
/**
* A component that renders buttons for the user to import and export
* geometry
* @param props Render properties
*/
function IOControls({
onImport,
onExport,
disabled,
}: {
/**
* Import button press event handler
*/
onImport: () => void;
/**
* Export button press event handler
*/
onExport: () => void;
/**
* Whether or not the buttons should be disabled
*/
disabled: boolean;
}) {
let buttonColor = 'orange';
if (disabled) {
buttonColor = 'grey';
}
const buttonStyle = { ...styles.button, backgroundColor: buttonColor };
return (
<View style={styles.ioControlsContainer}>
<Pressable style={buttonStyle} onPress={onImport} disabled={disabled}>
<Text style={styles.text}>Import static shapes</Text>
</Pressable>
<Pressable style={buttonStyle} onPress={onExport} disabled={disabled}>
<Text style={styles.text}>Export shapes</Text>
</Pressable>
</View>
);
}
/**
* Render a map page with a demonstration of the geometry editor library's functionality
*/
export default function App() {
/**
* Receive hints from the geometry editor, about where the camera should be looking,
* that are triggered by certain user actions.
*/
const cameraRef = useRef<MapboxGL.Camera>(null);
const cameraControls: CameraControls = useMemo(() => {
return {
fitBounds: (northEastCoordinates, southWestCoordinates, padding) => {
cameraRef.current?.fitBounds(
northEastCoordinates,
southWestCoordinates,
padding,
cameraMoveTime
);
},
moveTo: (coordinates) => {
cameraRef.current?.moveTo(coordinates, cameraMoveTime);
},
};
}, [cameraRef]);
/**
* Geometry import and export functionality
*/
const ioRef = useRef<GeometryIORef>(null);
const ioHandlers = {
onImport: () => {
(async () => {
if (ioRef.current) {
/**
* Time the import operation and display the time in an alert
*/
const t0 = getTimeMilliseconds();
try {
const result = await ioRef.current.import(
sampleFeatures as FeatureCollection,
{
replace: true,
strict: false,
validate: true,
}
);
const t1 = getTimeMilliseconds();
Alert.alert(
'Import result',
`Data imported ${result.exact ? 'exactly' : 'with changes'} in ${
t1 - t0
} milliseconds with ${result?.errors.length} errors.`
);
} catch (e) {
console.error(e);
let message = 'Unknown error';
if (e instanceof Error) {
message = e.message;
}
Alert.alert('Import failed', message);
}
}
})();
},
onExport: () => {
(async () => {
if (ioRef.current) {
/**
* Time the export operation and display the time in an alert
*/
const t0 = getTimeMilliseconds();
try {
const result = await ioRef.current.export();
const jsonResult = JSON.stringify(result, null, 1);
/**
* Avoid flooding the console with the result
*/
if (jsonResult.length < 10000) {
console.log('Export result: \n', jsonResult);
} else {
console.log(
`Stringified export result (with whitespace) has ${jsonResult.length} characters (not shown).`
);
}
const t1 = getTimeMilliseconds();
Alert.alert(
'Export result',
`Data exported in ${t1 - t0} milliseconds.`
);
} catch (e) {
console.error(e);
let message = 'Unknown error';
if (e instanceof Error) {
message = e.message;
}
Alert.alert('Export failed', message);
}
}
})();
},
};
/**
* Enable or disable the import and export buttons as a function of the current
* geometry editing operation
*/
const [disableIO, setDisableIO] = useState(false);
const interactionHandlers: InteractionEventProps = useMemo(() => {
return {
onEditingStatus: setDisableIO,
};
}, [setDisableIO]);
return (
<SafeAreaView style={styles.container}>
<IOControls disabled={disableIO} {...ioHandlers} />
<GeometryEditorUI
cameraControls={cameraControls}
style={styles.libraryContainer}
theme={DarkTheme}
mapProps={{
style: styles.map,
styleURL: 'mapbox://styles/mapbox/dark-v10',
}}
metadataSchemaGeneratorMap={metadataSchemaGeneratorMap}
styleGenerators={styleGeneratorMap}
interactionEventProps={interactionHandlers}
ref={ioRef}
>
<MapboxGL.Camera
ref={cameraRef}
centerCoordinate={[3.380271, 6.464217]}
zoomLevel={14}
/>
</GeometryEditorUI>
</SafeAreaView>
);
}