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/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/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/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/Sources/TripKitUI/view model/TKUITripOverviewViewModel.swift b/Sources/TripKitUI/view model/TKUITripOverviewViewModel.swift index dabfc25f688..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) @@ -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 @@ -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 + let dataSources: Driver<[TKAPI.DataAttribution]> let notificationKinds: Driver> diff --git a/Sources/TripKitUI/views/TKUITripSegmentsView.swift b/Sources/TripKitUI/views/TKUITripSegmentsView.swift index ccf0288f0e5..044ef34a06a 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) @@ -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 } @@ -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) { @@ -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) } @@ -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 { @@ -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() 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 diff --git a/Tests/TripKitUITests/TKUITripRealTimeUpdateTest.swift b/Tests/TripKitUITests/TKUITripRealTimeUpdateTest.swift new file mode 100644 index 00000000000..f7c1a898f4b --- /dev/null +++ b/Tests/TripKitUITests/TKUITripRealTimeUpdateTest.swift @@ -0,0 +1,151 @@ +// +// 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 + +import RxSwift + +@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) + } + + @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 }) + } + + @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 + +extension TKUITripRealTimeUpdateTest { + + private static let fixture = "routing-pt-realtime" + + private func fixtureJSON(_ fixture: String = Self.fixture) throws -> [String: Any] { + let url = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() + .appendingPathComponent("Data", isDirectory: true) + .appendingPathComponent(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(fixture: String = Self.fixture) throws -> Trip { + let request = try TKRoutingParser.addBlocking(response(from: fixtureJSON(fixture)), 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) } + } + } + +} + +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 diff --git a/Tests/TripKitUITests/TKUITripSegmentsViewSizingTest.swift b/Tests/TripKitUITests/TKUITripSegmentsViewSizingTest.swift new file mode 100644 index 00000000000..4f258f40f7f --- /dev/null +++ b/Tests/TripKitUITests/TKUITripSegmentsViewSizingTest.swift @@ -0,0 +1,124 @@ +// +// 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)) + } + + @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 + +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