Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(native): watch complications stay current, times hold on clock changes, and a review's findings

Maurice02b0454b3d86
diff --git a/client/ios/App/TREKWatch/Pages.swift b/client/ios/App/TREKWatch/Pages.swift
index 3cd3f13de..ba5b0df27 100644
--- a/client/ios/App/TREKWatch/Pages.swift
+++ b/client/ios/App/TREKWatch/Pages.swift
@@ -25,7 +25,9 @@ struct TodayPage: View {
return start <= nowMinutes && nowMinutes < end
}
let nextIndex = stops.firstIndex { ($0.minutes ?? -1) >= nowMinutes }
- let focus = currentIndex ?? nextIndex
+ // A day planned without times still has its places: the first of them,
+ // and "day done" only once every stop has a time and it is behind.
+ let focus = currentIndex ?? nextIndex ?? stops.firstIndex { $0.minutes == nil }
ScrollView {
VStack(alignment: .leading, spacing: 8) {
header
@@ -395,12 +397,14 @@ struct BookingSummary: View {
if let moment {
// The day goes first when the line is too short for all three.
let label = running ? L("booking.checkOut") : dayLabel(moment)
+ // A booking with no time lasts the day: its day, but no countdown to midnight.
+ let counts = running ? clock != nil : !booking.isAllDay
ViewThatFits(in: .horizontal) {
- timeLine(clock: clock, label: label, moment: moment, pill: true)
- timeLine(clock: clock, label: nil, moment: moment, pill: true)
+ timeLine(clock: clock, label: label, moment: moment, pill: counts)
+ timeLine(clock: clock, label: nil, moment: moment, pill: counts)
VStack(alignment: .leading, spacing: 4) {
timeLine(clock: clock, label: label, moment: moment, pill: false)
- countdownPill(moment)
+ if counts { countdownPill(moment) }
}
}
}
diff --git a/client/ios/App/TREKWatch/TREKWatchApp.swift b/client/ios/App/TREKWatch/TREKWatchApp.swift
index 21cde2f06..f48d33687 100644
--- a/client/ios/App/TREKWatch/TREKWatchApp.swift
+++ b/client/ios/App/TREKWatch/TREKWatchApp.swift
@@ -14,6 +14,11 @@ struct TREKWatchApp: App {
WindowGroup {
RootView()
}
+ // Woken in the background to take a snapshot or complication update from
+ // the phone: the task lasts until it is delivered, stored and drawn.
+ .backgroundTask(.watchConnectivity) {
+ await WatchLink.shared.finishPendingDeliveries()
+ }
}
}
diff --git a/client/ios/App/TREKWatch/WatchModel.swift b/client/ios/App/TREKWatch/WatchModel.swift
index 34c24de68..e48f976ee 100644
--- a/client/ios/App/TREKWatch/WatchModel.swift
+++ b/client/ios/App/TREKWatch/WatchModel.swift
@@ -58,6 +58,18 @@ final class WatchModel {
}
var isWaitingForPhone: Bool { !pending.isEmpty }
+
+ /// WatchConnectivity handed a tick to the phone: it is not sent again.
+ func markSent(_ id: String) {
+ guard let index = pending.firstIndex(where: { $0.id == id }) else { return }
+ pending[index].sent = true
+ WatchStore.savePending(pending)
+ }
+
+ /// Ticks that never reached the phone's queue: not yet handed over, or failed.
+ func unsent(excluding queued: Set<String>) -> [PendingAction] {
+ pending.filter { $0.sent != true && !queued.contains($0.id) }
+ }
}
/// The watch's end of WatchConnectivity: snapshots arrive as the application
@@ -69,8 +81,23 @@ final class WatchLink: NSObject, WCSessionDelegate {
func activate() {
guard WCSession.isSupported() else { return }
- WCSession.default.delegate = self
- WCSession.default.activate()
+ if WCSession.default.delegate == nil { WCSession.default.delegate = self }
+ if WCSession.default.activationState != .activated { WCSession.default.activate() }
+ }
+
+ /// For the system's WatchConnectivity background task: activates the session
+ /// and returns only once what the phone sent has been delivered (and the
+ /// snapshot stored and the complications told), or after twenty seconds.
+ func finishPendingDeliveries() async {
+ activate()
+ for _ in 0..<100 {
+ let session = WCSession.default
+ if session.activationState == .activated && !session.hasContentPending { break }
+ try? await Task.sleep(nanoseconds: 200_000_000)
+ }
+ // Let the deliveries already queued on the main actor run before the task ends.
+ await MainActor.run {}
+ try? await Task.sleep(nanoseconds: 300_000_000)
}
func send(_ action: PendingAction) {
@@ -91,17 +118,23 @@ final class WatchLink: NSObject, WCSessionDelegate {
if let data = session.receivedApplicationContext["snapshot"] as? Data {
Task { @MainActor in WatchModel.shared.receive(data) }
}
- // Ticks queued before an earlier launch ended are still in the system's queue;
- // anything only in our own store (sent while not activated) goes again.
+ // Only ticks that never reached the phone's queue go again: those still in the
+ // system's queue are on their way, and those handed over are the phone's now.
let queued = Set(session.outstandingUserInfoTransfers.compactMap { ($0.userInfo["action"] as? [String: Any])?["id"] as? String })
Task { @MainActor in
- for action in WatchModel.shared.pending where !queued.contains(action.id) {
+ for action in WatchModel.shared.unsent(excluding: queued) {
session.transferUserInfo(["action": action.message])
}
}
requestRefresh()
}
+ /// A tick reached the phone's queue (or failed, and is sent again on the next activation).
+ func session(_ session: WCSession, didFinish userInfoTransfer: WCSessionUserInfoTransfer, error: Error?) {
+ guard error == nil, let id = (userInfoTransfer.userInfo["action"] as? [String: Any])?["id"] as? String else { return }
+ Task { @MainActor in WatchModel.shared.markSent(id) }
+ }
+
func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String: Any]) {
guard let data = applicationContext["snapshot"] as? Data else { return }
Task { @MainActor in WatchModel.shared.receive(data) }
diff --git a/client/ios/App/TREKWatchKit/ComplicationViews.swift b/client/ios/App/TREKWatchKit/ComplicationViews.swift
index cc9a1f125..ca2dab87c 100644
--- a/client/ios/App/TREKWatchKit/ComplicationViews.swift
+++ b/client/ios/App/TREKWatchKit/ComplicationViews.swift
@@ -26,6 +26,9 @@ enum ComplicationFamily: String, CaseIterable {
}
}
+/// Which complication an idle face belongs to: each says something of its own.
+enum ComplicationKind { case nextStop, countdown, tripDay }
+
/// What the complications read from a snapshot at a moment.
struct ComplicationState {
struct NextStop {
@@ -56,11 +59,14 @@ struct ComplicationState {
if let day = snapshot?.today(at: now) {
let current = day.stops.first { ($0.minutes ?? .max) <= minutes && minutes < ($0.endMinutes ?? -1) }
let upcoming = day.stops.first { ($0.minutes ?? -1) >= minutes }
- if let stop = current ?? upcoming {
+ // A day planned without times still has its places: the first of them, not "day done".
+ let untimed = day.stops.first { $0.minutes == nil }
+ if let stop = current ?? upcoming ?? untimed {
next = NextStop(stop: stop, start: stop.minutes.map { TrekDate.at($0, on: now) }, isNow: current != nil)
}
}
- if let booking = snapshot?.bookings.first(where: { ($0.start ?? .distantPast) > now }), let start = booking.start {
+ // Only bookings with a time: one that lasts the whole day has no moment to count down to.
+ if let booking = snapshot?.bookings.first(where: { !$0.isAllDay && ($0.start ?? .distantPast) > now }), let start = booking.start {
let look = Trek.booking(booking.kind)
countdown = Countdown(title: booking.route ?? booking.title, detail: booking.route == nil ? nil : booking.carrier,
symbol: look.symbol, color: look.color, target: start)
@@ -69,19 +75,27 @@ struct ComplicationState {
}
}
- /// The moments a complication should redraw at: each stop's start and end today, each booking's departure.
- static func changes(_ snapshot: WatchSnapshot?, from now: Date) -> [Date] {
+ /// The moments within `window` a complication should redraw at: the start
+ /// and end of every stop on every day of the plan in it, every timed
+ /// booking, and each midnight.
+ static func changes(_ snapshot: WatchSnapshot?, from now: Date, window: TimeInterval = 86_400 * 2) -> [Date] {
guard let snapshot else { return [] }
+ let horizon = now.addingTimeInterval(window)
var dates: [Date] = []
- if let day = snapshot.today(at: now) {
+ for day in snapshot.days {
+ guard let date = day.dateValue, date <= horizon, date >= Calendar.current.startOfDay(for: now) else { continue }
for stop in day.stops {
- if let start = stop.minutes { dates.append(TrekDate.at(start, on: now)) }
- if let end = stop.endMinutes { dates.append(TrekDate.at(end, on: now)) }
+ if let start = stop.minutes { dates.append(TrekDate.at(start, on: date)) }
+ if let end = stop.endMinutes { dates.append(TrekDate.at(end, on: date)) }
}
}
- dates += snapshot.bookings.compactMap(\.start)
- dates.append(Calendar.current.startOfDay(for: now.addingTimeInterval(86_400)))
- return dates.filter { $0 > now && $0 < now.addingTimeInterval(86_400 * 2) }.sorted()
+ dates += snapshot.bookings.filter { !$0.isAllDay }.compactMap(\.start)
+ var midnight = Calendar.current.startOfDay(for: now)
+ while let next = Calendar.current.date(byAdding: .day, value: 1, to: midnight), next <= horizon {
+ dates.append(next)
+ midnight = next
+ }
+ return dates.filter { $0 > now && $0 <= horizon }.sorted()
}
}
@@ -104,7 +118,8 @@ struct NextStopComplication: View {
.fontWeight(.semibold)
.widgetAccentable()
if let start = next.start, !next.isNow, start > now {
- Text(WatchFormat.relative(start, now: now)).foregroundStyle(.secondary)
+ // Counts down by itself between timeline entries.
+ Text(start, style: .relative).foregroundStyle(.secondary).lineLimit(1)
}
}
.font(.system(.footnote, design: .rounded))
@@ -141,7 +156,7 @@ struct NextStopComplication: View {
Label([time, next.stop.name].compactMap { $0 }.joined(separator: " "), systemImage: WatchLook.stopSymbol(next.stop))
}
} else {
- ComplicationIdle(state: state, family: family)
+ ComplicationIdle(state: state, family: family, kind: .nextStop)
}
}
}
@@ -155,7 +170,6 @@ struct CountdownComplication: View {
var body: some View {
if let countdown = state.countdown {
- let left = WatchFormat.countdown(countdown.target, now: now)
switch family {
case .rectangular:
VStack(alignment: .leading, spacing: 1) {
@@ -164,9 +178,10 @@ struct CountdownComplication: View {
Text(countdown.title).fontWeight(.semibold).lineLimit(1)
}
.font(.system(.footnote, design: .rounded))
- Text(left)
+ Text(countdown.target, style: .relative)
.font(.system(.title3, design: .rounded).weight(.bold).monospacedDigit())
.widgetAccentable()
+ .lineLimit(1)
.minimumScaleFactor(0.7)
if let detail = countdown.detail {
Text(detail).font(.system(.caption2, design: .rounded)).foregroundStyle(.secondary).lineLimit(1)
@@ -188,12 +203,16 @@ struct CountdownComplication: View {
Image(systemName: countdown.symbol)
.font(.system(size: 20, weight: .semibold))
.widgetAccentable()
- .widgetLabel { Text(left) }
+ .widgetLabel { Text(countdown.target, style: .relative) }
case .inline:
- Label("\(countdown.title) · \(left)", systemImage: countdown.symbol)
+ Label {
+ Text("\(countdown.title) · ") + Text(countdown.target, style: .relative)
+ } icon: {
+ Image(systemName: countdown.symbol)
+ }
}
} else {
- ComplicationIdle(state: state, family: family)
+ ComplicationIdle(state: state, family: family, kind: .countdown)
}
}
@@ -221,7 +240,7 @@ struct TripDayComplication: View {
case .upcoming(let days):
upcoming(days)
default:
- ComplicationIdle(state: state, family: family)
+ ComplicationIdle(state: state, family: family, kind: .tripDay)
}
}
@@ -296,9 +315,23 @@ struct TripDayComplication: View {
struct ComplicationIdle: View {
let state: ComplicationState
let family: ComplicationFamily
+ let kind: ComplicationKind
+
+ /// What an idle face says: before the trip how far off it is, while it runs
+ /// "day done" for the next stop and the day of the trip for the rest, and
+ /// "no trip" outside of one.
+ private var text: String {
+ switch state.phase {
+ case .upcoming(let days):
+ return "\(state.tripTitle ?? "") · \(days) \(WatchFormat.daysUnit(days))"
+ case .running(let day, let total):
+ return kind == .nextStop ? L("today.done") : WatchFormat.dayOf(day, total)
+ case .past, .none:
+ return L("complication.noTrip")
+ }
+ }
var body: some View {
- let text = state.tripTitle == nil ? L("complication.noTrip") : L("today.done")
switch family {
case .circular:
ZStack {
diff --git a/client/ios/App/TREKWatchKit/WatchSample.swift b/client/ios/App/TREKWatchKit/WatchSample.swift
index 37984827f..10ee7f0e2 100644
--- a/client/ios/App/TREKWatchKit/WatchSample.swift
+++ b/client/ios/App/TREKWatchKit/WatchSample.swift
@@ -56,38 +56,38 @@ enum WatchSample {
let bookings: [WatchSnapshot.Booking] = [
WatchSnapshot.Booking(
id: 1, title: "LH 716", kind: "flight", confirmed: true, date: iso(0), time: "15:35", endDate: iso(1), endTime: "11:20",
- zone: nil, from: .init(name: "Frankfurt", code: "FRA", lat: 50.0379, lng: 8.5622),
+ zone: nil, endZone: nil, from: .init(name: "Frankfurt", code: "FRA", lat: 50.0379, lng: 8.5622),
to: .init(name: "Tokyo Haneda", code: "HND", lat: 35.5494, lng: 139.7798), code: "K7Q2XD",
carrier: "Lufthansa LH 716", seat: "42A", platform: nil, location: nil, lat: nil, lng: nil, checkIn: nil, checkOut: nil
),
WatchSnapshot.Booking(
id: 7, title: "Shinkansen Nozomi 21", kind: "train", confirmed: true, date: iso(1), time: "13:33", endDate: iso(1), endTime: "15:48",
- zone: nil, from: .init(name: "Tokyo", code: nil, lat: 35.6812, lng: 139.7671), to: .init(name: "Kyoto", code: nil, lat: 34.9858, lng: 135.7588),
+ zone: nil, endZone: nil, from: .init(name: "Tokyo", code: nil, lat: 35.6812, lng: 139.7671), to: .init(name: "Kyoto", code: nil, lat: 34.9858, lng: 135.7588),
code: "JR-5521", carrier: "JR Nozomi 21", seat: "7D", platform: "14", location: nil, lat: nil, lng: nil, checkIn: nil, checkOut: nil
),
WatchSnapshot.Booking(
id: 2, title: "Hotel Kanra Kyoto", kind: "hotel", confirmed: true, date: iso(1), time: "16:30", endDate: iso(7), endTime: "11:00",
- zone: nil, from: nil, to: nil, code: "HK-208431", carrier: nil, seat: nil, platform: nil,
+ zone: nil, endZone: nil, from: nil, to: nil, code: "HK-208431", carrier: nil, seat: nil, platform: nil,
location: "Hotel Kanra Kyoto", lat: 34.9922, lng: 135.7585, checkIn: "15:00", checkOut: "11:00"
),
WatchSnapshot.Booking(
id: 3, title: t("Kaiseki at Kikunoi"), kind: "restaurant", confirmed: false, date: iso(2), time: "19:00", endDate: nil, endTime: nil,
- zone: nil, from: nil, to: nil, code: "KK-77", carrier: nil, seat: nil, platform: nil,
+ zone: nil, endZone: nil, from: nil, to: nil, code: "KK-77", carrier: nil, seat: nil, platform: nil,
location: "459 Shimokawaracho, Higashiyama", lat: 34.9989, lng: 135.7812, checkIn: nil, checkOut: nil
),
WatchSnapshot.Booking(
id: 4, title: t("Tea ceremony"), kind: "event", confirmed: true, date: iso(5), time: "10:30", endDate: nil, endTime: nil,
- zone: nil, from: nil, to: nil, code: nil, carrier: nil, seat: nil, platform: nil,
+ zone: nil, endZone: nil, from: nil, to: nil, code: nil, carrier: nil, seat: nil, platform: nil,
location: "Camellia Flower", lat: 35.0036, lng: 135.7788, checkIn: nil, checkOut: nil
),
WatchSnapshot.Booking(
id: 5, title: "Shinkansen Hikari 503", kind: "train", confirmed: true, date: iso(8), time: "09:12", endDate: iso(8), endTime: "09:27",
- zone: nil, from: .init(name: "Kyoto", code: nil, lat: 34.9858, lng: 135.7588), to: .init(name: "Shin-Osaka", code: nil, lat: 34.7334, lng: 135.5001),
+ zone: nil, endZone: nil, from: .init(name: "Kyoto", code: nil, lat: 34.9858, lng: 135.7588), to: .init(name: "Shin-Osaka", code: nil, lat: 34.7334, lng: 135.5001),
code: "E4521", carrier: "JR Hikari 503", seat: "7D", platform: "12", location: nil, lat: nil, lng: nil, checkIn: nil, checkOut: nil
),
WatchSnapshot.Booking(
id: 6, title: "LH 741", kind: "flight", confirmed: true, date: iso(8), time: "13:25", endDate: iso(8), endTime: "19:05",
- zone: nil, from: .init(name: "Osaka Kansai", code: "KIX", lat: 34.4320, lng: 135.2304),
+ zone: nil, endZone: nil, from: .init(name: "Osaka Kansai", code: "KIX", lat: 34.4320, lng: 135.2304),
to: .init(name: "Frankfurt", code: "FRA", lat: 50.0379, lng: 8.5622), code: "K7Q2XD",
carrier: "Lufthansa LH 741", seat: "38C", platform: nil, location: nil, lat: nil, lng: nil, checkIn: nil, checkOut: nil
),
diff --git a/client/ios/App/TREKWatchKit/WatchSnapshot.swift b/client/ios/App/TREKWatchKit/WatchSnapshot.swift
index 858838813..cb3dd3f18 100644
--- a/client/ios/App/TREKWatchKit/WatchSnapshot.swift
+++ b/client/ios/App/TREKWatchKit/WatchSnapshot.swift
@@ -57,6 +57,8 @@ struct WatchSnapshot: Codable, Equatable {
var endDate: String?
var endTime: String?
var zone: String?
+ /// The zone the end time is local to (the arrival airport's), when the booking names one.
+ var endZone: String?
var from: Point?
var to: Point?
var code: String?
@@ -153,22 +155,22 @@ struct WatchSnapshot: Codable, Equatable {
// MARK: - Dates
+/// Days and times as the watch reads them: always in the time zone it is in
+/// now (it may have flown since the last launch), and times of day as wall-clock
+/// hours and minutes, never as minutes added to midnight, which are an hour off
+/// on the days the clocks change.
enum TrekDate {
- private static let isoFormatter: DateFormatter = {
- let formatter = DateFormatter()
- formatter.calendar = Calendar(identifier: .gregorian)
- formatter.locale = Locale(identifier: "en_US_POSIX")
- formatter.dateFormat = "yyyy-MM-dd"
- return formatter
- }()
-
+ /// The start of yyyy-MM-dd here.
static func day(_ iso: String?) -> Date? {
guard let iso, iso.count >= 10 else { return nil }
- return isoFormatter.date(from: String(iso.prefix(10)))
+ let ymd = iso.prefix(10).split(separator: "-").compactMap { Int($0) }
+ guard ymd.count == 3 else { return nil }
+ return Calendar.current.date(from: DateComponents(year: ymd[0], month: ymd[1], day: ymd[2]))
}
static func iso(_ date: Date) -> String {
- isoFormatter.string(from: date)
+ let parts = Calendar.current.dateComponents([.year, .month, .day], from: date)
+ return String(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0)
}
/// yyyy-MM-dd and HH:mm as a moment, in `zone` when given, else here; midnight without a time.
@@ -205,9 +207,10 @@ enum TrekDate {
return (parts.hour ?? 0) * 60 + (parts.minute ?? 0)
}
- /// A moment on `day` at `minutes`.
+ /// The moment the clock shows `minutes` after midnight on `day`.
static func at(_ minutes: Int, on day: Date) -> Date {
- Calendar.current.date(byAdding: .minute, value: minutes, to: Calendar.current.startOfDay(for: day)) ?? day
+ let m = min(max(minutes, 0), 24 * 60 - 1)
+ return Calendar.current.date(bySettingHour: m / 60, minute: m % 60, second: 0, of: day) ?? day
}
}
@@ -275,7 +278,11 @@ extension WatchSnapshot {
extension WatchSnapshot.Booking {
var start: Date? { TrekDate.moment(date, time, zone: zone) }
- var end: Date? { TrekDate.moment(endDate ?? date, endTime, zone: zone) }
+ /// The end in the arrival's zone; a ride without one ends in the zone the watch is in, never the departure's.
+ var end: Date? { TrekDate.moment(endDate ?? date, endTime, zone: endZone ?? (isTransport ? nil : zone)) }
+
+ /// A booking with a day but no time lasts the whole day: there is nothing to count down to.
+ var isAllDay: Bool { time == nil }
var isTransport: Bool { ["flight", "train", "bus", "car", "cruise"].contains(kind) }
diff --git a/client/ios/App/TREKWatchKit/WatchStore.swift b/client/ios/App/TREKWatchKit/WatchStore.swift
index ff2b5027b..4bdca36db 100644
--- a/client/ios/App/TREKWatchKit/WatchStore.swift
+++ b/client/ios/App/TREKWatchKit/WatchStore.swift
@@ -14,6 +14,9 @@ struct PendingAction: Codable, Equatable, Identifiable {
var itemId: Int
var done: Bool
var at: Date
+ /// Set once WatchConnectivity has handed the tick to the phone; such a tick
+ /// is never sent again, it only stays laid over the snapshot until confirmed.
+ var sent: Bool?
/// What the phone receives (parseWatchActions in client/src/native/watch.ts).
var message: [String: Any] {
@@ -23,23 +26,23 @@ struct PendingAction: Codable, Equatable, Identifiable {
/// Where the watch keeps the last snapshot and its pending ticks: the keychain
/// group the watch app shares with its complications (no App Group needed,
-/// the same way the phone shares the widget snapshot), with the app's own
-/// defaults as the fallback a build without the entitlement still works with.
+/// the same way the phone shares the widget snapshot). Nothing goes to
+/// UserDefaults, which the complications could not read anyway.
enum WatchStore {
private static let service = "com.liketrek.trek.watch"
private static let snapshotAccount = "watch.snapshot"
private static let pendingAccount = "watch.pending"
static func loadSnapshot() -> WatchSnapshot? {
- (read(snapshotAccount) ?? UserDefaults.standard.data(forKey: snapshotAccount)).flatMap(WatchSnapshot.decode)
+ read(snapshotAccount).flatMap(WatchSnapshot.decode)
}
static func saveSnapshot(_ data: Data) {
- if !write(snapshotAccount, data) { UserDefaults.standard.set(data, forKey: snapshotAccount) }
+ write(snapshotAccount, data)
}
static func loadPending() -> [PendingAction] {
- guard let data = read(pendingAccount) ?? UserDefaults.standard.data(forKey: pendingAccount) else { return [] }
+ guard let data = read(pendingAccount) else { return [] }
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
return (try? decoder.decode([PendingAction].self, from: data)) ?? []
@@ -49,7 +52,7 @@ enum WatchStore {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .secondsSince1970
guard let data = try? encoder.encode(actions) else { return }
- if !write(pendingAccount, data) { UserDefaults.standard.set(data, forKey: pendingAccount) }
+ write(pendingAccount, data)
}
private static func query(_ account: String) -> [String: Any] {
diff --git a/client/ios/App/TREKWatchKit/WatchStyle.swift b/client/ios/App/TREKWatchKit/WatchStyle.swift
index 2066420e4..60c14a9c0 100644
--- a/client/ios/App/TREKWatchKit/WatchStyle.swift
+++ b/client/ios/App/TREKWatchKit/WatchStyle.swift
@@ -9,12 +9,16 @@ func L(_ key: String) -> String {
/// days, ranges and countdowns in the watch's language.
enum WatchFormat {
private static var formatters: [String: DateFormatter] = [:]
+ private static let utc = TimeZone(identifier: "UTC") ?? .current
- private static func formatter(_ template: String) -> DateFormatter {
- let key = template + "|" + Locale.current.identifier
+ /// A formatter for the template in the watch's language, in `zone`
+ /// (the current one unless given), so a flight across zones is followed.
+ private static func formatter(_ template: String, zone: TimeZone = .current) -> DateFormatter {
+ let key = template + "|" + Locale.current.identifier + "|" + zone.identifier
if let cached = formatters[key] { return cached }
let formatter = DateFormatter()
formatter.locale = Locale.current
+ formatter.timeZone = zone
formatter.setLocalizedDateFormatFromTemplate(template)
formatters[key] = formatter
return formatter
@@ -24,8 +28,11 @@ enum WatchFormat {
formatter(hour12 ? "h:mm a" : "HH:mm").string(from: date)
}
- static func time(minutes: Int, hour12: Bool, on day: Date = Date()) -> String {
- time(TrekDate.at(minutes, on: day), hour12: hour12)
+ /// A time of day from its minutes, with no date involved, so no change of
+ /// the clocks can shift it: the minutes after the reference date, in UTC.
+ static func time(minutes: Int, hour12: Bool) -> String {
+ let m = min(max(minutes, 0), 24 * 60 - 1)
+ return formatter(hour12 ? "h:mm a" : "HH:mm", zone: utc).string(from: Date(timeIntervalSinceReferenceDate: TimeInterval(m * 60)))
}
/// "Tue 18 Nov"
diff --git a/client/ios/App/TREKWatchWidgets/TREKWatchWidgets.swift b/client/ios/App/TREKWatchWidgets/TREKWatchWidgets.swift
index 59adf9ed1..e38714436 100644
--- a/client/ios/App/TREKWatchWidgets/TREKWatchWidgets.swift
+++ b/client/ios/App/TREKWatchWidgets/TREKWatchWidgets.swift
@@ -38,20 +38,31 @@ struct WatchProvider: TimelineProvider {
completion(WatchEntry(date: Date(), snapshot: context.isPreview && stored == nil ? WatchSample.snapshot(.running) : stored, relevance: nil))
}
+ /// Entries at every change in the next two days, every quarter hour for two
+ /// hours and every hour after that (for the circular faces' counts; the
+ /// others count by themselves), rebuilt at midnight or after the last entry,
+ /// whichever comes first. Without a trip nothing changes until the app writes
+ /// a new snapshot, which reloads the timelines itself.
func getTimeline(in context: Context, completion: @escaping (Timeline<WatchEntry>) -> Void) {
let now = Date()
let snapshot = WatchStore.loadSnapshot()?.applying(WatchStore.loadPending())
- // Every quarter hour as well, so the counts in the text stay current.
+ guard snapshot?.trip != nil else {
+ completion(Timeline(entries: [WatchEntry(date: now, snapshot: snapshot, relevance: nil)], policy: .never))
+ return
+ }
var moments = ComplicationState.changes(snapshot, from: now)
for step in 1...8 { moments.append(now.addingTimeInterval(Double(step) * 15 * 60)) }
+ for hour in 3...24 { moments.append(now.addingTimeInterval(Double(hour) * 3_600)) }
let dates = ([now] + moments).sorted().reduce(into: [Date]()) { out, date in
if let last = out.last, date.timeIntervalSince(last) < 60 { return }
out.append(date)
}
- let entries = dates.prefix(40).map { date in
+ let entries = dates.prefix(80).map { date in
WatchEntry(date: date, snapshot: snapshot, relevance: relevance(snapshot, at: date))
}
- completion(Timeline(entries: entries, policy: .after(dates.last ?? now.addingTimeInterval(3_600))))
+ let midnight = Calendar.current.date(byAdding: .day, value: 1, to: Calendar.current.startOfDay(for: now)) ?? now.addingTimeInterval(86_400)
+ let reload = min(midnight, entries.last?.date ?? midnight)
+ completion(Timeline(entries: entries, policy: .after(reload > now ? reload : now.addingTimeInterval(3_600))))
}
private func relevance(_ snapshot: WatchSnapshot?, at date: Date) -> TimelineEntryRelevance? {
diff --git a/client/ios/scripts/add-extension.rb b/client/ios/scripts/add-extension.rb
index bc82654a6..3760a971b 100644
--- a/client/ios/scripts/add-extension.rb
+++ b/client/ios/scripts/add-extension.rb
@@ -7,7 +7,8 @@
# "watch" (the Apple Watch app, embedded in the phone app's Watch folder) or
# "watchwidget" (the watch's complications, embedded in the watch app). The
# target's sources live in ios/App/<name>/ with an Info.plist and
-# <name>.entitlements next to them; an asset catalog there is a resource. The
+# <name>.entitlements next to them; an asset catalog or a privacy manifest
+# there is a resource. The
# project file stays checked in, so the targets show in Xcode like any other;
# this script is how they got there, and running it again changes nothing.
#
@@ -63,7 +64,7 @@ lprojs, files = sources.partition { |file| file.end_with?('.lproj') }
files.each do |file|
ref = group.new_reference(file)
target.add_file_references([ref]) if file.end_with?('.swift')
- target.add_resources([ref]) if file.end_with?('.js', '.xcassets')
+ target.add_resources([ref]) if file.end_with?('.js', '.xcassets', '.xcprivacy')
end
unless lprojs.empty?
variant = group.new_variant_group('Localizable.strings')
diff --git a/client/src/native/watch.test.ts b/client/src/native/watch.test.ts
index 1bd6cf081..299dc5491 100644
--- a/client/src/native/watch.test.ts
+++ b/client/src/native/watch.test.ts
@@ -59,7 +59,7 @@ const flight = reservation({
code: 'HND',
lat: 35.5494,
lng: 139.7798,
- timezone: null,
+ timezone: 'Asia/Tokyo',
local_time: null,
local_date: null,
},
@@ -159,6 +159,7 @@ describe('watchBooking', () => {
endDate: '2026-11-18',
endTime: '08:50',
zone: 'Europe/Berlin',
+ endZone: 'Asia/Tokyo',
code: 'K7Q2XD',
carrier: 'Lufthansa LH 716',
seat: '42A',
@@ -198,6 +199,26 @@ describe('upcomingReservations', () => {
});
});
+describe('the arrival zone', () => {
+ it('falls back to the arrival timezone in the metadata and is left out without one', () => {
+ const noEndpoints = reservation({
+ id: 9,
+ title: 'LH 717',
+ type: 'flight',
+ reservation_time: '2026-11-25T10:00',
+ metadata: JSON.stringify({ departure_timezone: 'Asia/Tokyo', arrival_timezone: 'Europe/Berlin' }),
+ });
+ const b = watchBooking(
+ noEndpoints,
+ { day: '2026-11-25', time: '10:00' },
+ { dayDates: new Map(), places: new Map() }
+ );
+ expect(b).toMatchObject({ zone: 'Asia/Tokyo', endZone: 'Europe/Berlin' });
+ const plain = watchBooking(hotel, { day: '2026-11-18', time: null }, { dayDates: new Map(), places: new Map() });
+ expect(plain).not.toHaveProperty('endZone');
+ });
+});
+
describe('the lists', () => {
it('puts the packing still to do first and counts what is packed', () => {
const items = [
diff --git a/client/src/native/watch.ts b/client/src/native/watch.ts
index fc5d97dca..e2cad9768 100644
--- a/client/src/native/watch.ts
+++ b/client/src/native/watch.ts
@@ -66,8 +66,10 @@ interface WatchBooking {
time?: string;
endDate?: string;
endTime?: string;
- /** The IANA zone the times are local to, when the booking names one (a departure airport). */
+ /** The IANA zone the start is local to, when the booking names one (a departure airport). */
zone?: string;
+ /** The zone the end is local to (the arrival airport), so a long flight lands at the right hour. */
+ endZone?: string;
from?: WatchPoint;
to?: WatchPoint;
/** The booking reference. */
@@ -267,6 +269,7 @@ export function watchBooking(
confirmed: r.status === 'confirmed',
...timesOf(r, start, meta, dayDates),
zone: text(from?.timezone || metaText(meta, 'departure_timezone', 40), 40),
+ endZone: text(to?.timezone || metaText(meta, 'arrival_timezone', 40), 40),
from: point(from),
to: point(to),
code: text(r.confirmation_number, 40),