From 1f2dbf675d9016696f08f758b613a6e4d5d8a27f Mon Sep 17 00:00:00 2001 From: Adrian Schoenig Date: Fri, 4 Dec 2026 12:42:58 +1100 Subject: [PATCH 1/7] fix(trip-segments): keep what the segments view shows when it resizes after an update `TKUITripSegmentsView` re-applies its configuration when its size changes, e.g., on rotation, but held on to the segments themselves. A real-time update with new template hash codes deletes those segments' references, after which they return defaults, so every segment showed as non-transit with "1" minute. It now captures what it shows when configuring. Co-Authored-By: Claude Opus 5.5 --- .../views/TKUITripSegmentsView.swift | 40 ++++++ .../TKUITripRealTimeUpdateTest.swift | 118 ++++++++++++++++++ 2 files changed, 158 insertions(+) create mode 100644 Tests/TripKitUITests/TKUITripRealTimeUpdateTest.swift diff --git a/Sources/TripKitUI/views/TKUITripSegmentsView.swift b/Sources/TripKitUI/views/TKUITripSegmentsView.swift index ccf0288f0e5..794f151f8d6 100644 --- a/Sources/TripKitUI/views/TKUITripSegmentsView.swift +++ b/Sources/TripKitUI/views/TKUITripSegmentsView.swift @@ -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) @@ -474,6 +477,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 { diff --git a/Tests/TripKitUITests/TKUITripRealTimeUpdateTest.swift b/Tests/TripKitUITests/TKUITripRealTimeUpdateTest.swift new file mode 100644 index 00000000000..9aeeecee577 --- /dev/null +++ b/Tests/TripKitUITests/TKUITripRealTimeUpdateTest.swift @@ -0,0 +1,118 @@ +// +// TKUITripRealTimeUpdateTest.swift +// TripKitUITests +// +// A real-time update can come back with new template hash codes, which makes +// the parser delete the trip's old segment references and rebuild its +// segments. Views that are still showing the old segments must cope with that. +// + +#if canImport(Testing) + +import CoreData +import Foundation +import Testing +import UIKit + +@testable import TripKit +@testable import TripKitUI + +@MainActor +struct TKUITripRealTimeUpdateTest { + + /// Kept here, as managed objects don't retain their context + private let context: NSManagedObjectContext + + init() throws { + let model = try #require(TKTestCase.model) + let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model) + try coordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil) + context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) + context.persistentStoreCoordinator = coordinator + } + + @Test func segmentsViewKeepsWhatItShowedWhenResizedAfterUpdate() async throws { + let trip = try parseTrip() + + let view = TKUITripSegmentsView(frame: .init(x: 0, y: 0, width: 1000, height: 44)) + view.configure(trip.segments(with: .inSummary)) + view.layoutIfNeeded() + let before = view.texts + #expect(before.contains("U1")) + + try await update(trip, shiftingHashCodesBy: 1) + + // Like rotating, which re-applies the configuration at the new size + view.frame.size.width = 1100 + view.layoutIfNeeded() + #expect(view.texts == before) + } + +} + +// MARK: - Helpers + +extension TKUITripRealTimeUpdateTest { + + private static let fixture = "routing-pt-realtime" + + private func fixtureJSON() throws -> [String: Any] { + let url = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() + .appendingPathComponent("Data", isDirectory: true) + .appendingPathComponent(Self.fixture).appendingPathExtension("json") + return try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any]) + } + + private func response(from json: [String: Any]) throws -> TKAPI.RoutingResponse { + try JSONDecoder().decode(TKAPI.RoutingResponse.self, from: JSONSerialization.data(withJSONObject: json)) + } + + private func parseTrip() throws -> Trip { + let request = try TKRoutingParser.addBlocking(response(from: fixtureJSON()), into: context) + return try #require(request.tripGroups.first?.visibleTrip) + } + + /// Updates the trip from the same response, but with every template hash + /// code changed, like the server does when a template's content changes + private func update(_ trip: Trip, shiftingHashCodesBy offset: Int) async throws { + var json = try fixtureJSON() + let shift = { (value: Any?) in ((value as? Int) ?? 0) + offset } + json["segmentTemplates"] = (json["segmentTemplates"] as? [[String: Any]])?.map { template in + var template = template + template["hashCode"] = shift(template["hashCode"]) + return template + } + json["groups"] = (json["groups"] as? [[String: Any]])?.map { group in + var group = group + group["trips"] = (group["trips"] as? [[String: Any]])?.map { trip in + var trip = trip + trip["mainSegmentHashCode"] = shift(trip["mainSegmentHashCode"]) + trip["segments"] = (trip["segments"] as? [[String: Any]])?.map { segment in + var segment = segment + segment["segmentTemplateHashCode"] = shift(segment["segmentTemplateHashCode"]) + return segment + } + return trip + } + return group + } + let updated = try response(from: json) + + _ = try await withCheckedThrowingContinuation { continuation in + TKRoutingParser.update(trip, from: updated) { continuation.resume(with: $0) } + } + } + +} + +private extension UIView { + /// Texts of all labels in this view and its subviews, from the front + var texts: [String] { + subviews.flatMap { subview in + ((subview as? UILabel)?.text.map { [$0] } ?? []) + subview.texts + } + } +} + +#endif From 6bbafd90be50577094e67d73a72b983f78d9b1ff Mon Sep 17 00:00:00 2001 From: Adrian Schoenig Date: Fri, 4 Dec 2026 12:44:25 +1100 Subject: [PATCH 2/7] fix(trip-overview): update the title with real-time data The trip overview's title was only configured when creating the card, so it kept the initial times, and segments that a real-time update could replace. It now follows the same updates as the rest of the card. Co-Authored-By: Claude Opus 5.5 --- Sources/TripKitUI/cards/TKUITripOverviewCard.swift | 8 ++++++++ .../TripKitUI/view model/TKUITripOverviewViewModel.swift | 7 +++++++ 2 files changed, 15 insertions(+) diff --git a/Sources/TripKitUI/cards/TKUITripOverviewCard.swift b/Sources/TripKitUI/cards/TKUITripOverviewCard.swift index 178e1e891da..496caadb560 100644 --- a/Sources/TripKitUI/cards/TKUITripOverviewCard.swift +++ b/Sources/TripKitUI/cards/TKUITripOverviewCard.swift @@ -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 } @@ -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, *) { @@ -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 diff --git a/Sources/TripKitUI/view model/TKUITripOverviewViewModel.swift b/Sources/TripKitUI/view model/TKUITripOverviewViewModel.swift index dabfc25f688..5805d7af08a 100644 --- a/Sources/TripKitUI/view model/TKUITripOverviewViewModel.swift +++ b/Sources/TripKitUI/view model/TKUITripOverviewViewModel.swift @@ -70,6 +70,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 @@ -124,6 +128,9 @@ class TKUITripOverviewViewModel { let actions: Driver<([TKUITripOverviewCard.TripAction], Trip)> + /// The card's title, with the trip's current times and segments + let titleModel: Driver + let dataSources: Driver<[TKAPI.DataAttribution]> let notificationKinds: Driver> From ecd4a93b4ba39d65da859a36316a0978121bfe65 Mon Sep 17 00:00:00 2001 From: Adrian Schoenig Date: Fri, 4 Dec 2026 12:51:15 +1100 Subject: [PATCH 3/7] fix(trip-overview): reload rows in place when a real-time update changes templates The trip overview's rows were identified by their segment's template hash code. A real-time update with new templates hence gave every row a new identity, which the table animated as deleting all rows and inserting new ones. Rows are now identified by their segment's position, which `TKSegment` now captures, as an update can delete the reference it used to read it from. Co-Authored-By: Claude Opus 5.5 --- Sources/TripKit/model/TKSegment.swift | 10 ++++++---- .../TKUITripOverviewViewModel+Content.swift | 9 ++++++--- .../TripKitUITests/TKUITripRealTimeUpdateTest.swift | 12 ++++++++++++ 3 files changed, 24 insertions(+), 7 deletions(-) diff --git a/Sources/TripKit/model/TKSegment.swift b/Sources/TripKit/model/TKSegment.swift index 2170bdf407c..f54f53a4085 100644 --- a/Sources/TripKit/model/TKSegment.swift +++ b/Sources/TripKit/model/TKSegment.swift @@ -63,6 +63,7 @@ public class TKSegment: NSObject { self.end = location self.reference = nil self.templateHashCode = 0 + self.index = -1 super.init() } @@ -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() } @@ -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 @@ -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 diff --git a/Sources/TripKitUI/view model/TKUITripOverviewViewModel+Content.swift b/Sources/TripKitUI/view model/TKUITripOverviewViewModel+Content.swift index 453b87f025e..d6a70d08504 100644 --- a/Sources/TripKitUI/view model/TKUITripOverviewViewModel+Content.swift +++ b/Sources/TripKitUI/view model/TKUITripOverviewViewModel+Content.swift @@ -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" } } diff --git a/Tests/TripKitUITests/TKUITripRealTimeUpdateTest.swift b/Tests/TripKitUITests/TKUITripRealTimeUpdateTest.swift index 9aeeecee577..92560739ec9 100644 --- a/Tests/TripKitUITests/TKUITripRealTimeUpdateTest.swift +++ b/Tests/TripKitUITests/TKUITripRealTimeUpdateTest.swift @@ -48,6 +48,18 @@ struct TKUITripRealTimeUpdateTest { #expect(view.texts == before) } + @Test func overviewReloadsRowsInPlaceAfterUpdate() async throws { + let trip = try parseTrip() + let before = TKUITripOverviewViewModel.buildSections(for: trip) + + try await update(trip, shiftingHashCodesBy: 1) + + let after = TKUITripOverviewViewModel.buildSections(for: trip) + let changes = try Diff.differencesForSectionedView(initialSections: before, finalSections: after) + #expect(changes.allSatisfy { $0.insertedItems.isEmpty && $0.deletedItems.isEmpty && $0.movedItems.isEmpty }) + #expect(changes.contains { !$0.updatedItems.isEmpty }) + } + } // MARK: - Helpers From f6b4778bae1c799c39b6e3a53a492c39b270475d Mon Sep 17 00:00:00 2001 From: Adrian Schoenig Date: Fri, 4 Dec 2026 13:41:36 +1100 Subject: [PATCH 4/7] fix(trip-segments): ask for the full width, and again when the content changes Where the segments view gets its width from its content, as in the trip overview's title, it stopped measuring at the first segment that didn't fit its initial size, and didn't ask for more when configured again with wider content, e.g., a real-time departure. It then showed fewer details than fit, down to only icons. It now measures everything, rounded up to whole points, and invalidates its intrinsic size when that changes. Co-Authored-By: Claude Opus 5.5 --- .../views/TKUITripSegmentsView.swift | 25 +++-- .../TKUITripRealTimeUpdateTest.swift | 2 +- .../TKUITripSegmentsViewSizingTest.swift | 105 ++++++++++++++++++ 3 files changed, 124 insertions(+), 8 deletions(-) create mode 100644 Tests/TripKitUITests/TKUITripSegmentsViewSizingTest.swift diff --git a/Sources/TripKitUI/views/TKUITripSegmentsView.swift b/Sources/TripKitUI/views/TKUITripSegmentsView.swift index 794f151f8d6..9063b790b85 100644 --- a/Sources/TripKitUI/views/TKUITripSegmentsView.swift +++ b/Sources/TripKitUI/views/TKUITripSegmentsView.swift @@ -324,17 +324,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) } diff --git a/Tests/TripKitUITests/TKUITripRealTimeUpdateTest.swift b/Tests/TripKitUITests/TKUITripRealTimeUpdateTest.swift index 92560739ec9..c7fe5e9ef7c 100644 --- a/Tests/TripKitUITests/TKUITripRealTimeUpdateTest.swift +++ b/Tests/TripKitUITests/TKUITripRealTimeUpdateTest.swift @@ -118,7 +118,7 @@ extension TKUITripRealTimeUpdateTest { } -private extension UIView { +extension UIView { /// Texts of all labels in this view and its subviews, from the front var texts: [String] { subviews.flatMap { subview in diff --git a/Tests/TripKitUITests/TKUITripSegmentsViewSizingTest.swift b/Tests/TripKitUITests/TKUITripSegmentsViewSizingTest.swift new file mode 100644 index 00000000000..e59d3d4d799 --- /dev/null +++ b/Tests/TripKitUITests/TKUITripSegmentsViewSizingTest.swift @@ -0,0 +1,105 @@ +// +// TKUITripSegmentsViewSizingTest.swift +// TripKitUITests +// +// The trip overview's title gets the segments view's width from its intrinsic +// content size, so that has to cover everything, also after configuring it +// again with wider content, e.g., after a real-time update. +// + +#if canImport(Testing) + +import Foundation +import Testing +import UIKit + +import TripKit +@testable import TripKitUI + +@MainActor +struct TKUITripSegmentsViewSizingTest { + + @Test func showsEverythingWhenSizedByContent() { + let (container, view) = makeTitleLikeLayout() + + let scheduled = segments(isRealTime: false) + view.configure(scheduled) + layout(container) + #expect(view.texts == unconstrainedTexts(for: scheduled)) + + let realTime = segments(isRealTime: true) + view.configure(realTime) + layout(container) + #expect(view.texts == unconstrainedTexts(for: realTime)) + } + +} + +// MARK: - Helpers + +extension TKUITripSegmentsViewSizingTest { + + private struct Segment: TKUITripSegmentDisplayable { + var tripSegmentModeColor: TKColor? = nil + var tripSegmentModeImage: TKImage? + var tripSegmentModeTitle: String? = nil + var tripSegmentFixedDepartureTime: Date? = nil + var tripSegmentTimeZone: TimeZone? = nil + var tripSegmentTimesAreRealTime: Bool = false + var tripSegmentDistanceInMetres: Double? = nil + var tripSegmentDuration: TimeInterval? = nil + var tripSegmentIsWalking: Bool = false + var tripSegmentAccessibilityLabel: String? { nil } + } + + private func segments(isRealTime: Bool) -> [TKUITripSegmentDisplayable] { + let walk = UIImage(systemName: "figure.walk") + let bus = UIImage(systemName: "bus") + return [ + Segment(tripSegmentModeImage: walk, tripSegmentDistanceInMetres: 300, tripSegmentDuration: 180, tripSegmentIsWalking: true), + Segment(tripSegmentModeColor: .systemBlue, tripSegmentModeImage: bus, tripSegmentModeTitle: "199", tripSegmentFixedDepartureTime: Date(timeIntervalSince1970: 1_796_272_740), tripSegmentTimeZone: TimeZone(identifier: "Australia/Sydney"), tripSegmentTimesAreRealTime: isRealTime), + Segment(tripSegmentModeImage: walk, tripSegmentDistanceInMetres: 950, tripSegmentDuration: 720, tripSegmentIsWalking: true), + ] + } + + /// Like `TKUITripTitleView`, which has it in a top-aligned vertical stack, + /// with plenty of space, starting with the nib's width + private func makeTitleLikeLayout() -> (UIView, TKUITripSegmentsView) { + let container = UIView(frame: .init(x: 0, y: 0, width: 600, height: 100)) + let stack = UIStackView() + stack.axis = .vertical + stack.alignment = .leading + stack.translatesAutoresizingMaskIntoConstraints = false + container.addSubview(stack) + NSLayoutConstraint.activate([ + stack.leadingAnchor.constraint(equalTo: container.leadingAnchor), + stack.trailingAnchor.constraint(equalTo: container.trailingAnchor), + stack.topAnchor.constraint(equalTo: container.topAnchor), + ]) + + let view = TKUITripSegmentsView(frame: .init(x: 0, y: 0, width: 240, height: 40)) + view.translatesAutoresizingMaskIntoConstraints = false + view.heightAnchor.constraint(equalToConstant: 40).isActive = true + stack.addArrangedSubview(view) + return (container, view) + } + + /// Like the run loop, which lays out again after a size invalidation + private func layout(_ view: UIView) { + for _ in 0..<3 { + view.setNeedsLayout() + view.layoutIfNeeded() + } + } + + /// What the view shows with no size limit, i.e., everything + private func unconstrainedTexts(for segments: [TKUITripSegmentDisplayable]) -> [String] { + let view = TKUITripSegmentsView() + view.configure(segments) + _ = view.intrinsicContentSize + return view.texts + } + +} + +#endif From 0901af4134c21f7a1be30ddc5a2e3b83f82a8214 Mon Sep 17 00:00:00 2001 From: Adrian Schoenig Date: Fri, 4 Dec 2026 13:49:04 +1100 Subject: [PATCH 5/7] fix(trip-overview): refresh the map with real-time updates The trip overview only refreshed its map when showing a different trip or once the services' content was fetched, so departure times on the map stayed as they were then. Real-time updates can also replace the segments that the map's annotations are. The map now refreshes with every real-time update, too. Co-Authored-By: Claude Opus 5.5 --- .../TKUITripOverviewViewModel.swift | 18 ++++++++---- .../TKUITripRealTimeUpdateTest.swift | 29 ++++++++++++++++--- 2 files changed, 38 insertions(+), 9 deletions(-) diff --git a/Sources/TripKitUI/view model/TKUITripOverviewViewModel.swift b/Sources/TripKitUI/view model/TKUITripOverviewViewModel.swift index 5805d7af08a..ca1b23c8108 100644 --- a/Sources/TripKitUI/view model/TKUITripOverviewViewModel.swift +++ b/Sources/TripKitUI/view model/TKUITripOverviewViewModel.swift @@ -26,7 +26,13 @@ class TKUITripOverviewViewModel { var isVisible: Driver = .just(true) } - init(presentedTrip: Infallible, inputs: UIInput = UIInput(), includeTimeToLeaveNotification: Bool) { + /// - Parameter realTimeUpdates: Updates of the trip, given the trip and whether the card is visible + init( + presentedTrip: Infallible, + inputs: UIInput = UIInput(), + includeTimeToLeaveNotification: Bool, + realTimeUpdates: @escaping (Trip, Observable) -> Observable = { TKRealTimeFetcher.rx.streamUpdates($0, active: $1) } + ) { //MARK: Content @@ -46,13 +52,10 @@ class TKUITripOverviewViewModel { .map { trip } } - refreshMap = Observable.merge(tripChanged, servicesFetched) - .asAssertingSignal() - let tripUpdated: Infallible = presentedTrip .asObservable() .flatMapLatest { - return TKRealTimeFetcher.rx.streamUpdates($0, active: inputs.isVisible.asObservable()) + return realTimeUpdates($0, inputs.isVisible.asObservable()) .startWith($0) .catchAndReturn($0) } @@ -60,6 +63,11 @@ class TKUITripOverviewViewModel { .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) diff --git a/Tests/TripKitUITests/TKUITripRealTimeUpdateTest.swift b/Tests/TripKitUITests/TKUITripRealTimeUpdateTest.swift index c7fe5e9ef7c..f7c1a898f4b 100644 --- a/Tests/TripKitUITests/TKUITripRealTimeUpdateTest.swift +++ b/Tests/TripKitUITests/TKUITripRealTimeUpdateTest.swift @@ -14,6 +14,8 @@ import Foundation import Testing import UIKit +import RxSwift + @testable import TripKit @testable import TripKitUI @@ -60,6 +62,25 @@ struct TKUITripRealTimeUpdateTest { #expect(changes.contains { !$0.updatedItems.isEmpty }) } + @Test func overviewRefreshesMapAfterUpdate() throws { + // No public transport, as that'd fetch the services' content + let trip = try parseTrip(fixture: "routing-motorbike") + let updates = PublishSubject() + let viewModel = TKUITripOverviewViewModel( + presentedTrip: .just(trip), + includeTimeToLeaveNotification: false, + realTimeUpdates: { _, _ in updates } + ) + + var refreshes = 0 + let disposable = viewModel.refreshMap.emit(onNext: { _ in refreshes += 1 }) + defer { disposable.dispose() } + let before = refreshes + + updates.onNext(trip) + #expect(refreshes == before + 1) + } + } // MARK: - Helpers @@ -68,11 +89,11 @@ extension TKUITripRealTimeUpdateTest { private static let fixture = "routing-pt-realtime" - private func fixtureJSON() throws -> [String: Any] { + private func fixtureJSON(_ fixture: String = Self.fixture) throws -> [String: Any] { let url = URL(fileURLWithPath: #filePath) .deletingLastPathComponent() .appendingPathComponent("Data", isDirectory: true) - .appendingPathComponent(Self.fixture).appendingPathExtension("json") + .appendingPathComponent(fixture).appendingPathExtension("json") return try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any]) } @@ -80,8 +101,8 @@ extension TKUITripRealTimeUpdateTest { try JSONDecoder().decode(TKAPI.RoutingResponse.self, from: JSONSerialization.data(withJSONObject: json)) } - private func parseTrip() throws -> Trip { - let request = try TKRoutingParser.addBlocking(response(from: fixtureJSON()), into: context) + private func parseTrip(fixture: String = Self.fixture) throws -> Trip { + let request = try TKRoutingParser.addBlocking(response(from: fixtureJSON(fixture)), into: context) return try #require(request.tripGroups.first?.visibleTrip) } From 592fe7391dd8cb8e8b1ce07fe15bc2e0cf75322d Mon Sep 17 00:00:00 2001 From: Adrian Schoenig Date: Fri, 4 Dec 2026 13:58:43 +1100 Subject: [PATCH 6/7] fix(results): keep a group's trips in departure order after real-time updates The results only rebuilt when their trip groups changed, or when something posted `.TKUIUpdatedRealTimeData`, which neither the results' own nor the trip overview's real-time updates do. These change trips in place, so rows showed the new times in the old order. The results now also rebuild when the request's trips change. Co-Authored-By: Claude Opus 5.5 --- .../TKUIRoutingResultsViewModel+Content.swift | 35 +++++++++++ .../TKUIRoutingResultsViewModel.swift | 15 +---- .../TKUIRoutingResultsRealTimeTest.swift | 61 +++++++++++++++++++ 3 files changed, 97 insertions(+), 14 deletions(-) create mode 100644 Tests/TripKitUITests/TKUIRoutingResultsRealTimeTest.swift diff --git a/Sources/TripKitUI/view model/TKUIRoutingResultsViewModel+Content.swift b/Sources/TripKitUI/view model/TKUIRoutingResultsViewModel+Content.swift index 1ccb918fc1a..c9ce75ebc30 100644 --- a/Sources/TripKitUI/view model/TKUIRoutingResultsViewModel+Content.swift +++ b/Sources/TripKitUI/view model/TKUIRoutingResultsViewModel+Content.swift @@ -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 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 diff --git a/Sources/TripKitUI/view model/TKUIRoutingResultsViewModel.swift b/Sources/TripKitUI/view model/TKUIRoutingResultsViewModel.swift index 6ed45bfe9dc..725af94d312 100644 --- a/Sources/TripKitUI/view model/TKUIRoutingResultsViewModel.swift +++ b/Sources/TripKitUI/view model/TKUIRoutingResultsViewModel.swift @@ -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) diff --git a/Tests/TripKitUITests/TKUIRoutingResultsRealTimeTest.swift b/Tests/TripKitUITests/TKUIRoutingResultsRealTimeTest.swift new file mode 100644 index 00000000000..1efbacafb52 --- /dev/null +++ b/Tests/TripKitUITests/TKUIRoutingResultsRealTimeTest.swift @@ -0,0 +1,61 @@ +// +// TKUIRoutingResultsRealTimeTest.swift +// TripKitUITests +// +// Real-time updates change a trip's times in place, which can change the +// order of a group's trips, so the results need to be rebuilt then. +// + +#if canImport(Testing) + +import CoreData +import Foundation +import Testing + +import RxSwift + +@testable import TripKit +@testable import TripKitUI + +@MainActor +struct TKUIRoutingResultsRealTimeTest { + + /// Kept here, as managed objects don't retain their context + private let context: NSManagedObjectContext + + init() throws { + let model = try #require(TKTestCase.model) + let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model) + try coordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil) + context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) + context.persistentStoreCoordinator = coordinator + } + + @Test func tripGroupsReEmitWhenATripsTimesChange() async throws { + let url = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() + .appendingPathComponent("Data/routing-cycle-train-cycle.json") + let response = try JSONDecoder().decode(TKAPI.RoutingResponse.self, from: Data(contentsOf: url)) + let request = try TKRoutingParser.addBlocking(response, into: context) + let trip = try #require(request.tripGroups.first?.trips.first) + + var emissions = 0 + let disposable = TKUIRoutingResultsViewModel + .observeTripGroups(.just((request, mutable: true))) + .subscribe(onNext: { _ in emissions += 1 }) + defer { disposable.dispose() } + try await Task.sleep(for: .seconds(1)) // past the throttling + let before = emissions + #expect(before > 0) + + // Like a real-time update, which changes the trip in place + trip.departureTime = trip.departureTime.addingTimeInterval(5 * 60) + context.processPendingChanges() + try await Task.sleep(for: .seconds(1)) + + #expect(emissions > before) + } + +} + +#endif From ce6c3889e11fcb3b757b54abbecee5cf3aead2da Mon Sep 17 00:00:00 2001 From: Adrian Schoenig Date: Fri, 4 Dec 2026 17:03:51 +1100 Subject: [PATCH 7/7] fix(trip-segments): give digits in routes and times the same width Otherwise a narrow "1" can be what lets one trip show its details while the next one in the list drops them. Co-Authored-By: Claude Opus 5.5 --- .../views/TKUITripSegmentsView.swift | 21 +++++++++++++++++-- .../TKUITripSegmentsViewSizingTest.swift | 19 +++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/Sources/TripKitUI/views/TKUITripSegmentsView.swift b/Sources/TripKitUI/views/TKUITripSegmentsView.swift index 9063b790b85..044ef34a06a 100644 --- a/Sources/TripKitUI/views/TKUITripSegmentsView.swift +++ b/Sources/TripKitUI/views/TKUITripSegmentsView.swift @@ -189,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 } @@ -293,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) { @@ -581,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() diff --git a/Tests/TripKitUITests/TKUITripSegmentsViewSizingTest.swift b/Tests/TripKitUITests/TKUITripSegmentsViewSizingTest.swift index e59d3d4d799..4f258f40f7f 100644 --- a/Tests/TripKitUITests/TKUITripSegmentsViewSizingTest.swift +++ b/Tests/TripKitUITests/TKUITripSegmentsViewSizingTest.swift @@ -33,6 +33,25 @@ struct TKUITripSegmentsViewSizingTest { #expect(view.texts == unconstrainedTexts(for: realTime)) } + @Test func departureTimesAndRoutesTakeTheSameWidth() throws { + let sydney = try #require(TimeZone(identifier: "Australia/Sydney")) + func width(route: String = "8", departingAt hour: Int = 14, _ minute: Int = 10) throws -> CGFloat { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = sydney + let departure = try #require(calendar.date(from: .init(year: 2026, month: 12, day: 4, hour: hour, minute: minute))) + var segments = segments(isRealTime: false) + segments[1] = Segment(tripSegmentModeColor: .systemBlue, tripSegmentModeImage: UIImage(systemName: "bus"), tripSegmentModeTitle: route, tripSegmentFixedDepartureTime: departure, tripSegmentTimeZone: sydney) + let view = TKUITripSegmentsView() + view.configure(segments) + return view.intrinsicContentSize.width + } + + // Otherwise a narrow "1" can be what makes one trip fit its details, + // but not the next one + #expect(try width(departingAt: 14, 10) == width(departingAt: 15, 00)) + #expect(try width(route: "11") == width(route: "88")) + } + } // MARK: - Helpers