-
-
Notifications
You must be signed in to change notification settings - Fork 937
Expand file tree
/
Copy pathRNMBXCamera.swift
More file actions
760 lines (644 loc) · 21.5 KB
/
RNMBXCamera.swift
File metadata and controls
760 lines (644 loc) · 21.5 KB
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
import Foundation
import MapboxMaps
import Turf
extension NSNumber {
/// Converts an `NSNumber` to a `CGFloat` value from its `Double` representation.
internal var CGFloat: CGFloat {
CoreGraphics.CGFloat(doubleValue)
}
}
public enum RemovalReason {
case ViewRemoval, StyleChange, OnDestroy, ComponentChange, Reorder
}
/// Base protocol for all map components
public protocol RNMBXMapComponentProtocol: AnyObject {
func waitForStyleLoad() -> Bool
}
/// Default implementation: most components don't need to wait for style load
extension RNMBXMapComponentProtocol {
public func waitForStyleLoad() -> Bool {
return false
}
}
/// Protocol for components that can work without direct MapView access
public protocol RNMBXMapComponent: RNMBXMapComponentProtocol {
func addToMap(_ map: RNMBXMapView, style: Style)
func removeFromMap(_ map: RNMBXMapView, reason: RemovalReason) -> Bool
}
/// Protocol for components that require a valid MapView instance for both add and remove operations.
/// Use this protocol when your component needs to interact with the native MapView directly.
/// The MapView parameter is guaranteed to be non-nil when these methods are called.
///
/// This protocol inherits from RNMBXMapComponent to ensure compatibility with existing code,
/// but provides default implementations of the base protocol methods that throw errors,
/// forcing implementers to use the mapView-aware versions.
public protocol RNMBXMapAndMapViewComponent: RNMBXMapComponent {
func addToMap(_ map: RNMBXMapView, mapView: MapView, style: Style)
func removeFromMap(_ map: RNMBXMapView, mapView: MapView, reason: RemovalReason) -> Bool
}
/// Default implementations for RNMBXMapAndMapViewComponent that prevent accidental use of base protocol methods
extension RNMBXMapAndMapViewComponent {
public func addToMap(_ map: RNMBXMapView, style: Style) {
Logger.error("CRITICAL: addToMap(_:style:) called on RNMBXMapAndMapViewComponent. Use addToMap(_:mapView:style:) instead. Component: \(type(of: self))")
}
public func removeFromMap(_ map: RNMBXMapView, reason: RemovalReason) -> Bool {
Logger.error("CRITICAL: removeFromMap(_:reason:) called on RNMBXMapAndMapViewComponent. Use removeFromMap(_:mapView:reason:) instead. Component: \(type(of: self))")
return false
}
}
enum CameraMode: Int {
case flight = 1
case ease = 2
case linear = 3
case move = 4
case none = 5
}
enum UserTrackingMode: String {
case none, compass, course, normal
}
struct CameraUpdateItem {
var camera: CameraOptions
var mode: CameraMode
var duration: TimeInterval?
func execute(map: RNMBXMapView, cameraAnimator: inout BasicCameraAnimator?) {
logged("CameraUpdateItem.execute") {
if let center = camera.center {
try center.validate()
}
switch mode {
case .flight:
map.mapView.camera.fly(to: camera, duration: duration)
case .ease:
map.mapView.camera.ease(to: camera, duration: duration ?? 0, curve: .easeInOut, completion: nil)
case .linear:
map.mapView.camera.ease(to: camera, duration: duration ?? 0, curve: .linear, completion: nil)
default:
map.mapboxMap.setCamera(to: camera)
}
}
}
}
class CameraUpdateQueue {
var queue: [CameraUpdateItem] = [];
func dequeue() -> CameraUpdateItem? {
guard !queue.isEmpty else {
return nil
}
return queue.removeFirst()
}
func enqueue(stop: CameraUpdateItem) {
queue.append(stop)
}
func execute(map: RNMBXMapView, cameraAnimator: inout BasicCameraAnimator?) {
guard let stop = dequeue() else {
return
}
stop.execute(map: map, cameraAnimator: &cameraAnimator)
}
}
open class RNMBXMapComponentBase : UIView, RNMBXMapComponent {
private weak var _map: RNMBXMapView! = nil
private var _mapCallbacks: [(RNMBXMapView) -> Void] = []
weak var map : RNMBXMapView? {
return _map;
}
func withMapView(_ callback: @escaping (_ mapView: MapView) -> Void) {
withRNMBXMapView { mapView in
callback(mapView.mapView)
}
}
func withRNMBXMapView(_ callback: @escaping (_ map: RNMBXMapView) -> Void) {
if let map = _map {
callback(map)
} else {
_mapCallbacks.append(callback)
}
}
public func addToMap(_ map: RNMBXMapView, style: Style) {
_mapCallbacks.forEach { callback in
callback(map)
}
_mapCallbacks = []
_map = map
}
public func removeFromMap(_ map: RNMBXMapView, reason: RemovalReason) -> Bool {
_mapCallbacks = []
_map = nil
return true
}
}
/// Base class for components that require MapView to be non-nil
open class RNMBXMapAndMapViewComponentBase : UIView, RNMBXMapAndMapViewComponent {
private weak var _map: RNMBXMapView! = nil
private var _mapCallbacks: [(RNMBXMapView) -> Void] = []
weak var map : RNMBXMapView? {
return _map;
}
func withMapView(_ callback: @escaping (_ mapView: MapView) -> Void) {
withRNMBXMapView { mapView in
callback(mapView.mapView)
}
}
func withRNMBXMapView(_ callback: @escaping (_ map: RNMBXMapView) -> Void) {
if let map = _map {
callback(map)
} else {
_mapCallbacks.append(callback)
}
}
// Uses default implementation from RNMBXMapComponentProtocol extension
public func addToMap(_ map: RNMBXMapView, mapView: MapView, style: Style) {
_mapCallbacks.forEach { callback in
callback(map)
}
_mapCallbacks = []
_map = map
}
public func removeFromMap(_ map: RNMBXMapView, mapView: MapView, reason: RemovalReason) -> Bool {
_mapCallbacks = []
_map = nil
return true
}
}
@objc(RNMBXCamera)
open class RNMBXCamera : RNMBXMapAndMapViewComponentBase {
var cameraAnimator: BasicCameraAnimator?
let cameraUpdateQueue = CameraUpdateQueue()
// MARK: React properties
@objc public var animationDuration: NSNumber?
@objc public var animationMode: NSString?
@objc public var defaultStop: [String: Any]?
@objc public var followUserLocation : Bool = false {
didSet {
_updateCameraFromTrackingMode()
}
}
@objc public var followUserMode: String? {
didSet {
_updateCameraFromTrackingMode()
}
}
@objc public var followZoomLevel: NSNumber? {
didSet {
_updateCameraFromTrackingMode()
}
}
@objc public var followPitch: NSNumber? {
didSet {
_updateCameraFromTrackingMode()
}
}
@objc public var followHeading: NSNumber? {
didSet {
_updateCameraFromTrackingMode()
}
}
@objc public var followPadding: NSDictionary? {
didSet {
_updateCameraFromTrackingMode()
}
}
@objc public var maxZoomLevel: NSNumber? {
didSet { _updateMaxBounds() }
}
@objc public var minZoomLevel: NSNumber? {
didSet { _updateMaxBounds() }
}
@objc public var onUserTrackingModeChange: RCTBubblingEventBlock? = nil
@objc public var stop: [String: Any]? {
didSet {
_updateCamera()
}
}
@objc public var maxBounds: String? {
didSet {
if let maxBounds = maxBounds {
logged("RNMBXCamera.maxBounds") {
maxBoundsFeature = try JSONDecoder().decode(FeatureCollection.self, from: maxBounds.data(using: .utf8)!)
}
} else {
maxBoundsFeature = nil
}
_updateMaxBounds()
}
}
var maxBoundsFeature : FeatureCollection? = nil
// MARK: Update methods
func _updateCameraFromJavascript() {
guard !followUserLocation else {
return
}
guard let stop = stop else {
return
}
/*
V10 TODO
if let map = map, map.userTrackingMode != .none {
map.userTrackingMode = .none
}
*/
if let stops = stop["stops"] as? [[String:Any]] {
stops.forEach {
if let stop = toUpdateItem(stop: $0) {
cameraUpdateQueue.enqueue(stop: stop)
}
}
} else {
if let stop = toUpdateItem(stop: stop) {
cameraUpdateQueue.enqueue(stop: stop)
}
}
if let map = map {
cameraUpdateQueue.execute(map: map, cameraAnimator: &cameraAnimator)
}
}
func _disableUserTracking(_ map: MapView) {
map.viewport.idle()
}
@objc public func updateCameraStop(_ stop: [String: Any]) {
self.stop = stop
}
func _toCoordinateBounds(_ bounds: FeatureCollection) throws -> CoordinateBounds {
guard bounds.features.count == 2 else {
throw RNMBXError.paramError("Expected two Points in FeatureColletion")
}
let swFeature = bounds.features[0]
let neFeature = bounds.features[1]
guard case let .point(sw) = swFeature.geometry,
case let .point(ne) = neFeature.geometry else {
throw RNMBXError.paramError("Expected two Points in FeatureColletion")
}
return CoordinateBounds(southwest: sw.coordinates, northeast: ne.coordinates)
}
func _updateMaxBounds() {
withMapView { map in
let current = map.mapboxMap.cameraBounds
var options = CameraBoundsOptions()
if let maxBounds = self.maxBoundsFeature {
logged("RNMBXCamera._updateMaxBounds._toCoordinateBounds") {
options.bounds = try self._toCoordinateBounds(maxBounds)
}
} else {
options.bounds = nil
}
options.minZoom = self.minZoomLevel?.CGFloat
options.maxZoom = self.maxZoomLevel?.CGFloat
options.minPitch = current.minPitch
options.maxPitch = current.maxPitch
logged("RNMBXCamera._updateMaxBounds") {
try map.mapboxMap.setCameraBounds(with: options)
}
}
}
func _updateCameraFromTrackingMode() {
withMapView { map in
let userTrackingMode = UserTrackingMode(rawValue: self.followUserMode ?? UserTrackingMode.normal.rawValue)
guard let userTrackingMode = userTrackingMode else {
Logger.error("RNMBXCamera: Unexpected followUserMode \(optional: self.followUserMode)")
self._disableUserTracking(map)
return
}
guard self.followUserLocation && userTrackingMode != .none else {
self._disableUserTracking(map)
return
}
if let locationModule = RNMBXLocationModule.shared {
locationModule.override(for: map.location)
}
var trackingModeChanged = false
var followOptions = FollowPuckViewportStateOptions()
switch userTrackingMode {
case .none:
Logger.assert("RNMBXCamera, userTrackingModes should not be none here")
case .compass:
followOptions.bearing = FollowPuckViewportStateBearing.heading
trackingModeChanged = true
case .course:
followOptions.bearing = FollowPuckViewportStateBearing.course
trackingModeChanged = true
case .normal:
followOptions.bearing = nil
trackingModeChanged = true
}
if let onUserTrackingModeChange = self.onUserTrackingModeChange {
if (trackingModeChanged) {
let event = RNMBXEvent(type: .onUserTrackingModeChange, payload: ["followUserMode": self.followUserMode ?? "normal", "followUserLocation": self.followUserLocation])
onUserTrackingModeChange(event.toJSON())
}
}
if let zoom = self.followZoomLevel as? CGFloat {
if (zoom >= 0.0) {
followOptions.zoom = zoom
}
}
if let followPitch = self.followPitch as? CGFloat {
if (followPitch >= 0.0) {
followOptions.pitch = followPitch
}
} else if let stopPitch = self.stop?["pitch"] as? CGFloat {
if (stopPitch >= 0.0) {
followOptions.pitch = stopPitch
}
} else {
followOptions.pitch = nil
}
var _camera = CameraOptions()
if let followHeading = self.followHeading as? CGFloat {
if (followHeading >= 0.0) {
_camera.bearing = followHeading
}
} else if let stopHeading = self.stop?["heading"] as? CGFloat {
if (stopHeading >= 0.0) {
_camera.bearing = stopHeading
}
}
if let padding = self.followPadding {
let edgeInsets = UIEdgeInsets(
top: padding["paddingTop"] as? Double ?? 0,
left: padding["paddingLeft"] as? Double ?? 0,
bottom: padding["paddingBottom"] as? Double ?? 0,
right: padding["paddingRight"] as? Double ?? 0
)
followOptions.padding = edgeInsets
}
let followState = map.viewport.makeFollowPuckViewportState(options: followOptions)
map.viewport.transition(to: followState)
map.viewport.addStatusObserver(self)
map.mapboxMap.setCamera(to: _camera)
}
}
private func toUpdateItem(stop: [String: Any]) -> CameraUpdateItem? {
if (stop.isEmpty) {
return nil
}
var zoom: CGFloat?
if let z = stop["zoom"] as? Double {
zoom = CGFloat(z)
}
var pitch: CGFloat?
if let p = stop["pitch"] as? Double {
pitch = CGFloat(p)
}
var heading: CLLocationDirection?
if let h = stop["heading"] as? Double {
heading = CLLocationDirection(h)
}
var padding: UIEdgeInsets = UIEdgeInsets(
top: stop["paddingTop"] as? Double ?? 0,
left: stop["paddingLeft"] as? Double ?? 0,
bottom: stop["paddingBottom"] as? Double ?? 0,
right: stop["paddingRight"] as? Double ?? 0
)
var camera: CameraOptions?
if let feature = stop["centerCoordinate"] as? String {
let centerFeature : Turf.Feature? = logged("RNMBXCamera.toUpdateItem.decode.cc") { try
JSONDecoder().decode(Turf.Feature.self, from: feature.data(using: .utf8)!)
}
var center: LocationCoordinate2D?
switch centerFeature?.geometry {
case .point(let centerPoint):
center = centerPoint.coordinates
default:
Logger.log(level: .error, message: "RNMBXCamera.toUpdateItem: Unexpected geometry: \(String(describing: centerFeature?.geometry))")
return nil
}
camera = CameraOptions(
center: center,
padding: padding,
anchor: nil,
zoom: zoom,
bearing: heading,
pitch: pitch
)
} else if let feature = stop["bounds"] as? String {
let collection : Turf.FeatureCollection? = logged("RNMBXCamera.toUpdateItem.decode.bound") { try
JSONDecoder().decode(Turf.FeatureCollection.self, from: feature.data(using: .utf8)!) }
let features = collection?.features
let ne: CLLocationCoordinate2D
switch features?.first?.geometry {
case .point(let point):
ne = point.coordinates
default:
Logger.log(level: .error, message: "RNMBXCamera.toUpdateItem: Unexpected geometry: \(String(describing: features?.first?.geometry))")
return nil
}
let sw: CLLocationCoordinate2D
switch features?.last?.geometry {
case .point(let point):
sw = point.coordinates
default:
Logger.log(level: .error, message: "RNMBXCamera.toUpdateItem: Unexpected geometry: \(String(describing: features?.last?.geometry))")
return nil
}
withMapView { map in
let bounds = [sw, ne]
camera = map.mapboxMap.camera(
for: bounds,
padding: padding,
bearing: heading ?? map.mapboxMap.cameraState.bearing,
pitch: pitch ?? map.mapboxMap.cameraState.pitch
)
}
} else {
camera = CameraOptions(
center: nil,
padding: padding,
anchor: nil,
zoom: zoom,
bearing: heading,
pitch: pitch
)
}
guard let camera = camera else {
return nil
}
var duration: TimeInterval?
if let d = stop["duration"] as? Double {
duration = toSeconds(d)
}
var mode: CameraMode = .flight
if let m = stop["mode"] as? NSNumber, let m = CameraMode(rawValue: m.intValue) {
mode = m
}
return CameraUpdateItem(
camera: camera,
mode: mode,
duration: duration
)
}
func _updateCamera() {
if let _ = map {
if followUserLocation {
self._updateCameraFromTrackingMode()
} else {
self._updateCameraFromJavascript()
}
}
}
func _setInitialCamera() {
guard let stop = self.defaultStop, let map = map else {
return
}
if var updateItem = toUpdateItem(stop: stop) {
updateItem.mode = .none
updateItem.duration = 0
updateItem.execute(map: map, cameraAnimator: &cameraAnimator)
}
}
func initialLayout() {
_setInitialCamera()
_updateCamera()
}
public override func addToMap(_ map: RNMBXMapView, mapView: MapView, style: Style) {
super.addToMap(map, mapView: mapView, style: style)
map.reactCamera = self
}
public override func removeFromMap(_ map: RNMBXMapView, mapView: MapView, reason: RemovalReason) -> Bool {
if (reason == .StyleChange) {
return false
}
mapView.viewport.removeStatusObserver(self)
return super.removeFromMap(map, mapView: mapView, reason: reason)
}
@objc public func moveBy(x: Double, y: Double, animationMode: Double, animationDuration: Double, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
withMapView { mapView in
let contentFrame = mapView.bounds.inset(by: mapView.safeAreaInsets)
let centerPoint = CGPoint(x: contentFrame.midX, y: contentFrame.midY)
let endCameraPoint = CGPoint(x: centerPoint.x + x, y: centerPoint.y + y)
let cameraOptions = mapView.mapboxMap.dragCameraOptions(from: centerPoint, to: endCameraPoint)
let duration = animationDuration / 1000
if (duration == 0.0) {
mapView.mapboxMap.setCamera(to: cameraOptions)
resolve(nil)
return
}
var curve: UIView.AnimationCurve = .linear
if let m = CameraMode(rawValue: Int(animationMode)) {
curve = m == CameraMode.ease ? .easeInOut : .linear
}
mapView.camera.ease(to: cameraOptions, duration: duration, curve: curve, completion: { _ in resolve(nil) })
}
}
@objc public func scaleBy(
x: Double,
y: Double,
scaleFactor: Double,
animationMode: Double,
animationDuration: Double,
resolve: @escaping RCTPromiseResolveBlock,
reject: @escaping RCTPromiseRejectBlock
) {
withMapView { mapView in
let currentZoom = mapView.cameraState.zoom
let newZoom = currentZoom + log2(scaleFactor)
let anchor = CGPoint(x: x, y: y)
let cameraOptions = CameraOptions(anchor: anchor, zoom: newZoom)
let duration = animationDuration / 1000
if (duration == 0.0) {
mapView.mapboxMap.setCamera(to: cameraOptions)
resolve(nil)
return
}
var curve: UIView.AnimationCurve = .linear
if let m = CameraMode(rawValue: Int(animationMode)) {
curve = m == CameraMode.ease ? .easeInOut : .linear
}
mapView.camera.ease(to: cameraOptions, duration: duration, curve: curve) { _ in
resolve(nil)
}
}
}
}
// MARK: - ViewportStatusObserver
extension RNMBXCamera : ViewportStatusObserver {
func toDict(_ status: ViewportStatus) -> [String: Any] {
switch (status) {
case .idle:
return ["state":"idle"]
case .state(let state):
return ["state":String(describing: type(of: state))]
case .transition(let transition, toState: let toState):
return [
"transition": String(describing: type(of: transition)),
"state":String(describing: type(of: toState))
]
}
}
func toFollowUserLocation(_ status: ViewportStatus) -> Bool {
switch status {
case .idle:
return false
case .state(_):
return true
case .transition(_, toState: _):
return true
}
}
func toFollowUserMode(_ state: ViewportState) -> String? {
if let state = state as? FollowPuckViewportState {
switch state.options.bearing {
case .heading:
return "compass"
case .course:
return "course"
case .some(let bearing):
return "constant"
case .none:
return "normal"
}
} else if let state = state as? OverviewViewportState {
return "overview"
} else {
return "custom"
}
}
func toFollowUserMode(_ status: ViewportStatus) -> String? {
switch status {
case .idle:
return nil
case .state(let state):
return toFollowUserMode(state)
case .transition(_, toState: let state):
return toFollowUserMode(state)
}
}
func toString(_ reason: ViewportStatusChangeReason) -> String {
if reason == .idleRequested {
return "idleRequested"
} else if reason == .transitionFailed {
return "transitionFailed"
} else if reason == .transitionStarted {
return "transitionStarted"
} else if reason == .transitionSucceeded {
return "transitionSucceeded"
} else if reason == .userInteraction {
return "userInteraction"
} else {
return "unkown \(reason)"
}
}
public func viewportStatusDidChange(from fromStatus: ViewportStatus,
to toStatus: ViewportStatus,
reason: ViewportStatusChangeReason)
{
if (reason == .userInteraction) {
followUserLocation = toFollowUserLocation(toStatus)
if let onUserTrackingModeChange = onUserTrackingModeChange {
let event = RNMBXEvent(
type: .onUserTrackingModeChange,
payload: [
"followUserMode": toFollowUserMode(toStatus) as Any,
"followUserLocation": followUserLocation,
"fromViewportStatus": toDict(fromStatus),
"toViewportState": toDict(toStatus),
"reason": toString(reason)
]
)
onUserTrackingModeChange(event.toJSON())
}
}
}
}
private func toSeconds(_ ms: Double) -> TimeInterval {
return ms * 0.001
}