@mapsindoors/react-native-maps-indoors-mapbox 2.9.0 → 2.10.0

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 (38) hide show
  1. package/README.md +81 -21
  2. package/android/build.gradle +2 -14
  3. package/android/src/main/java/com/mapsindoorsrn/MapboxMapView.java +4 -0
  4. package/android/src/main/java/com/mapsindoorsrn/MapsIndoorsPackage.java +10 -1
  5. package/android/src/main/java/com/mapsindoorsrn/MapsIndoorsViewManager.java +28 -2
  6. package/android/src/main/java/com/mapsindoorsrn/core/DirectionsRendererModule.java +10 -2
  7. package/android/src/main/java/com/mapsindoorsrn/core/DirectionsServiceModule.java +1 -0
  8. package/android/src/main/java/com/mapsindoorsrn/core/MapControlModule.java +335 -99
  9. package/android/src/main/java/com/mapsindoorsrn/core/MapsIndoorsModule.java +17 -1
  10. package/android/src/main/java/com/mapsindoorsrn/core/RouteStore.java +59 -0
  11. package/app.plugin.js +8 -86
  12. package/ios/core/DirectionsRendererBridge.m +1 -0
  13. package/ios/core/DirectionsRendererModule.swift +292 -308
  14. package/ios/core/DirectionsServiceModule.swift +7 -1
  15. package/ios/core/MapControlModule.swift +330 -244
  16. package/ios/core/MapsIndoorsBridge.m +1 -0
  17. package/ios/core/MapsIndoorsModule.swift +48 -14
  18. package/ios/core/ReactPositionProvider.swift +6 -7
  19. package/ios/core/Sources/MainThread/CallGeneration.swift +38 -0
  20. package/ios/core/Sources/MainThread/MainThread.swift +25 -0
  21. package/ios/core/Sources/RouteStore/RouteStore.swift +62 -0
  22. package/package.json +10 -2
  23. package/react-native-maps-indoors-mapbox.podspec +6 -2
  24. package/specs/NativeDirectionsRendererModule.ts +1 -1
  25. package/specs/NativeMapsIndoorsModule.ts +1 -1
  26. package/src/core/MPCameraPosition.ts +1 -1
  27. package/src/core/MPDirectionsRenderer.ts +19 -3
  28. package/src/core/MPDirectionsService.ts +4 -1
  29. package/src/core/MPRouteStopIconConfig.ts +5 -3
  30. package/src/core/MapsIndoors.ts +36 -3
  31. package/src/core/RouteHandles.ts +76 -0
  32. package/src/core/RouteStopIconConfig.ts +5 -1
  33. package/src/core/__tests__/MPBounds.test.ts +0 -109
  34. package/src/core/__tests__/MPFilter.test.ts +0 -76
  35. package/src/core/__tests__/MPLanguageTag.test.ts +0 -168
  36. package/src/core/__tests__/MPPoint.test.ts +0 -82
  37. package/src/core/__tests__/MPSolution.test.ts +0 -107
  38. package/src/core/__tests__/MapsIndoors.language.test.ts +0 -180
@@ -5,6 +5,7 @@
5
5
 
6
6
  RCT_EXTERN_METHOD(loadMapsIndoors:(NSString *)apiKey
7
7
  optionalStrings:(NSArray<NSString *> _Nullable)optionalStrings
8
+ sdkVersion:(NSString * _Nullable)sdkVersion
8
9
  resolver:(RCTPromiseResolveBlock)resolve
9
10
  rejecter:(RCTPromiseRejectBlock)reject)
10
11
 
