-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathTripViewController.swift
More file actions
603 lines (491 loc) · 22.7 KB
/
Copy pathTripViewController.swift
File metadata and controls
603 lines (491 loc) · 22.7 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
//
// TripViewController.swift
// OBAKit
//
// Copyright © Open Transit Software Foundation
// This source code is licensed under the Apache 2.0 license found in the
// LICENSE file in the root directory of this source tree.
//
import UIKit
import MapKit
import Combine
import FloatingPanel
import OBAKitCore
class TripViewController: UIViewController,
AppContext,
FloatingPanelControllerDelegate,
Idleable,
MKMapViewDelegate,
Previewable {
public let application: Application
let viewModel: TripViewModel
var tripConvertible: TripConvertible { viewModel.tripConvertible }
private var cancellables = Set<AnyCancellable>()
private lazy var dataLoadFeedbackGenerator = DataLoadFeedbackGenerator(application: application)
init(application: Application, tripConvertible: TripConvertible) {
self.application = application
self.viewModel = TripViewModel(application: application, tripConvertible: tripConvertible)
super.init(nibName: nil, bundle: nil)
registerTraitChangeCallback()
}
init(application: Application, arrivalDeparture: ArrivalDeparture) {
self.application = application
self.viewModel = TripViewModel(
application: application,
tripConvertible: TripConvertible(arrivalDeparture: arrivalDeparture)
)
super.init(nibName: nil, bundle: nil)
registerTraitChangeCallback()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func registerTraitChangeCallback() {
let sizeTraits: [UITrait] = [UITraitVerticalSizeClass.self, UITraitHorizontalSizeClass.self, UITraitPreferredContentSizeCategory.self]
registerForTraitChanges(sizeTraits) { (self: Self, _) in
self.updateTitleView()
}
}
// MARK: - UIViewController
lazy var reloadButton: UIBarButtonItem = {
let button = UIBarButtonItem(image: Icons.refresh, style: .plain, target: self, action: #selector(refresh))
button.title = Strings.refresh
return button
}()
let activityIndicatorButton = UIActivityIndicatorView.asNavigationItem()
override func viewDidLoad() {
super.viewDidLoad()
// Don't show user location if accuracy is reduced to avoid user confusion.
mapView.showsUserLocation = application.locationService.isLocationUseAuthorized && application.locationService.accuracyAuthorization == .fullAccuracy
mapView.showsTraffic = application.mapRegionManager.mapViewShowsTraffic
mapView.showsScale = application.mapRegionManager.mapViewShowsScale
application.mapRegionManager.registerAnnotationViews(mapView: mapView)
updateTitleView()
view.addSubview(mapView)
mapView.pinToSuperview(.edges)
bindViewModel()
if !isBeingPreviewed {
floatingPanel.addPanel(toParent: self)
}
let appearance = UINavigationBarAppearance()
appearance.configureWithDefaultBackground()
navigationItem.scrollEdgeAppearance = appearance
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
disableIdleTimer()
beginUserActivity()
viewModel.start()
setContentScrollView(tripDetailsController.listView, for: .bottom)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
updateVoiceover()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
enableIdleTimer()
viewModel.deactivate()
}
// MARK: - NSUserActivity
/// Creates and assigns an `NSUserActivity` object corresponding to this trip.
private func beginUserActivity() {
guard
let region = application.regionsService.currentRegion,
let activity = application.userActivityBuilder?.userActivity(for: tripConvertible, region: region)
else {
return
}
self.userActivity = activity
}
// MARK: Previewable
/// Set this to `true` before `viewDidLoad` to present the UI in a stripped-down 'preview mode'
/// suitable for display in a context menu.
var isBeingPreviewed = false
func enterPreviewMode() {
isBeingPreviewed = true
}
func exitPreviewMode() {
isBeingPreviewed = false
if isViewLoaded, floatingPanel.parent == nil {
floatingPanel.addPanel(toParent: self)
floatingPanel.move(to: .half, animated: true)
}
tripDetailsController.listView.applyData()
}
// MARK: - Title View
private let titleView = StackedMarqueeTitleView(width: 178.0)
private func updateTitleView() {
navigationItem.titleView = isAccessibility ? nil : titleView
guard let tripStatus = tripConvertible.tripStatus else {
title = nil
titleView.topLabel.text = ""
titleView.bottomLabel.text = ""
return
}
let parts = [tripStatus.vehicleID, tripStatus.activeTrip.route.shortName].compactMap { $0 }
if parts.count > 0 {
titleView.topLabel.text = parts.joined(separator: " - ")
}
if let vehicleID = tripStatus.vehicleID {
title = vehicleID
}
if let lastUpdate = tripStatus.lastUpdate {
let format = OBALoc("trip_details_controller.last_report_fmt", value: "Last report: %@", comment: "Last report: <TIME>")
let time = application.formatters.timeFormatter.string(from: lastUpdate)
titleView.bottomLabel.text = String(format: format, time)
}
}
// MARK: - Drawer/Trip Details UI
var showTripDetails: Bool = false {
didSet {
guard oldValue != self.showTripDetails else { return }
UIView.animate(withDuration: 0.1) {
self.tripDetailsController.setListVisibility(isVisible: self.showTripDetails)
}
}
}
private lazy var tripDetailsController = TripFloatingPanelController(
application: application,
tripConvertible: tripConvertible,
parentTripViewController: self
)
/// The floating panel controller, which displays a drawer at the bottom of the map.
private lazy var floatingPanel: OBAFloatingPanelController = {
let panel = OBAFloatingPanelController(application, delegate: self)
panel.isRemovalInteractionEnabled = false
panel.surfaceView.appearance.cornerRadius = ThemeMetrics.cornerRadius
panel.contentMode = .fitToBounds
// Set a content view controller.
panel.set(contentViewController: tripDetailsController)
return panel
}()
public func floatingPanel(_ vc: FloatingPanelController, layoutFor newCollection: UITraitCollection) -> FloatingPanelLayout {
let layout: FloatingPanelLayout
switch newCollection.horizontalSizeClass {
case .regular:
layout = MapPanelLandscapeLayout(initialState: .tip)
default:
layout = MapPanelLayout(initialState: .tip)
}
return layout
}
func floatingPanelDidMove(_ vc: FloatingPanelController) {
showTripDetails = true
}
func floatingPanelDidChangeState(_ fpc: FloatingPanelController) {
showTripDetails = fpc.state != .tip
tripDetailsController.configureView(for: fpc.state)
if fpc.state != .full {
if traitCollection.horizontalSizeClass == .regular {
mapView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 0, leading: MapPanelLandscapeLayout.WidthSize + ThemeMetrics.padding, bottom: 0, trailing: 0)
} else {
let bottom: CGFloat
if fpc.state == .half {
bottom = self.view.safeAreaLayoutGuide.layoutFrame.height / 2
} else {
bottom = MapPanelLayout.EstimatedDrawerTipStateHeight
}
mapView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: bottom, trailing: 0)
}
}
}
func showStopOnMap(_ tripStop: TripStopViewModel) {
floatingPanel.move(to: .half, animated: true) { [weak self] in
self?.selectedStopTime = tripStop.stopTime
}
}
func updateVoiceover() {
if UIAccessibility.isVoiceOverRunning {
self.floatingPanel.move(to: .full, animated: true)
}
}
// MARK: - Map Data
private var currentTripStatus: TripStatus? {
didSet {
guard let currentTripStatus = currentTripStatus else {
removeVehicleAnnotation()
return
}
if let vehicleAnnotation = vehicleAnnotation {
// `tripStatus`'s didSet writes lastKnownLocation onto coordinate
// immediately. Restore `from` so `VehicleCoordinateUpdate` can
// interpolate instead of teleporting (#1341) — same pattern as
// `TripFocusMapLayer.drawVehicle`.
let from = vehicleAnnotation.coordinate
vehicleAnnotation.tripStatus = currentTripStatus
vehicleAnnotation.coordinate = from
// No lastKnownLocation → drop the pin, matching `TripFocusMapLayer`
// (`removeVehicle()` when the feed omits a coordinate). Keeping a
// stale real coordinate used to drag `showAnnotations` zoom and
// skip the null-island filter that the old `(0,0)` fallback hit.
guard let to = currentTripStatus.lastKnownLocation?.coordinate else {
removeVehicleAnnotation()
updateTitleView()
return
}
VehicleCoordinateUpdate.apply(from: from, to: to, on: vehicleAnnotation)
// Update the annotation view's heading and real-time state since
// the annotation property didSet on the view won't re-fire.
if let vehicleAnnotationView = vehicleAnnotationView as? PulsingVehicleAnnotationView {
vehicleAnnotationView.applyTripStatus(currentTripStatus)
}
}
else {
// Don't mint a pin on null island when the feed has no location yet.
guard currentTripStatus.lastKnownLocation != nil else {
updateTitleView()
return
}
vehicleAnnotation = VehicleAnnotation(tripStatus: currentTripStatus)
self.mapView.addAnnotation(vehicleAnnotation!)
}
updateTitleView()
}
}
/// Removes the vehicle annotation from the map and clears the reference.
private func removeVehicleAnnotation() {
if let annotation = vehicleAnnotation {
mapView.removeAnnotation(annotation)
}
vehicleAnnotation = nil
vehicleAnnotationView = nil
}
// MARK: - Load Data
@objc private func refresh(_ sender: Any) {
viewModel.refresh()
}
private func bindViewModel() {
viewModel.shouldSkipProgrammaticRefresh = { UIAccessibility.isVoiceOverRunning }
bindTripContent()
bindRouteOverlay()
bindLoadingState()
}
// MARK: - Map View
/// A subclass of MKMapView that tells you if it has ever been touched by the user.
class TouchesMapView: MKMapView {
/// True if the user touched the map and false otherwise.
var hasBeenTouched = false
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
hasBeenTouched = true
super.touchesBegan(touches, with: event)
}
}
private lazy var mapView: TouchesMapView = {
let map = TouchesMapView.autolayoutNew()
map.delegate = self
map.mapType = application.mapRegionManager.userSelectedMapType
map.accessibilityElementsHidden = true
return map
}()
/// Armed by `selectedStopTime`'s `didSet` immediately before a programmatic
/// `selectAnnotation`, and consumed by the `didSelect` it provokes. Riders never
/// assign `selectedStopTime` — their taps arrive as `didSelect` — so every
/// selection this controller makes itself is one the rider did not ask for and
/// must not open a stop page.
public var skipNextStopTimeHighlight = false
public func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
guard let stopTime = view.annotation as? TripStopTime else { return }
defer { skipNextStopTimeHighlight = false }
if skipNextStopTimeHighlight {
// Programmatic select leaves the pin selected. MapKit will not
// re-fire `didSelect` for an already-selected annotation, so the
// first tap on the origin stop would do nothing.
mapView.deselectAnnotation(view.annotation, animated: false)
return
}
// Scroll the list without blinking the row: `openStop` pushes the stop page on
// the next line, so the delayed blink would play underneath it and be over
// before the rider comes back. The scroll still leaves the row on screen for them.
if let stopTimes = tripDetailsController.tripDetails?.stopTimes,
let stopIndex = stopTimes.firstIndex(where: { $0 == stopTime }) {
tripDetailsController.highlightStopInList(stopTime.stop, stopIndex: stopIndex, blinksAfterScroll: false)
} else {
tripDetailsController.highlightStopInList(stopTime.stop, blinksAfterScroll: false)
}
openStop(stopTime, on: mapView)
}
public func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
guard let stopTime = view.annotation as? TripStopTime,
stopTime == self.selectedStopTime else { return }
self.selectedStopTime = nil
}
private func openStop(_ stopTime: TripStopTime, on mapView: MKMapView) {
var transferContext: TransferContext?
if let arrivalDeparture = tripConvertible.arrivalDeparture,
stopTime.stopID != arrivalDeparture.stopID {
transferContext = .from(arrivalDeparture: arrivalDeparture, arrivalDate: stopTime.arrivalDate)
}
// Same reason as `MapViewController`: leaving the tapped pin selected
// only strands a highlight. MapKit will not fire `didSelect` again.
mapView.deselectAnnotation(stopTime, animated: false)
// Callouts are off here, so selection is the open gesture — the same case
// `MapViewController` reports when a stop annotation has no chevron to tap.
application.analytics?.reportEvent(
pageURL: "app://localhost/trip",
label: AnalyticsLabels.mapStopAnnotationTapped,
value: nil
)
application.viewRouter.navigateTo(stop: stopTime.stop, from: self, transferContext: transferContext)
}
// TODO FIXME: DRY up with MapRegionManager
public func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline) // swiftlint:disable:this force_cast
let isSpent = (overlay as? TripShapeOverlay)?.isSpent ?? false
let routeColor = tripConvertible.arrivalDeparture?.route.color ?? ThemeColors.shared.brand
let needsIncreasedVisibility =
traitCollection.userInterfaceStyle == .dark ||
traitCollection.accessibilityContrast == .high ||
UIAccessibility.isReduceTransparencyEnabled
let appearance = TripRouteOverlayAppearance.make(
isSpent: isSpent,
routeColor: routeColor,
needsIncreasedVisibility: needsIncreasedVisibility
)
renderer.strokeColor = appearance.strokeColor
renderer.lineWidth = appearance.lineWidth
renderer.lineCap = .round
return renderer
}
private var routeOverlays: [MKOverlay] = []
private var userLocationAnnotationView: PulsingAnnotationView?
private var vehicleAnnotationView: PulsingAnnotationView?
private var vehicleAnnotation: VehicleAnnotation?
public func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard let reuseIdentifier = reuseIdentifier(for: annotation) else {
return nil
}
let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier, for: annotation)
if let annotationView = annotationView as? PulsingVehicleAnnotationView {
vehicleAnnotationView = annotationView
if let color = tripConvertible.arrivalDeparture?.route.color {
annotationView.realTimeAnnotationColor = color
}
}
else if let annotationView = annotationView as? PulsingAnnotationView {
userLocationAnnotationView = annotationView
}
else if let view = annotationView as? MinimalStopAnnotationView, let arrivalDeparture = tripConvertible.arrivalDeparture {
view.selectedArrivalDeparture = arrivalDeparture
TripMapAnnotationPolicy.apply(to: view)
}
return annotationView
}
private func reuseIdentifier(for annotation: MKAnnotation) -> String? {
switch annotation {
case is VehicleAnnotation: return MKMapView.reuseIdentifier(for: PulsingVehicleAnnotationView.self)
case is MKUserLocation: return MKMapView.reuseIdentifier(for: PulsingAnnotationView.self)
case is TripStopTime: return MKMapView.reuseIdentifier(for: MinimalStopAnnotationView.self)
default: return nil
}
}
public var selectedStopTime: TripStopTime? {
didSet {
guard !isBeingPreviewed else { return }
var animated = true
if isFirstStopTimeLoad {
animated = false
isFirstStopTimeLoad.toggle()
}
self.mapView.deselectAnnotation(oldValue, animated: animated)
guard let selectedStopTime = self.selectedStopTime else { return }
// Fixes #220: Find matching trip stop using stop ID instead of using pointers.
if let annotation = self.mapView.annotations
.filter(type: TripStopTime.self)
.filter({ $0.stopID == selectedStopTime.stopID }).first {
// Arm the skip here rather than at the call sites: this is the only
// statement that can provoke `didSelect`, so an arm can never outlive
// an assignment that found no annotation to select.
skipNextStopTimeHighlight = true
self.mapView.selectAnnotation(annotation, animated: true)
}
}
}
private var isFirstStopTimeLoad = true
private var hasAppliedOriginStopSelection = false
/// Selects the rider's origin stop when trip details first arrive, and only then.
///
/// `$tripDetails` republishes about every 30 seconds. A second programmatic select
/// would fire `didSelect` → `openStop` and push the stop page out from under
/// whatever the rider is doing. There is no rider selection to compare against
/// either: the load-time select is torn down inside its own call stack, because
/// `didSelect` consumes the skip, deselects the pin, and `didDeselect` clears
/// `selectedStopTime`.
func applyOriginStopSelection(from details: TripDetails) {
guard !hasAppliedOriginStopSelection else { return }
guard let arrivalDeparture = tripConvertible.arrivalDeparture else { return }
guard let origin = details.stopTimes.first(where: { $0.stopID == arrivalDeparture.stopID }) else { return }
hasAppliedOriginStopSelection = true
selectedStopTime = origin
}
}
// MARK: - ViewModel Binding
private extension TripViewController {
func bindTripContent() {
viewModel.$tripConvertible
.sink { [weak self] convertible in
guard let self else { return }
tripDetailsController.tripConvertible = convertible
updateTitleView()
}
.store(in: &cancellables)
viewModel.$tripDetails
.sink { [weak self] details in
guard let self else { return }
floatingPanel.surfaceView.grabberHandle.isHidden = details == nil
guard let details else { return }
tripDetailsController.tripDetails = details
mapView.updateAnnotations(with: details.stopTimes)
currentTripStatus = details.status
var annotationsToShow = mapView.annotations.filter { !($0 is MKUserLocation) }
annotationsToShow.removeAll(where: { $0.coordinate.isNullIsland })
if !mapView.hasBeenTouched {
mapView.showAnnotations(annotationsToShow, animated: true)
}
applyOriginStopSelection(from: details)
}
.store(in: &cancellables)
}
func bindRouteOverlay() {
viewModel.$routePolylineCoordinates
.combineLatest(viewModel.$tripDetails)
.sink { [weak self] coordinates, details in
guard let self, let coordinates, coordinates.count >= 2 else { return }
let fraction = details?.status.flatMap {
TripShapeSplit.fraction(
distanceAlongTrip: $0.distanceAlongTrip,
totalDistanceAlongTrip: $0.totalDistanceAlongTrip
)
}
mapView.removeOverlays(routeOverlays)
let overlays = TripRouteOverlays.make(coordinates: coordinates, fraction: fraction)
routeOverlays = overlays
mapView.addOverlays(overlays)
if !mapView.hasBeenTouched {
let fit = overlays.reduce(MKMapRect.null) { $0.union($1.boundingMapRect) }
guard !fit.isNull else { return }
mapView.visibleMapRect = mapView.mapRectThatFits(
fit,
edgePadding: UIEdgeInsets(top: 60, left: 20, bottom: 128, right: 20)
)
}
}
.store(in: &cancellables)
}
func bindLoadingState() {
viewModel.$isLoading
.sink { [weak self] loading in
guard let self else { return }
navigationItem.rightBarButtonItem = loading ? activityIndicatorButton : reloadButton
}
.store(in: &cancellables)
viewModel.$operationError
.compactMap { $0 }
.sink { [weak self] error in
guard let self else { return }
dataLoadFeedbackGenerator.dataLoad(.failed)
Task { await self.application.displayError(error) }
}
.store(in: &cancellables)
}
}