/
MapView.tsx
539 lines (501 loc) · 15.7 KB
/
MapView.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
/* eslint-disable @typescript-eslint/no-empty-function */
/* eslint-disable @typescript-eslint/no-explicit-any */
import React, {
useCallback,
useEffect,
useImperativeHandle,
useRef,
useState,
} from "react";
import {
Linking,
Platform,
type StyleProp,
StyleSheet,
type ViewStyle,
} from "react-native";
import WebView from "react-native-webview";
import type {
WebViewErrorEvent,
WebViewMessageEvent,
} from "react-native-webview/lib/WebViewTypes";
import SitumPlugin from "../../sdk";
import useSitum from "../hooks";
import {
type MapViewDirectionsOptions,
type MapViewError,
type MapViewRef,
type NavigateToPointPayload,
type NavigateToPoiPayload,
type OnDirectionsRequestInterceptor,
type OnExternalLinkClickedResult,
type OnFavoritePoisUpdatedResult,
type OnFloorChangedResult,
type OnPoiDeselectedResult,
type OnPoiSelectedResult,
type SearchFilter,
} from "../types";
import { ErrorName } from "../types/constants";
import { sendMessageToViewer } from "../utils";
import ViewerMapper from "../utils/mapper";
const SITUM_BASE_DOMAIN = "https://map-viewer.situm.com";
const NETWORK_ERROR_CODE = {
android: -2,
ios: -1009,
// These platforms are unhandled
windows: 0,
macos: 0,
web: 0,
};
export type MapViewConfiguration = {
/**
* A String parameter that allows you to choose the API you will be retrieving our cartography from. Default is "dashboard.situm.com".
* In most cases this parameter shouldn't be changed.
*/
apiDomain?: string;
/**
* A String parameter that allows you to specify which domain will be displayed inside our webview. Defaults to "https://map-viewer.situm.com/".
* In most cases this parameter shouldn't be changed.
*/
viewerDomain?: string;
/**
* @required
* Your Situm API key. Find your API key at your [situm profile](https://dashboard.situm.com/accounts/profile)
*/
situmApiKey: string;
/**
* A String identifier that allows you to remotely configure all map settings.
*/
remoteIdentifier?: string;
/**
* @required
* The building that will be loaded on the map.
* In case you set a buildingIdentifier in your remote configuration, it will be prioritized over {@link MapViewConfiguration.buildingIdentifier} parameter.
*/
buildingIdentifier: string;
/**
* Sets the directionality of the texts that will be displayed inside MapView. Default is "ltr".
*/
directionality?: string;
/**
* Sets the UI language based on the given ISO 639-1 code. Checkout the [Situm docs](https://situm.com/docs/query-params/) to see the list of supported languages.
*/
language?: string;
};
const viewerStyles = StyleSheet.create({
webview: {
minHeight: "100%",
minWidth: "100%",
},
});
export interface MapViewProps {
/**
* The required basic configuration to use our MapView.
*/
configuration: MapViewConfiguration;
style?: StyleProp<ViewStyle>;
/**
* Get notified when a POI is selected.
* @param event {@link OnPoiSelectedResult} object.
*/
onPoiSelected?: (event: OnPoiSelectedResult) => void;
/**
* Get notified when the selected POI is deselected.
* @param event {@link OnPoiDeselectedResult} object.
*/
onPoiDeselected?: (event: OnPoiDeselectedResult) => void;
/**
* Get notified when the MapView has been loaded and is ready to receive actions.
*/
onLoad?: (event: any) => void;
/**
* Get notified when an error has occurred during the MapView load process.
* @param event {@link MapViewError} object.
*/
onLoadError?: (event: MapViewError) => void;
/**
* Get notified when the current floor displayed on the map has changed.
* @param event {@link OnFloorChangedResult} object.
*/
onFloorChanged?: (event: OnFloorChangedResult) => void;
/**
* Callback invoked when the user clicks on a link in the MapView that leads to a website different from the MapView's domain.
* For example some POI description may contain a link to a video or a website, and if this callback is not set,
* the link will be opened in the system's default browser by default.
* @param event {@link OnExternalLinkClickedResult} object.
*/
onExternalLinkClicked?: (event: OnExternalLinkClickedResult) => void;
/**
* Callback invoked when the list of favoritePois is updated
* @param event {@link OnFavoritePoisUpdatedResult} object.
*/
onFavoritePoisUpdated?: (event: OnFavoritePoisUpdatedResult) => void;
}
const MapView = React.forwardRef<MapViewRef, MapViewProps>(
(
{
configuration,
style,
onLoad = () => {},
onLoadError = () => {},
onPoiSelected = () => {},
onPoiDeselected = () => {},
onFloorChanged = () => {},
onExternalLinkClicked = undefined,
onFavoritePoisUpdated = () => {},
},
ref
) => {
const webViewRef = useRef<WebView>();
const [_onDirectionsRequestInterceptor, setInterceptor] =
useState<OnDirectionsRequestInterceptor>();
// Local states
const [mapLoaded, setMapLoaded] = useState<boolean>(false);
const [buildingIdentifier, setBuildingIdentifier] = useState<string>(
configuration.buildingIdentifier
);
const {
init,
location,
locationStatus,
directions,
navigation,
calculateRoute,
startNavigation,
stopNavigation,
error,
} = useSitum();
const sendFollowUser = () => {
if (
webViewRef.current &&
mapLoaded &&
location?.position?.buildingIdentifier ===
configuration.buildingIdentifier
) {
sendMessageToViewer(webViewRef.current, ViewerMapper.followUser(true));
}
};
// Helper functions used on imperative handler
// Navigation
const _navigateToPoi = useCallback((payload: NavigateToPoiPayload) => {
if (!webViewRef.current || !payload || !payload.identifier) return;
sendMessageToViewer(
webViewRef.current,
ViewerMapper.navigateToPoi(payload)
);
}, []);
const _navigateToPoint = useCallback((payload: NavigateToPointPayload) => {
if (
!webViewRef.current ||
(!payload?.lat && !payload?.lng && !payload?.floorIdentifier)
)
return;
sendMessageToViewer(
webViewRef.current,
ViewerMapper.navigateToPoint(payload)
);
}, []);
// Cartography
const _selectPoi = useCallback((poiId: number) => {
if (!webViewRef.current) {
return;
}
if (SitumPlugin.navigationIsRunning()) {
console.error(
"Situm > hook > Navigation on course, poi selection is unavailable"
);
return;
}
sendMessageToViewer(webViewRef.current, ViewerMapper.selectPoi(poiId));
}, []);
const _selectPoiCategory = useCallback((categoryId: number) => {
if (!webViewRef.current) {
return;
}
if (SitumPlugin.navigationIsRunning()) {
console.error(
"Situm > hook > Navigation on course, poi category selection is unavailable"
);
return;
}
sendMessageToViewer(
webViewRef.current,
ViewerMapper.selectPoiCategory(categoryId)
);
}, []);
const _search = useCallback((payload: SearchFilter) => {
sendMessageToViewer(webViewRef.current, ViewerMapper.search(payload));
}, []);
const _setDirectionsOptions = useCallback(
(directionsOptions: MapViewDirectionsOptions) => {
if (!webViewRef.current) {
return;
}
sendMessageToViewer(
webViewRef.current,
ViewerMapper.setDirectionsOptions(directionsOptions)
);
},
[]
);
const _setFavoritePois = useCallback((poiIds: number[]) => {
if (!webViewRef.current) {
return;
}
sendMessageToViewer(
webViewRef.current,
ViewerMapper.setFavoritePois(poiIds)
);
}, []);
/**
* API exported to the outside world from the MapViewer
*
* These handler allows third party developers to send actions to the MapView.
* please check the MapViewRef type definitions to know the public API.
*
* <MapView
* ref={(ref: MapViewRef) => ref.selectPoi(122)}
* configuration={{
* buildingIdentifier: SITUM_BUILDING_ID,
* }}
* onLoad={onLoad} />
*/
useImperativeHandle(
ref,
() => {
return {
followUser() {
webViewRef.current &&
sendMessageToViewer(
webViewRef.current,
ViewerMapper.followUser(true)
);
},
unFollowUser() {
webViewRef.current &&
sendMessageToViewer(
webViewRef.current,
ViewerMapper.followUser(false)
);
},
selectPoi(poiId: number) {
_selectPoi(poiId);
},
selectPoiCategory(poiId: number) {
_selectPoiCategory(poiId);
},
setDirectionsOptions(directionsOptions: MapViewDirectionsOptions) {
_setDirectionsOptions(directionsOptions);
},
setFavoritePois(poiIds: number[]) {
_setFavoritePois(poiIds);
},
deselectPoi() {
webViewRef.current &&
sendMessageToViewer(
webViewRef.current,
ViewerMapper.selectPoi(null)
);
},
navigateToPoi(payload): void {
_navigateToPoi(payload);
},
navigateToPoint(payload: NavigateToPointPayload): void {
_navigateToPoint(payload);
},
setOnDirectionsRequestInterceptor(directionRequestInterceptor): void {
setInterceptor(() => directionRequestInterceptor);
},
cancelNavigation(): void {
if (!webViewRef.current) return;
stopNavigation();
sendMessageToViewer(
webViewRef.current,
ViewerMapper.cancelNavigation()
);
},
search(payload): void {
_search(payload);
},
};
},
[
stopNavigation,
_navigateToPoi,
_navigateToPoint,
_selectPoi,
_selectPoiCategory,
_setDirectionsOptions,
_setFavoritePois,
_search,
]
);
useEffect(() => {
if (!error) return;
console.error(
"Error code:",
error.code ? error.code : " no code provided"
);
console.error("Error detected:", error.message);
}, [error]);
// Updated SDK location
useEffect(() => {
if (!webViewRef.current || !location) return;
sendMessageToViewer(webViewRef.current, ViewerMapper.location(location));
}, [location]);
// Updated SDK navigation
useEffect(() => {
if (!webViewRef.current || !navigation) return;
sendMessageToViewer(
webViewRef.current,
ViewerMapper.navigation(navigation)
);
}, [navigation]);
// Updated SDK route
useEffect(() => {
if (!webViewRef.current || !directions) return;
sendMessageToViewer(webViewRef.current, ViewerMapper.route(directions));
}, [directions]);
// Update language
useEffect(() => {
if (!webViewRef.current || !configuration.language || !mapLoaded) return;
sendMessageToViewer(
webViewRef.current,
ViewerMapper.setLanguage(configuration.language)
);
}, [configuration.language, mapLoaded]);
// Update SDK configuration
useEffect(() => {
if (webViewRef.current && mapLoaded) {
sendMessageToViewer(
webViewRef.current,
ViewerMapper.initialConfiguration(style)
);
}
}, [webViewRef, mapLoaded, style]);
// Update follow user
useEffect(() => {
mapLoaded && sendFollowUser();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [mapLoaded]);
//locationStatus
useEffect(() => {
if (!webViewRef.current || !locationStatus || !mapLoaded) return;
sendMessageToViewer(
webViewRef.current,
ViewerMapper.locationStatus(locationStatus)
);
}, [locationStatus, mapLoaded]);
const handleRequestFromViewer = (event: WebViewMessageEvent) => {
const eventParsed = JSON.parse(event.nativeEvent.data);
switch (eventParsed.type) {
case "app.map_is_ready":
init();
onLoad && onLoad("");
setMapLoaded(true);
break;
case "directions.requested":
calculateRoute(eventParsed.payload, _onDirectionsRequestInterceptor);
break;
case "navigation.requested":
startNavigation(eventParsed.payload, _onDirectionsRequestInterceptor);
break;
case "navigation.stopped":
stopNavigation();
break;
case "cartography.poi_selected":
onPoiSelected(eventParsed?.payload);
break;
case "cartography.poi_deselected":
onPoiDeselected(eventParsed?.payload);
break;
case "ui.favorite_pois_updated": {
const favoritePoisIds = {
currentPoisIdentifiers: eventParsed.payload.favoritePois
? [...eventParsed.payload.favoritePois]
: [],
};
onFavoritePoisUpdated(favoritePoisIds);
break;
}
case "cartography.floor_selected":
onFloorChanged(eventParsed?.payload);
break;
case "cartography.building_selected":
if (
!eventParsed.payload.identifier ||
eventParsed.payload.identifier.toString() === buildingIdentifier
) {
return;
} else {
setBuildingIdentifier(eventParsed.payload.identifier.toString());
}
break;
default:
break;
}
};
const _onShouldStartLoadWithRequest = (request) => {
if (
request &&
request.url &&
!request.url.startsWith(configuration.viewerDomain || SITUM_BASE_DOMAIN)
) {
if (
onExternalLinkClicked &&
typeof onExternalLinkClicked === "function"
) {
onExternalLinkClicked({ url: request.url });
} else {
Linking.openURL(request.url);
}
return false;
}
return true;
};
return (
<WebView
ref={webViewRef}
source={{
uri: `${configuration.viewerDomain || SITUM_BASE_DOMAIN}/${
configuration.remoteIdentifier
? `id/${configuration.remoteIdentifier}`
: ""
}?&apikey=${
configuration.situmApiKey
}&wl=true&global=true&mode=embed${
configuration.buildingIdentifier
? `&buildingid=${configuration.buildingIdentifier}`
: ""
}&show=rts`,
}}
style={StyleSheet.flatten([viewerStyles.webview, style])}
limitsNavigationsToAppBoundDomains={true}
javaScriptEnabled={true}
domStorageEnabled={true}
startInLoadingState={true}
cacheEnabled
onMessage={handleRequestFromViewer}
onShouldStartLoadWithRequest={_onShouldStartLoadWithRequest}
onError={(evt: WebViewErrorEvent) => {
if (!onLoadError) return;
const { nativeEvent } = evt;
// TODO: on render error should probably still try to render an html
if (nativeEvent.code === NETWORK_ERROR_CODE[Platform.OS]) {
onLoadError({
name: ErrorName.ERR_INTERNET_DISCONNECTED,
description: nativeEvent.description,
});
} else {
// TODO: handle more errors
onLoadError({
name: ErrorName.ERR_INTERNAL_SERVER_ERROR,
description: nativeEvent.description,
});
}
}}
/>
);
}
);
export default MapView;