@@ -35,8 +35,22 @@ public class MapsIndoorsModule: RCTEventEmitter {
35
35
  /// Keeps the `cacheData` delegate alive while a dataset sync runs - see the note in `cacheData`.
36
36
  private var datasetDelegate: DatasetDelegate?
37
37
 
38
- @objc(loadMapsIndoors:optionalStrings:resolver:rejecter:)
39
- func loadMapsIndoors(apiKey: String, optionalStrings: [String]?, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
38
+ /// Names this wrapper as the component behind the MapsIndoors Insights session, so React Native
39
+ /// apps are told apart from native ones in the rollups.
40
+ ///
41
+ /// The SDK stamps the component into the session when the session starts, inside `load`, so this
42
+ /// has to run on the same call, right before it. The version comes from JS, which reads it from
43
+ /// the map package's own package.json.
44
+ private func setReactNativeComponent(_ sdkVersion: String?) {
45
+ MPLogger.sharedInstance.component = "React Native/iOS SDK"
46
+ MPLogger.sharedInstance.componentVersion = sdkVersion ?? "unknown"
47
+ }
48
+
49
+ @objc(loadMapsIndoors:optionalStrings:sdkVersion:resolver:rejecter:)
50
+ func loadMapsIndoors(apiKey: String, optionalStrings: [String]?, sdkVersion: String?, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
51
+ setReactNativeComponent(sdkVersion)
52
+ keptRoutes.removeAll()
53
+
40
54
  Task {
41
55
  do {
42
56
  if optionalStrings != nil {
@@ -148,19 +162,22 @@ public class MapsIndoorsModule: RCTEventEmitter {
148
162
  return resolve(toJSON(locations))
149
163
  }
150
164
 
151
- @objc public func getMapStyles(_ resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) {
152
- guard let mapControl = MapsIndoorsData.sharedInstance.mapView?.getMapControl() else {
153
- return doReject(reject, message: "getMapStyles: Must create MapControl first")
154
- }
155
- guard let venue = mapControl.currentVenue else {
156
- return doReject(reject, message: "getMapStyles: No current venue")
157
- }
158
- guard let styles = venue.styles else {
159
- return doReject(reject, message: "getMapStyles: Got no styles")
160
- }
165
+ @objc public func getMapStyles(_ resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
166
+ // `currentVenue` is read from the map control, which has to happen on the main thread.
167
+ onMainThread {
168
+ guard let mapControl = MapsIndoorsData.sharedInstance.mapView?.getMapControl() else {
169
+ return doReject(reject, message: "getMapStyles: Must create MapControl first")
170
+ }
171
+ guard let venue = mapControl.currentVenue else {
172
+ return doReject(reject, message: "getMapStyles: No current venue")
173
+ }
174
+ guard let styles = venue.styles else {
175
+ return doReject(reject, message: "getMapStyles: Got no styles")
176
+ }
161
177
 
162
- let mapStyles = styles.map({ MPMapStyleCodable(withMapStyle: $0) })
163
- return resolve(toJSON(mapStyles))
178
+ let mapStyles = styles.map({ MPMapStyleCodable(withMapStyle: $0) })
179
+ resolve(toJSON(mapStyles))
180
+ }
164
181
  }
165
182
 
166
183
  @objc public func getSolution(_ resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) {
@@ -208,6 +225,7 @@ public class MapsIndoorsModule: RCTEventEmitter {
208
225
 
209
226
  positionProvider = provider
210
227
  MPMapsIndoors.shared.positionProvider = positionProvider
228
+ setOnMapControl(provider)
211
229
 
212
230
  return resolve(nil)
213
231
  }
@@ -215,10 +233,25 @@ public class MapsIndoorsModule: RCTEventEmitter {
215
233
  @objc public func removePositionProvider(_ resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) {
216
234
  positionProvider = nil
217
235
  MPMapsIndoors.shared.positionProvider = nil
236
+ setOnMapControl(nil)
218
237
 
219
238
  return resolve(nil)
220
239
  }
221
240
 
241
+ /// Hands the provider to this wrapper's map control directly, not only through the SDK.
242
+ ///
243
+ /// The SDK passes `MPMapsIndoors.shared.positionProvider` on only to the map controls it has
244
+ /// registered, and every `load` clears that registry. The wrapper keeps its existing map control
245
+ /// across a reload (`initMapControl` returns early), so after a second `load` the control is no
246
+ /// longer registered, the provider's delegate is never set, and the blue dot never shows
247
+ /// (MS-3929). Setting it here wires the delegate whatever the SDK's registry holds; for a
248
+ /// registered control it is the same assignment the SDK makes.
249
+ private func setOnMapControl(_ provider: MPPositionProvider?) {
250
+ onMainThread {
251
+ MapsIndoorsData.sharedInstance.mapView?.getMapControl()?.positionProvider = provider
252
+ }
253
+ }
254
+
222
255
  @objc public func onPositionUpdate(_ positionJSON: String, resolver resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) {
223
256
  do {
224
257
  let positionResult: MPPositionResult = try fromJSON(positionJSON)
@@ -287,6 +320,7 @@ public class MapsIndoorsModule: RCTEventEmitter {
287
320
  }
288
321
 
289
322
  @objc public func destroy(_ resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
323
+ keptRoutes.removeAll()
290
324
  Task {
291
325
  MPMapsIndoors.shared.shutdown()
292
326
  MapsIndoorsData.sharedInstance.isInitialized = false
@@ -5,17 +5,16 @@ public class ReactPositionProvider: MPPositionProvider {
5
5
  public var latestPosition: MapsIndoors.MPPositionResult?
6
6
 
7
7
  public var name = "default"
8
- public var delegate: MapsIndoors.MPPositionProviderDelegate?
9
- private var mapsIndoorsData: MapsIndoorsData
10
-
11
- init() {
12
- mapsIndoorsData = MapsIndoorsData.sharedInstance
13
- }
8
+ // Weak: the delegate is the map control, which holds this provider. Strong, the pair kept each
9
+ // other, and the map, alive after the map view was gone (SPEX-2885).
10
+ public weak var delegate: MapsIndoors.MPPositionProviderDelegate?
14
11
 
15
12
  public func setLatestPosition(positionResult: MPPositionResult) {
16
13
  DispatchQueue.main.async {
17
14
  if self.latestPosition?.floorIndex != positionResult.floorIndex {
18
- let floorSelector = self.mapsIndoorsData.floorSelector
15
+ // Read per call, not kept: every new map view resets `sharedInstance`, and a kept
16
+ // instance closed the cycle provider -> data -> map view -> map control -> provider.
17
+ let floorSelector = MapsIndoorsData.sharedInstance.floorSelector
19
18
  floorSelector?.onUserPositionFloorChange(floorIndex: positionResult.floorIndex)
20
19
  }
21
20
 
@@ -0,0 +1,38 @@
1
+ //
2
+ // CallGeneration.swift
3
+ // react-native-maps-indoors
4
+ //
5
+
6
+ import Foundation
7
+
8
+ /// Makes last-call-wins hold for module methods that download before they apply.
9
+ ///
10
+ /// Such a call can finish after a later one, and would then overwrite the later call's result. Each
11
+ /// call takes a token with ``next()`` and applies only while ``isCurrent(_:)`` - a call that finished
12
+ /// late is stale and drops its result.
13
+ ///
14
+ /// The token has to be taken *synchronously*, before the call's `Task` is created. React Native
15
+ /// serialises a module's methods on one queue, and ``onMainThread`` runs them on the main queue in
16
+ /// that same order, so taking it there makes the token follow call order. Taking it inside the `Task`
17
+ /// would instead number the calls by whichever one the cooperative pool happened to schedule first,
18
+ /// which is not the order they were made in - the newer call could take the lower token and then be
19
+ /// discarded in favour of the older one.
20
+ final class CallGeneration: @unchecked Sendable {
21
+ private let lock = NSLock()
22
+ private var current: UInt64 = 0
23
+
24
+ /// Takes the next token, invalidating every earlier one.
25
+ func next() -> UInt64 {
26
+ lock.lock()
27
+ defer { lock.unlock() }
28
+ current &+= 1
29
+ return current
30
+ }
31
+
32
+ /// Whether `token` is still the newest, i.e. no later call has taken one.
33
+ func isCurrent(_ token: UInt64) -> Bool {
34
+ lock.lock()
35
+ defer { lock.unlock() }
36
+ return token == current
37
+ }
38
+ }
@@ -0,0 +1,25 @@
1
+ //
2
+ // MainThread.swift
3
+ // react-native-maps-indoors
4
+ //
5
+
6
+ import Foundation
7
+
8
+ /// Runs `work` on the main thread, which is where the MapsIndoors map control and directions
9
+ /// renderer have to be used.
10
+ ///
11
+ /// React Native calls this package's module methods on their own method queue
12
+ /// (`requiresMainQueueSetup()` is `false`). `MPMapControl` and `MPDirectionsRenderer` are main-actor
13
+ /// isolated in the iOS SDK, and touching either from any other thread crashes the app (SPEX-2633,
14
+ /// SPEX-2686), so every module method that reads or writes them does that work in here and settles
15
+ /// its promise from in here too.
16
+ ///
17
+ /// `work` is always enqueued, even when the caller is already on the main thread. React Native calls
18
+ /// a module's methods one at a time on its queue, and the main queue runs blocks in the order they
19
+ /// were added, so the map sees calls in the order the app made them. Running inline when already on
20
+ /// main would let such a call overtake one that was enqueued before it.
21
+ func onMainThread(_ work: @escaping @MainActor () -> Void) {
22
+ DispatchQueue.main.async {
23
+ MainActor.assumeIsolated(work)
24
+ }
25
+ }
@@ -0,0 +1,62 @@
1
+ //
2
+ // RouteStore.swift
3
+ // react-native-maps-indoors
4
+ //
5
+
6
+ import Foundation
7
+
8
+ /// Keeps the routes the directions service module returned, so the renderer module can render the
9
+ /// very instance instead of decoding the copy that comes back from JavaScript (SPEX-2782).
10
+ ///
11
+ /// Only that instance carries the endpoints the SDK reports with the directions Insights events,
12
+ /// and neither SDK encodes them, so a decoded copy reports none.
13
+ ///
14
+ /// Holds at most `capacity` routes and forgets the least recently used, since JavaScript never says
15
+ /// when it is done with one. A forgotten route still renders, from its JSON, just without endpoints.
16
+ /// Lookups count as use, so a route the app keeps setting stays. Rendering a kept route again is
17
+ /// safe: the SDK resolves its endpoints once and reads them on every event.
18
+ final class RouteStore<Route>: @unchecked Sendable {
19
+ private let lock = NSLock()
20
+ private let capacity: Int
21
+ private var routes: [String: Route] = [:]
22
+ /// Keys in `routes`, least recently used first.
23
+ private var order: [String] = []
24
+
25
+ init(capacity: Int) {
26
+ precondition(capacity > 0, "A RouteStore must be able to hold a route")
27
+ self.capacity = capacity
28
+ }
29
+
30
+ /// Keeps `route` and returns the key to look it up by.
31
+ func keep(_ route: Route) -> String {
32
+ let key = UUID().uuidString
33
+ lock.lock()
34
+ defer { lock.unlock() }
35
+ routes[key] = route
36
+ order.append(key)
37
+ if order.count > capacity {
38
+ routes[order.removeFirst()] = nil
39
+ }
40
+ return key
41
+ }
42
+
43
+ /// The route kept under `key`, if it is still kept.
44
+ func route(for key: String) -> Route? {
45
+ lock.lock()
46
+ defer { lock.unlock() }
47
+ guard let route = routes[key], let index = order.firstIndex(of: key) else {
48
+ return nil
49
+ }
50
+ order.append(order.remove(at: index))
51
+ return route
52
+ }
53
+
54
+ /// Forgets every route, when MapsIndoors loads or is destroyed: a route belongs to the solution that
55
+ /// was loaded when it was requested.
56
+ func removeAll() {
57
+ lock.lock()
58
+ defer { lock.unlock() }
59
+ routes.removeAll()
60
+ order.removeAll()
61
+ }
62
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mapsindoors/react-native-maps-indoors-mapbox",
3
3
  "title": "React Native MapsIndoors Mapbox",
4
- "version": "2.9.0",
4
+ "version": "2.10.0",
5
5
  "description": "React Native MapsIndoors component with mapbox",
6
6
  "react-native": "index.ts",
7
7
  "files": [
@@ -12,11 +12,16 @@
12
12
  "index.ts",
13
13
  "ios",
14
14
  "react-native-maps-indoors-mapbox.podspec",
15
+ "!src/core/__tests__",
16
+ "!ios/core/Package.swift",
17
+ "!ios/core/Tests",
18
+ "!ios/core/.build",
15
19
  "!android/build",
16
20
  "app.plugin.js"
17
21
  ],
18
22
  "scripts": {
19
- "test": "echo \"Error: no test specified\" && exit 1"
23
+ "test": "jest",
24
+ "test:watch": "jest --watch"
20
25
  },
21
26
  "repository": {
22
27
  "type": "git",
@@ -40,7 +45,10 @@
40
45
  "react-native": ">=0.75.0 <1.0.x"
41
46
  },
42
47
  "devDependencies": {
48
+ "@types/jest": "^29.5.14",
43
49
  "@types/react": "^19.0.0",
50
+ "jest": "^29.7.0",
51
+ "ts-jest": "^29.4.12",
44
52
  "typedoc": "^0.24.8",
45
53
  "typescript": "^5.0.4"
46
54
  },
@@ -21,6 +21,10 @@ Pod::Spec.new do |s|
21
21
  s.source = { :git => "https://github.com/github_account/react-native-maps-indoors-mapbox.git", :tag => "#{s.version}" }
22
22
 
23
23
  s.source_files = "ios/**/*.{h,c,cc,cpp,m,mm,swift}"
24
+ # ios/core carries a SwiftPM manifest and unit tests for its React-free helpers (SPEX-2686). They
25
+ # are run with `swift test` in that repository and must not be compiled into the pod, nor must the
26
+ # build products `swift test` leaves in .build (they include a generated `@main` test runner).
27
+ s.exclude_files = "ios/core/Package.swift", "ios/core/Tests/**/*", "ios/core/.build/**/*"
24
28
  s.requires_arc = true
25
29
 
26
30
  install_modules_dependencies(s)
@@ -33,6 +37,6 @@ Pod::Spec.new do |s|
33
37
  # embeds the resulting dynamic frameworks into the app bundle, so the app builds and links but
34
38
  # dies at launch with `Library not loaded: @rpath/MapsIndoorsCore.framework/MapsIndoorsCore`.
35
39
  # See SPEX-2429 before reintroducing SPM here.
36
- s.dependency "MapsIndoorsMapbox11", "4.20.0"
37
- s.dependency "MapsIndoorsCodable", "4.20.0"
40
+ s.dependency "MapsIndoorsMapbox11", "4.23.0"
41
+ s.dependency "MapsIndoorsCodable", "4.23.0"
38
42
  end
@@ -13,7 +13,7 @@ export interface Spec extends TurboModule {
13
13
  setCameraViewFitMode(cameraFitMode: number): Promise<null>;
14
14
  setCameraAnimationDuration(duration: number): Promise<null>;
15
15
  setOnLegSelectedListener(): Promise<null>;
16
- setRoute(routeString: string, stopIcons: string, legIndex: number): Promise<null>;
16
+ setRoute(routeString: string, stopIcons: string, legIndex: number, routeId: string | null): Promise<null>;
17
17
  setAnimatedPolyline(animated: boolean, repeated: boolean, duration: number): Promise<null>;
18
18
  setPolyLineColors(foregroundString: string, backgroundString: string): Promise<null>;
19
19
  setOptions(optionsString: string): Promise<null>;
@@ -4,7 +4,7 @@ import {TurboModuleRegistry} from 'react-native';
4
4
  export interface Spec extends TurboModule {
5
5
  addListener(eventName: string): void;
6
6
  removeListeners(count: number): void;
7
- loadMapsIndoors(apiKey: string, optionalStrings: Array<string> | null): Promise<null>;
7
+ loadMapsIndoors(apiKey: string, optionalStrings: Array<string> | null, sdkVersion: string | null): Promise<null>;
8
8
  getDefaultVenue(): Promise<string | null>;
9
9
  getVenues(): Promise<string>;
10
10
  getBuildings(): Promise<string>;
@@ -41,8 +41,8 @@ export default class MPCameraPosition {
41
41
  return new MPCameraPosition(
42
42
  object?.zoom,
43
43
  target,
44
- object?.bearing ? object.bearing : 0,
45
44
  object?.tilt ? object.tilt : 0,
45
+ object?.bearing ? object.bearing : 0,
46
46
  );
47
47
  }
48
48
  }
@@ -1,6 +1,7 @@
1
1
  import { EmitterSubscription, NativeEventEmitter, NativeModules } from 'react-native';
2
2
  import { MPCameraViewFitMode, MPDirectionsRendererOptions, MPError, MPRoute, OnLegSelectedListener } from "../../index";
3
3
  import { EventNames } from './EventNames';
4
+ import { nativeRouteId } from './RouteHandles';
4
5
  import { RouteStopIconConfig } from './RouteStopIconConfig';
5
6
 
6
7
  const { DirectionsRenderer } = NativeModules;
@@ -15,6 +16,16 @@ const { DirectionsRenderer } = NativeModules;
15
16
  */
16
17
  const NO_USAGE_PERCENTAGE = -1;
17
18
 
19
+ /**
20
+ * Encodes a stop icon for the native modules, which download http(s) URLs and otherwise drop the
21
+ * last character before decoding JSON. That character used to be the `/` React Native's URL
22
+ * polyfill appended to the JSON it was (mis)used to wrap.
23
+ */
24
+ function encodeStopIcon(icon: RouteStopIconConfig): string {
25
+ const image = icon.getImage().toString();
26
+ return /^https?:\/\//.test(image) ? image : image + '/';
27
+ }
28
+
18
29
  /**
19
30
  * Renders a {@link MPRoute} on the map.
20
31
  *
@@ -94,6 +105,10 @@ export default class MPDirectionsRenderer {
94
105
  /**
95
106
  * Set a route to be rendered. This also resets the selected leg and step indices to 0.
96
107
  *
108
+ * Directions analytics attribute the route to its origin and destination only when it has the
109
+ * content of a route {@link MPDirectionsService.getRoute} returned since MapsIndoors last loaded,
110
+ * among its ten most recently used. A copy made through JSON qualifies; an edited route does not.
111
+ *
97
112
  * @public
98
113
  * @async
99
114
  * @param {?MPRoute} [route]
@@ -105,10 +120,11 @@ export default class MPDirectionsRenderer {
105
120
  var iconsAsString = new Map<number, string>();
106
121
  if (stopIcons !== null) {
107
122
  stopIcons.forEach((icon, index) => {
108
- iconsAsString.set(index, icon.getImage().toString());
123
+ iconsAsString.set(index, encodeStopIcon(icon));
109
124
  });
110
125
  }
111
- await DirectionsRenderer.setRoute(JSON.stringify(route), JSON.stringify(Object.fromEntries(iconsAsString.entries())), legIndex);
126
+ const routeJson = JSON.stringify(route);
127
+ await DirectionsRenderer.setRoute(routeJson, JSON.stringify(Object.fromEntries(iconsAsString.entries())), legIndex, nativeRouteId(routeJson));
112
128
  }
113
129
 
114
130
  /**
@@ -121,7 +137,7 @@ export default class MPDirectionsRenderer {
121
137
  */
122
138
  public async setDefaultRouteStopIcon(icon: RouteStopIconConfig): Promise<void> {
123
139
  this._defaultRouteStopIcon = icon;
124
- await DirectionsRenderer.setDefaultRouteStopIcon(icon.getImage().toString());
140
+ await DirectionsRenderer.setDefaultRouteStopIcon(encodeStopIcon(icon));
125
141
  }
126
142
 
127
143
  /**
@@ -1,5 +1,6 @@
1
1
  import { NativeModules } from 'react-native';
2
2
  import { MPError, MPPoint, MPRoute, MPHighway } from "../../index";
3
+ import { attachNativeRoute } from './RouteHandles';
3
4
 
4
5
  const { DirectionsService } = NativeModules;
5
6
 
@@ -114,7 +115,9 @@ export default class MPDirectionsService {
114
115
  res = await DirectionsService.getRoute(JSON.stringify(origin), JSON.stringify(destination), stopsAsJson, optimze, this.id);
115
116
  }
116
117
  if (res.route !== undefined) {
117
- return Promise.resolve(MPRoute.create(JSON.parse(res.route)));
118
+ const route = MPRoute.create(JSON.parse(res.route));
119
+ attachNativeRoute(route, res.routeId);
120
+ return Promise.resolve(route);
118
121
  } else {
119
122
  return Promise.reject(MPError.create(JSON.parse(res.error)));
120
123
  }
@@ -30,10 +30,12 @@ export default class MPRouteStopIconConfig implements RouteStopIconConfig{
30
30
  /**
31
31
  * Internal
32
32
  *
33
- * @returns {URL}
33
+ * Not a URL: wrapping JSON in one throws on spec-compliant URL implementations (Expo 55+).
34
+ *
35
+ * @returns {string}
34
36
  */
35
- getImage(): URL {
36
- return new URL(JSON.stringify(this));
37
+ getImage(): string {
38
+ return JSON.stringify(this);
37
39
  }
38
40
 
39
41
  /**
@@ -8,9 +8,28 @@ import {
8
8
  import MPBuildingCollection from './MPBuildingCollection';
9
9
  import MPVenueCollection from './MPVenueCollection';
10
10
  import { EventNames } from './EventNames';
11
+ import { forgetNativeRoutes } from './RouteHandles';
11
12
  import { OnBaseMapCacheProgressListener } from './OnBaseMapCacheProgressListener';
12
13
 
13
14
  const { MapsIndoorsModule } = NativeModules;
15
+
16
+ /**
17
+ * The published version of the map package this file is bundled into, read from its own
18
+ * package.json rather than kept as a constant so it cannot drift from the released version.
19
+ *
20
+ * It is sent on {@link MapsIndoors.load} so the native side can name this wrapper as the component
21
+ * behind the MapsIndoors Insights session. The SDK snapshots the component when the session starts,
22
+ * inside the native load, so the version has to travel on the load call itself.
23
+ */
24
+ const sdkVersion: string = (() => {
25
+ try {
26
+ // Resolved relative to this file inside the installed package: <package root>/package.json.
27
+ return require('../../package.json').version ?? 'unknown';
28
+ } catch (e) {
29
+ return 'unknown';
30
+ }
31
+ })();
32
+
14
33
  /**
15
34
  * Main class for accessing data in the MapsIndoors SDK.
16
35
  *
@@ -38,7 +57,9 @@ export default class MapsIndoors {
38
57
  * @returns {Promise<void>} If the load fails for any reason, it will reject with a {@link MPError}.
39
58
  */
40
59
  public static async load(apiKey: String, venues: String[] = null): Promise<void> {
41
- return MapsIndoorsModule.loadMapsIndoors(apiKey, venues).catch((err: Error) =>
60
+ // Native forgets its kept routes on load; keep the ids in step.
61
+ forgetNativeRoutes();
62
+ return MapsIndoorsModule.loadMapsIndoors(apiKey, venues, sdkVersion).catch((err: Error) =>
42
63
  Promise.reject(MPError.parse(err))
43
64
  );
44
65
  }
@@ -267,6 +288,12 @@ export default class MapsIndoors {
267
288
  /**
268
289
  * Run a query on all available locations with a query and filter.
269
290
  *
291
+ * Selecting one of the returned locations afterwards is reported to MapsIndoors Insights as a
292
+ * search-driven selection (`location_searched`) alongside the plain selection event, but only when
293
+ * the {@link query} carries search text: a call without it, such as a filter-only lookup, marks
294
+ * nothing and also clears the marks left by the previous text search. A location the app found by
295
+ * searching its own data outside this call is never reported as search-driven.
296
+ *
270
297
  * @public
271
298
  * @static
272
299
  * @async
@@ -372,14 +399,19 @@ export default class MapsIndoors {
372
399
  if (positonProvider) {
373
400
  const positionUpdateListener = (position: MPPositionResultInterface) => {
374
401
  if (Platform.OS === 'ios') {
402
+ // The coordinate is [lng, lat] only. floorIndex is optional, and iOS decodes the
403
+ // coordinate as numbers, so an undefined floor here becomes null in the JSON and
404
+ // every update is rejected (MS-3929). A missing floorIndex key defaults to 0 natively.
375
405
  let obj = {
376
- coordinate: [position.point.longitude, position.point.latitude, position.floorIndex],
406
+ coordinate: [position.point.longitude, position.point.latitude],
377
407
  floorIndex: position.floorIndex,
378
408
  bearing: position.bearing,
379
409
  accuracy: position.accuracy,
380
410
  providerName: position.positionProvider
381
411
  }
382
- MapsIndoorsModule.onPositionUpdate(JSON.stringify(obj));
412
+ // Nothing awaits this, so a rejected update would otherwise vanish without a trace.
413
+ MapsIndoorsModule.onPositionUpdate(JSON.stringify(obj))
414
+ .catch((err: any) => console.warn('MapsIndoors: position update rejected', err?.message ?? err));
383
415
  }else {
384
416
  MapsIndoorsModule.onPositionUpdate(JSON.stringify(position));
385
417
  }
@@ -435,6 +467,7 @@ export default class MapsIndoors {
435
467
  * @returns {Promise<void>}
436
468
  */
437
469
  public static async destroy(): Promise<void> {
470
+ forgetNativeRoutes();
438
471
  return MapsIndoorsModule.destroy().then(() => { });
439
472
  }
440
473
 
@@ -0,0 +1,76 @@
1
+ import MPRoute from './MPRoute';
2
+
3
+ /**
4
+ * Links each {@link MPRoute} that {@link MPDirectionsService.getRoute} returns to the native route it
5
+ * was encoded from, so {@link MPDirectionsRenderer.setRoute} can render that native instance instead
6
+ * of decoding a copy (SPEX-2782).
7
+ *
8
+ * Only the native instance knows the route's resolved endpoints, which the SDK reports with the
9
+ * directions Insights events. Neither SDK serialises them, so every decoded copy reports none.
10
+ * Rendering one native instance repeatedly is safe: its endpoints are resolved once and read on every
11
+ * event, never consumed.
12
+ *
13
+ * Keyed by the route's JSON rather than by object, so a route that went through JSON on the app's
14
+ * side, such as a state store or navigation params, still finds its native route. An edited route has
15
+ * different JSON and finds none, so it reports no endpoints rather than ones it may no longer have.
16
+ */
17
+
18
+ /** Matches the native stores, which forget the least recently used route past this many. */
19
+ const CAPACITY = 10;
20
+
21
+ /** Native route ids by route JSON, least recently used first. */
22
+ const ids = new Map<string, string>();
23
+
24
+ let warned = false;
25
+
26
+ /** Records the native route behind a route that {@link MPDirectionsService} just created. */
27
+ export function attachNativeRoute(route: MPRoute, id: string | undefined): void {
28
+ if (!id) {
29
+ return;
30
+ }
31
+ const json = JSON.stringify(route);
32
+ ids.delete(json);
33
+ ids.set(json, id);
34
+ if (ids.size > CAPACITY) {
35
+ ids.delete(ids.keys().next().value!);
36
+ }
37
+ }
38
+
39
+ /**
40
+ * The id of the native route to render in place of `json`, or null to decode `json`.
41
+ *
42
+ * @param json The route as JSON, which the caller sends across the bridge anyway.
43
+ */
44
+ export function nativeRouteId(json: string): string | null {
45
+ const id = ids.get(json);
46
+ if (id === undefined) {
47
+ warnOnce();
48
+ return null;
49
+ }
50
+ ids.delete(json);
51
+ ids.set(json, id);
52
+ return id;
53
+ }
54
+
55
+ /**
56
+ * Forgets every route, as the native stores do when MapsIndoors loads or is destroyed: the routes
57
+ * belong to the solution that was loaded when they were requested.
58
+ */
59
+ export function forgetNativeRoutes(): void {
60
+ ids.clear();
61
+ }
62
+
63
+ /**
64
+ * The fallback is legitimate for a route the app built, but it is also how these endpoints went
65
+ * missing unnoticed before, so development builds say so once.
66
+ */
67
+ function warnOnce(): void {
68
+ if (warned || !(globalThis as { __DEV__?: boolean }).__DEV__) {
69
+ return;
70
+ }
71
+ warned = true;
72
+ console.warn(
73
+ 'MapsIndoors: setRoute was given a route MPDirectionsService.getRoute did not return, or one changed ' +
74
+ 'since. It renders, but directions analytics will not attribute its origin and destination.'
75
+ );
76
+ }
@@ -6,5 +6,9 @@
6
6
  * @typedef {RouteStopIconConfig}
7
7
  */
8
8
  export interface RouteStopIconConfig {
9
- getImage(): URL;
9
+ /**
10
+ * The icon image. An http(s) URL is downloaded by the native SDK; anything else is passed on as
11
+ * an encoded MPRouteStopIconConfig.
12
+ */
13
+ getImage(): URL | string;
10
14
  }