Skip to content
10 changes: 6 additions & 4 deletions Sources/TripKit/model/TKSegment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ public class TKSegment: NSObject {
self.end = location
self.reference = nil
self.templateHashCode = 0
self.index = -1

super.init()
}
Expand All @@ -79,6 +80,7 @@ public class TKSegment: NSObject {
self.start = template?.start
self.end = template?.end
self.templateHashCode = template?.hashCode?.intValue ?? 0
self.index = Int(reference.index)

super.init()
}
Expand Down Expand Up @@ -148,6 +150,10 @@ public class TKSegment: NSObject {

public var templateHashCode: Int

/// Position in the trip's segments, or -1 for terminals. Captured, as a real-
/// time update can delete the reference, while the segment is still shown.
public let index: Int

public var color: TKColor {
if let color = service?.color {
return color
Expand Down Expand Up @@ -538,10 +544,6 @@ extension TKSegment {

extension TKSegment {

public var index: Int {
reference.map { Int($0.index) } ?? -1
}

@objc
public func triggerRealTimeKVO() {
let time = self.departureTime
Expand Down
8 changes: 8 additions & 0 deletions Sources/TripKitUI/cards/TKUITripOverviewCard.swift
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ public class TKUITripOverviewCard: TKUITableCard {

private weak var tableView: UITableView?

private weak var tripTitle: TKUITripTitleView?

private lazy var notificationFooterView = TKUINotificationView.newInstance()

var tripMapManager: TKUITripMapManager? { mapManager as? TKUITripMapManager }
Expand All @@ -87,6 +89,7 @@ public class TKUITripOverviewCard: TKUITableCard {

let tripTitle = TKUITripTitleView.newInstance()
tripTitle.configure(with: .init(trip, allowFading: false))
self.tripTitle = tripTitle

let style: UITableView.Style
if #available(iOS 26.0, *) {
Expand Down Expand Up @@ -180,6 +183,11 @@ public class TKUITripOverviewCard: TKUITableCard {
viewModel.error
.emit(onNext: { [weak self] in self?.controller?.show($0) })
.disposed(by: disposeBag)

// Real-time updates change the times, and can replace the segments
viewModel.titleModel
.drive(onNext: { [weak self] in self?.tripTitle?.configure(with: $0) })
.disposed(by: disposeBag)

// We wait for the table view to have a width before showing attribution
// and card actions view, otherwise we'd get AL warnings due to the table
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,41 @@ extension TKUIRoutingResultsViewModel {

extension TKUIRoutingResultsViewModel {

/// The trip groups to show, re-emitting whenever what's shown of them changes
static func observeTripGroups(_ requests: Observable<(TripRequest, mutable: Bool)>) -> Observable<([TripGroup], mutable: Bool)> {
// This picks up CoreData changes of the trip group itself, but ...
let tripGroupsUpdated = fetchTripGroups(requests)
.share(replay: 1, scope: .forever)
.distinctUntilChanged { $0.0 == $1.0 }

// ... what we show are the trips, so we'll also need to pick up real-time
// updates of those, which change them in place, and can change their order
let tripsChanged = requests
.flatMapLatest { tuple -> Observable<Void> in
guard let context = tuple.0.managedObjectContext else { return .empty() }
return context.rx
.fetchObjects(
Trip.self,
sortDescriptors: [NSSortDescriptor(key: "departureTime", ascending: true)],
predicate: NSPredicate(format: "tripGroup.request = %@", tuple.0)
)
.skip(1) // only the changes
.map { _ in }
}
.throttle(.milliseconds(500), scheduler: MainScheduler.instance)
.share()
let tripGroupsRefreshed = Observable.merge(
NotificationCenter.default.rx.notification(.TKUIUpdatedRealTimeData).map { _ in },
tripsChanged
)
.withLatestFrom(tripGroupsUpdated)

// ... and what we then use is the combination of the two. Important to
// *not* call `.distinctUntilChanged` here, as the TripGroup would not
// always have changed, but instead the nested Trip.
return Observable.merge([tripGroupsUpdated, tripGroupsRefreshed])
}

static func fetchTripGroups(_ requests: Observable<(TripRequest, mutable: Bool)>) -> Observable<([TripGroup], mutable: Bool)> {
return requests.flatMapLatest { tuple -> Observable<([TripGroup], mutable: Bool)> in
let request = tuple.0
Expand Down
15 changes: 1 addition & 14 deletions Sources/TripKitUI/view model/TKUIRoutingResultsViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -111,20 +111,7 @@ class TKUIRoutingResultsViewModel {
let requestToShowWithBuilder = requestChangedWithBuilder.map { (request: $0.0, builder: $0.2) }
let updateableRequest = requestChanged.compactMap { $0.1 == true ? $0.0 : nil }

// This picks up CoreData changes of the trip group itself, but ...
let tripGroupsUpdated = TKUIRoutingResultsViewModel.fetchTripGroups(requestChanged)
.share(replay: 1, scope: .forever)
.distinctUntilChanged { $0.0 == $1.0 }

// ... what we show is the trip, so we'll also need to pick up real-time
// updates of those...
let tripGroupsRefreshed = NotificationCenter.default.rx.notification(.TKUIUpdatedRealTimeData)
.withLatestFrom(tripGroupsUpdated)

// ... and what we then use is the combination of the two. Important to
// *not* call `.distinctUntilChanged` here, as the TripGroup would not
// always have changed, but instead the nested Trip.
let tripGroupsChanged = Observable.merge([tripGroupsUpdated, tripGroupsRefreshed])
let tripGroupsChanged = Self.observeTripGroups(requestChanged)

let builderChanged = builderChangedWithID.map(\.0)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -437,11 +437,14 @@ fileprivate extension TKSegment {
extension TKUITripOverviewViewModel.Item: IdentifiableType {
typealias Identity = String
var identity: Identity {
// By position rather than template hash code, as a real-time update can
// replace the templates, which would make the table delete and re-insert
// every row rather than reload them in place
switch self {
case .terminal(let item): return item.isStart ? "Start" : "End"
case .stationary(let item): return "stationary-item-hashCode:" + String(describing: item.segment.templateHashCode)
case .moving(let item): return "moving-item-hashCode:" + String(describing: item.segment.templateHashCode)
case .alert(let item): return "alert-item-hashCode:" + String(describing: item.segment.templateHashCode)
case .stationary(let item): return "stationary-item-index:\(item.segment.index)"
case .moving(let item): return "moving-item-index:\(item.segment.index)"
case .alert(let item): return "alert-item-index:\(item.segment.index)"
case .impossible: return "Impossible"
}
}
Expand Down
25 changes: 20 additions & 5 deletions Sources/TripKitUI/view model/TKUITripOverviewViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,13 @@ class TKUITripOverviewViewModel {
var isVisible: Driver<Bool> = .just(true)
}

init(presentedTrip: Infallible<Trip>, inputs: UIInput = UIInput(), includeTimeToLeaveNotification: Bool) {
/// - Parameter realTimeUpdates: Updates of the trip, given the trip and whether the card is visible
init(
presentedTrip: Infallible<Trip>,
inputs: UIInput = UIInput(),
includeTimeToLeaveNotification: Bool,
realTimeUpdates: @escaping (Trip, Observable<Bool>) -> Observable<Trip> = { TKRealTimeFetcher.rx.streamUpdates($0, active: $1) }
) {

//MARK: Content

Expand All @@ -46,20 +52,22 @@ class TKUITripOverviewViewModel {
.map { trip }
}

refreshMap = Observable.merge(tripChanged, servicesFetched)
.asAssertingSignal()

let tripUpdated: Infallible<Trip> = presentedTrip
.asObservable()
.flatMapLatest {
return TKRealTimeFetcher.rx.streamUpdates($0, active: inputs.isVisible.asObservable())
return realTimeUpdates($0, inputs.isVisible.asObservable())
.startWith($0)
.catchAndReturn($0)
}
.share(replay: 1, scope: .forever)
.asObservable()
.observe(on: MainScheduler.instance)
.asInfallible { _ in .empty() }

// Real-time updates change the departure times on the map, and can
// replace the segments that its annotations are
refreshMap = Observable.merge(tripChanged, servicesFetched, tripUpdated.asObservable().skip(1))
.asAssertingSignal()

sections = tripUpdated
.map(Self.buildSections)
Expand All @@ -70,6 +78,10 @@ class TKUITripOverviewViewModel {
(TKUITripOverviewCard.config.tripActionsFactory?(updated) ?? [], updated)
}
.asDriver(onErrorDriveWith: .never())

titleModel = tripUpdated
.map { TKUITripCell.Model($0, allowFading: false) }
.asDriver(onErrorDriveWith: .never())

//MARK: User interaction

Expand Down Expand Up @@ -124,6 +136,9 @@ class TKUITripOverviewViewModel {

let actions: Driver<([TKUITripOverviewCard.TripAction], Trip)>

/// The card's title, with the trip's current times and segments
let titleModel: Driver<TKUITripCell.Model>

let dataSources: Driver<[TKAPI.DataAttribution]>

let notificationKinds: Driver<Set<TKAPI.TripNotification.MessageKind>>
Expand Down
86 changes: 77 additions & 9 deletions Sources/TripKitUI/views/TKUITripSegmentsView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ public class TKUITripSegmentsView : UIView {
/// - mainSegmentIndex: Index of the trip's main segment in `segments`. Defaults to the first segment with a fixed departure time.
/// - allowInfoIcons: Whether to show info icons, e.g., for alerts
public func configure(_ segments: [TKUITripSegmentDisplayable], mainSegmentIndex: Int? = nil, allowInfoIcons: Bool = true) {
// Captured, as this gets re-applied when the size changes, by when a real-
// time update might have deleted a `TKSegment`'s data, making it return defaults
let segments: [TKUITripSegmentDisplayable] = segments.map(Snapshot.init)
self.mainSegmentIndex = mainSegmentIndex
self.reconfigure = { [weak self] in
self?.configure(segments, mainSegmentIndex: mainSegmentIndex, allowInfoIcons: allowInfoIcons)
Expand Down Expand Up @@ -186,7 +189,11 @@ public class TKUITripSegmentsView : UIView {
let mask = autoresizingMask

let textFont = TKStyleManager.customFont(forTextStyle: .subheadline)
let badgeFont = TKStyleManager.semiboldCustomFont(forTextStyle: .subheadline)
// So that whether a trip's details fit doesn't depend on how many narrow
// "1"s are in its routes and times, which would show trips in the same
// list differently
let timeFont = textFont.withMonospacedDigits
let badgeFont = TKStyleManager.semiboldCustomFont(forTextStyle: .subheadline).withMonospacedDigits

let mainIndex = mainSegmentIndex ?? segments.firstIndex { $0.tripSegmentFixedDepartureTime != nil }

Expand Down Expand Up @@ -290,7 +297,7 @@ public class TKUITripSegmentsView : UIView {
if showDetails, let fixedTime {
let time = TKStyleManager.timeString(fixedTime, for: segment.tripSegmentTimeZone ?? .current)
let realTime = segment.tripSegmentTimesAreRealTime ? UIImageView(asRealTimeAccessoryImageAnimated: true, tintColor: lightTextColor) : nil
add(PillView(text: time, font: textFont, textColor: darkTextColor, borderColor: .tkSeparator, accessory: realTime))
add(PillView(text: time, font: timeFont, textColor: darkTextColor, borderColor: .tkSeparator, accessory: realTime))
}

} else if showDetails, let text = title ?? segment.tripSegmentDistanceInMetres.map(Self.distanceString) {
Expand Down Expand Up @@ -321,17 +328,28 @@ public class TKUITripSegmentsView : UIView {
maxX = x
nextX = x + Self.spacing
count += 1
if details == .everything {
// Ask for the space for everything, even if we then show less
desiredSize = .init(width: maxX, height: maxHeight)
}
}

if limitSize, maxX > frame.width, let fewer = details.next {
configure(segments, details: fewer, allowInfoIcons: allowInfoIcons)
return
if details == .everything {
// Ask for the space for everything, even if we then show less, as this
// view can get its width from that, e.g., in the trip overview's title.
// Rounded up, as layout snaps it to pixels, which can make it too small.
let size = CGSize(width: maxX.rounded(.up), height: maxHeight)
if size != desiredSize {
// Not when first asked for, as `intrinsicContentSize` configures it then
let shouldInvalidate = desiredSize != .zero
desiredSize = size
if shouldInvalidate {
invalidateIntrinsicContentSize()
}
}
}

if limitSize, maxX > frame.width, let fewer = details.next {
configure(segments, details: fewer, allowInfoIcons: allowInfoIcons)
return
}

finishConfiguring(width: maxX, maxHeight: maxHeight, segmentXValues: newSegmentXValues, accessibilityElements: accessibileElements, segmentIndexToSelect: segmentIndexToSelect)
}

Expand Down Expand Up @@ -474,6 +492,43 @@ public class TKUITripSegmentsView : UIView {

extension TKUITripSegmentsView {

/// What this view reads of a segment, captured when configuring
fileprivate struct Snapshot: TKUITripSegmentDisplayable {
let tripSegmentModeColor: TKColor?
let tripSegmentModeImage: TKImage?
let tripSegmentModeImageURL: URL?
let tripSegmentModeImageIsTemplate: Bool
let tripSegmentModeImageIsBranding: Bool
let tripSegmentModeInfoIconType: TKInfoIconType
let tripSegmentSubtitleIconType: TKInfoIconType
let tripSegmentAccessibilityLabel: String?
let tripSegmentModeTitle: String?
let tripSegmentFixedDepartureTime: Date?
let tripSegmentTimeZone: TimeZone?
let tripSegmentTimesAreRealTime: Bool
let tripSegmentDistanceInMetres: Double?
let tripSegmentDuration: TimeInterval?
let tripSegmentIsWalking: Bool

init(_ segment: TKUITripSegmentDisplayable) {
tripSegmentModeColor = segment.tripSegmentModeColor
tripSegmentModeImage = segment.tripSegmentModeImage
tripSegmentModeImageURL = segment.tripSegmentModeImageURL
tripSegmentModeImageIsTemplate = segment.tripSegmentModeImageIsTemplate
tripSegmentModeImageIsBranding = segment.tripSegmentModeImageIsBranding
tripSegmentModeInfoIconType = segment.tripSegmentModeInfoIconType
tripSegmentSubtitleIconType = segment.tripSegmentSubtitleIconType
tripSegmentAccessibilityLabel = segment.tripSegmentAccessibilityLabel
tripSegmentModeTitle = segment.tripSegmentModeTitle
tripSegmentFixedDepartureTime = segment.tripSegmentFixedDepartureTime
tripSegmentTimeZone = segment.tripSegmentTimeZone
tripSegmentTimesAreRealTime = segment.tripSegmentTimesAreRealTime
tripSegmentDistanceInMetres = segment.tripSegmentDistanceInMetres
tripSegmentDuration = segment.tripSegmentDuration
tripSegmentIsWalking = segment.tripSegmentIsWalking
}
}

/// A rounded badge with a text and an optional accessory image
fileprivate class PillView: UIView {

Expand Down Expand Up @@ -530,6 +585,19 @@ extension TKUITripSegmentsView {

}

extension UIFont {
/// The same font, but with all digits the same width, if the font has that
fileprivate var withMonospacedDigits: UIFont {
let descriptor = fontDescriptor.addingAttributes([
.featureSettings: [[
UIFontDescriptor.FeatureKey.type: kNumberSpacingType,
UIFontDescriptor.FeatureKey.selector: kMonospacedNumbersSelector,
]]
])
return UIFont(descriptor: descriptor, size: 0)
}
}

extension String {
fileprivate func size(font: UIFont, maximumWidth: CGFloat = .greatestFiniteMagnitude) -> CGSize {
let context = NSStringDrawingContext()
Expand Down
Loading
Loading