From 3e0a2ef8edfa4c46f61e7a279b4513624fbc166e Mon Sep 17 00:00:00 2001 From: Maurice Date: Wed, 18 Nov 2026 21:28:00 +0100 Subject: [PATCH] fix(native): widgets turn to the next trip day by themselves TestFlight feedback: during a trip the widgets stayed on day 1 until the app was opened again. The app wrote only today's day into the widget snapshot, and only while it ran, so every timeline entry after midnight still showed the day it last ran, with its stops all ahead again. The snapshot now also carries the trip's days from today on (a month at most, sixteen stops a day), each with its date. On iOS every timeline entry takes the day of its own date, so the quarter-hour entry at midnight turns the widget to the next day, and the bookings list drops the days behind; the Android widgets do the same on each update. A snapshot from an app without the days reads as it was written, and an older app binary ignores them. --- .../com/liketrek/trek/widget/TrekWidgets.kt | 4 +- .../liketrek/trek/widget/WidgetSnapshot.kt | 46 ++++++--- .../trek/widget/WidgetSnapshotTest.kt | 30 ++++++ .../ios/App/TREKWidgets/NextTripWidget.swift | 13 ++- client/ios/App/TREKWidgets/TripIntent.swift | 3 +- .../ios/App/TREKWidgets/WidgetSnapshot.swift | 25 +++++ .../Layout/NativeWidgetsSync.test.tsx | 87 +++++++++++++++++ .../components/Layout/NativeWidgetsSync.tsx | 17 ++-- client/src/native/widgets.test.ts | 90 ++++++++++++++++++ client/src/native/widgets.ts | 95 +++++++++++++++++-- 10 files changed, 377 insertions(+), 33 deletions(-) create mode 100644 client/src/components/Layout/NativeWidgetsSync.test.tsx diff --git a/client/android/app/src/main/java/com/liketrek/trek/widget/TrekWidgets.kt b/client/android/app/src/main/java/com/liketrek/trek/widget/TrekWidgets.kt index 1af7aa1e8..2ca548246 100644 --- a/client/android/app/src/main/java/com/liketrek/trek/widget/TrekWidgets.kt +++ b/client/android/app/src/main/java/com/liketrek/trek/widget/TrekWidgets.kt @@ -82,10 +82,12 @@ abstract class TrekWidget : GlanceAppWidget() { // Read inside the composition: a session outlives one update, and every // write (the dashboard's, then each trip's) must reach it. val version by WidgetStore.version.collectAsState() - val snapshot = remember(version) { + val stored = remember(version) { val tripId = if (perTrip && appWidgetId >= 0) WidgetStore.tripFor(context, appWidgetId) else WidgetStore.AUTO WidgetStore.load(context, tripId) } + // The day of the trip is today's on every update, not the one the app last wrote. + val snapshot = stored?.on(LocalDate.now()) TrekWidgetTheme.Themed { Content(snapshot) } } } diff --git a/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetSnapshot.kt b/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetSnapshot.kt index 3f23623a7..712ba3b22 100644 --- a/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetSnapshot.kt +++ b/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetSnapshot.kt @@ -27,7 +27,28 @@ data class WidgetSnapshot( val labels: Labels, /** The trip's next flight or the one in the air; last and defaulted, so older callers keep compiling. */ val flight: Flight? = null, + /** + * The trip's days from the day the app wrote this on, each with its date, so + * the widget turns to the next day itself (see [on]); empty from an app + * that predates them. + */ + val days: List = emptyList(), ) { + /** + * The snapshot as it reads on [date]: that date's trip day out of [days], + * none before or after the trip, and only the bookings from that date on. + * The app writes its snapshot only while it runs, so without this a widget + * showed the day it last ran. A snapshot without [days] reads as written. + */ + fun on(date: LocalDate): WidgetSnapshot { + if (days.isEmpty()) return this + val key = date.toString() + return copy( + today = days.firstOrNull { it.date == key }, + bookings = bookings.filter { (it.date ?: key) >= key }, + ) + } + data class Trip( val title: String, val start: String, @@ -52,7 +73,8 @@ data class WidgetSnapshot( val symbol: String?, ) - data class Today(val dayLabel: String, val stops: List, val index: Int?, val total: Int?) + /** A trip day; [date] (yyyy-MM-dd) is absent from an app that predates the days ahead. */ + data class Today(val dayLabel: String, val stops: List, val index: Int?, val total: Int?, val date: String? = null) data class Weather( val temp: Int, @@ -212,6 +234,16 @@ data class WidgetSnapshot( null } + private fun dayOf(t: JSONObject): Today = Today( + dayLabel = t.optString("dayLabel"), + stops = t.optJSONArray("stops").objects().map { + Stop(it.str("time"), it.optString("name"), it.int("minutes"), it.str("color"), it.str("symbol")) + }, + index = t.int("index"), + total = t.int("total"), + date = t.str("date"), + ) + fun fromJson(o: JSONObject): WidgetSnapshot = WidgetSnapshot( trip = o.optJSONObject("trip")?.let { Trip( @@ -226,16 +258,8 @@ data class WidgetSnapshot( memberCount = it.int("memberCount"), ) }, - today = o.optJSONObject("today")?.let { t -> - Today( - dayLabel = t.optString("dayLabel"), - stops = t.optJSONArray("stops").objects().map { - Stop(it.str("time"), it.optString("name"), it.int("minutes"), it.str("color"), it.str("symbol")) - }, - index = t.int("index"), - total = t.int("total"), - ) - }, + today = o.optJSONObject("today")?.let(::dayOf), + days = o.optJSONArray("days").objects().map(::dayOf), weather = o.optJSONObject("weather")?.let { Weather(it.optInt("temp"), it.int("high"), it.int("low"), it.optString("main"), it.optString("label"), it.str("place"), it.int("rain")) }, diff --git a/client/android/app/src/test/java/com/liketrek/trek/widget/WidgetSnapshotTest.kt b/client/android/app/src/test/java/com/liketrek/trek/widget/WidgetSnapshotTest.kt index 15e13e16f..e9b41e7df 100644 --- a/client/android/app/src/test/java/com/liketrek/trek/widget/WidgetSnapshotTest.kt +++ b/client/android/app/src/test/java/com/liketrek/trek/widget/WidgetSnapshotTest.kt @@ -99,4 +99,34 @@ class WidgetSnapshotTest { assertEquals("ferry.fill", TrekIcons.booking("cruise").first) assertEquals("bookmark.fill", TrekIcons.booking("something").first) } + + @Test + fun turnsToTheDayOfTheDateItIsReadOn() { + val json = """{"trip":{"title":"T","start":"2026-11-06","end":"2026-11-08","path":"/trips/1"}, + "today":{"date":"2026-11-06","dayLabel":"Day 1 of 3","stops":[{"time":"09:00","name":"Museum","minutes":540}]}, + "days":[ + {"date":"2026-11-06","dayLabel":"Day 1 of 3","stops":[{"time":"09:00","name":"Museum","minutes":540}]}, + {"date":"2026-11-07","dayLabel":"Day 2 of 3","stops":[{"time":"10:00","name":"Harbour","minutes":600}]} + ], + "bookings":[ + {"title":"Hotel","kind":"hotel","date":"2026-11-06","confirmed":true,"path":"/trips/1"}, + {"title":"Train","kind":"train","date":"2026-11-07","confirmed":true,"path":"/trips/1"} + ], + "labels":{}}""" + val snapshot = WidgetSnapshot.parse(json)!! + assertEquals("Day 1 of 3", snapshot.on(LocalDate.of(2026, 11, 6)).today!!.dayLabel) + val second = snapshot.on(LocalDate.of(2026, 11, 7)) + assertEquals("Day 2 of 3", second.today!!.dayLabel) + assertEquals("Harbour", second.today!!.stops.single().name) + assertEquals(listOf("Train"), second.bookings.map { it.title }) + // A day the app wrote nothing for (the trip is over) shows no day. + assertNull(snapshot.on(LocalDate.of(2026, 11, 9)).today) + } + + @Test + fun aSnapshotWithoutDaysReadsAsWritten() { + val snapshot = WidgetSnapshot.parse(WidgetSamples.json(running = true, now = today))!! + assertTrue(snapshot.days.isEmpty()) + assertEquals(snapshot, snapshot.on(today.plusDays(3))) + } } diff --git a/client/ios/App/TREKWidgets/NextTripWidget.swift b/client/ios/App/TREKWidgets/NextTripWidget.swift index f5f3ab38c..6512e7494 100644 --- a/client/ios/App/TREKWidgets/NextTripWidget.swift +++ b/client/ios/App/TREKWidgets/NextTripWidget.swift @@ -21,12 +21,14 @@ struct TrekProvider: TimelineProvider { func getSnapshot(in context: Context, completion: @escaping (TrekEntry) -> Void) { let stored = WidgetSnapshot.load() let snapshot: WidgetSnapshot? = (stored?.trip != nil || !context.isPreview) ? stored : WidgetSnapshot.sample(running: false) - completion(TrekEntry(date: Date(), snapshot: snapshot)) + let now = Date() + completion(TrekEntry(date: now, snapshot: snapshot?.on(now))) } /// An entry every quarter hour for the next six hours, so the now line and - /// the next stop move on without the app; the app reloads the timeline - /// whenever it writes a new snapshot. + /// the next stop move on without the app, each with the trip day of its own + /// date: the one at midnight turns to the next day. The app reloads the + /// timeline whenever it writes a new snapshot, WidgetKit when it runs out. func getTimeline(in context: Context, completion: @escaping (Timeline) -> Void) { completion(TrekProvider.timeline(WidgetSnapshot.load())) } @@ -36,10 +38,11 @@ struct TrekProvider: TimelineProvider { let calendar = Calendar.current let minute = calendar.component(.minute, from: now) let firstStep = calendar.date(byAdding: .minute, value: 15 - minute % 15, to: now) ?? now - var entries = [TrekEntry(date: now, snapshot: snapshot)] + var entries = [TrekEntry(date: now, snapshot: snapshot?.on(now))] for step in 0..<24 { if let date = calendar.date(byAdding: .minute, value: step * 15, to: firstStep) { - entries.append(TrekEntry(date: calendar.date(bySetting: .second, value: 0, of: date) ?? date, snapshot: snapshot)) + let at = calendar.date(bySetting: .second, value: 0, of: date) ?? date + entries.append(TrekEntry(date: at, snapshot: snapshot?.on(at))) } } return Timeline(entries: entries, policy: .atEnd) diff --git a/client/ios/App/TREKWidgets/TripIntent.swift b/client/ios/App/TREKWidgets/TripIntent.swift index 3a7ebe61b..a14064cf5 100644 --- a/client/ios/App/TREKWidgets/TripIntent.swift +++ b/client/ios/App/TREKWidgets/TripIntent.swift @@ -63,7 +63,8 @@ struct TrekTripProvider: AppIntentTimelineProvider { func snapshot(for configuration: SelectTripIntent, in context: Context) async -> TrekEntry { let stored = WidgetSnapshot.load(trip: configuration.trip?.id) let snapshot: WidgetSnapshot? = (stored?.trip != nil || !context.isPreview) ? stored : WidgetSnapshot.sample(running: false) - return TrekEntry(date: Date(), snapshot: snapshot) + let now = Date() + return TrekEntry(date: now, snapshot: snapshot?.on(now)) } func timeline(for configuration: SelectTripIntent, in context: Context) async -> Timeline { diff --git a/client/ios/App/TREKWidgets/WidgetSnapshot.swift b/client/ios/App/TREKWidgets/WidgetSnapshot.swift index e511425fc..59b285a6c 100644 --- a/client/ios/App/TREKWidgets/WidgetSnapshot.swift +++ b/client/ios/App/TREKWidgets/WidgetSnapshot.swift @@ -35,6 +35,8 @@ struct WidgetSnapshot: Codable { } struct Today: Codable { + /// The calendar day it is, yyyy-MM-dd (absent from an app that predates `days`). + var date: String? var dayLabel: String var stops: [Stop] /// 1-based position of today in the trip. @@ -245,6 +247,9 @@ struct WidgetSnapshot: Codable { var trip: Trip? var today: Today? + /// The trip's days from the day the app wrote this on, each with its date, + /// so the widget turns to the next day itself (see `on(_:)`). + var days: [Today]? var weather: Weather? var bookings: [Booking]? var todos: Todos? @@ -306,6 +311,26 @@ struct WidgetSnapshot: Codable { return days + 1 } + /// The snapshot as it reads on `date`: that date's trip day out of `days`, + /// none before or after the trip, and only the bookings from that date on. + /// The app writes its snapshot only while it runs, so without this a widget + /// showed the day it last ran (TestFlight feedback: "stuck on day 1"). A + /// snapshot from an app without `days` reads as it was written. + func on(_ date: Date) -> WidgetSnapshot { + guard let days, !days.isEmpty else { return self } + let key = WidgetSnapshot.key(date) + var snapshot = self + snapshot.today = days.first { $0.date == key } + snapshot.bookings = bookings?.filter { ($0.date ?? key) >= key } + return snapshot + } + + /// A date as the app writes one, yyyy-MM-dd in the device's calendar day. + static func key(_ date: Date) -> String { + 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) + } + static func daysBetween(_ from: Date, _ to: Date) -> Int? { let calendar = Calendar.current return calendar.dateComponents([.day], from: calendar.startOfDay(for: from), to: calendar.startOfDay(for: to)).day diff --git a/client/src/components/Layout/NativeWidgetsSync.test.tsx b/client/src/components/Layout/NativeWidgetsSync.test.tsx new file mode 100644 index 000000000..c876a334b --- /dev/null +++ b/client/src/components/Layout/NativeWidgetsSync.test.tsx @@ -0,0 +1,87 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { render, waitFor } from '../../../tests/helpers/render'; +import { offlineDb } from '../../db/offlineDb'; +import type { Day, Trip } from '../../types'; + +const published = vi.hoisted(() => ({ calls: [] as unknown[][] })); + +vi.mock('@capacitor/app', () => ({ App: { addListener: vi.fn(async () => ({ remove: vi.fn() })) } })); +vi.mock('../../native/capabilities', () => ({ useNativeCapabilities: () => ({ caps: {} }) })); +vi.mock('../../native/watch', () => ({ + applyWatchActions: vi.fn(async () => []), + buildWatchSnapshot: vi.fn(), + publishWatch: vi.fn(async () => {}), + takeWatchActions: vi.fn(async () => []), + watchActive: () => false, +})); +vi.mock('../../native/widgetMedia', () => ({ + widgetCover: vi.fn(async () => null), + widgetWeather: vi.fn(async () => null), +})); +vi.mock('../../native/widgetOnline', () => ({ + atlasSummary: vi.fn(async () => null), + collabSummary: vi.fn(async () => null), + packingDetail: vi.fn(async () => null), +})); +vi.mock('../../native/widgets', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + widgetsActive: () => true, + publishWidgets: vi.fn(async (...args: unknown[]) => { + published.calls.push(args); + }), + }; +}); + +import NativeWidgetsSync from './NativeWidgetsSync'; + +const trip = { + id: 7, + title: 'Lisbon', + start_date: '2026-11-06', + end_date: '2026-11-08', + is_archived: 0, +} as unknown as Trip; +const day = (id: number, n: number, date: string, name: string) => + ({ + id, + trip_id: 7, + day_number: n, + date, + assignments: [{ id: id * 10, order_index: 0, place: { name, place_time: '10:00' } }], + }) as unknown as Day; + +describe('NativeWidgetsSync', () => { + beforeEach(async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(new Date(2026, 10, 7, 9, 0)); + published.calls = []; + await offlineDb.trips.put(trip as never); + await offlineDb.days.bulkPut([ + day(1, 1, '2026-11-06', 'Castle'), + day(2, 2, '2026-11-07', 'Harbour'), + day(3, 3, '2026-11-08', 'Market'), + ] as never); + }); + + afterEach(async () => { + vi.useRealTimers(); + await offlineDb.trips.clear(); + await offlineDb.days.clear(); + }); + + it('FE-NATIVE-WSYNC-001: writes today and every day ahead, so the widgets turn the day without the app', async () => { + render(); + await waitFor(() => expect(published.calls.length).toBeGreaterThan(0)); + const snapshot = published.calls[0][0] as { + today: { date: string; stops: { name: string }[] } | null; + days: { date: string; stops: { name: string }[] }[]; + }; + expect(snapshot.today).toMatchObject({ date: '2026-11-07', stops: [{ name: 'Harbour' }] }); + expect(snapshot.days.map((d) => [d.date, d.stops[0]?.name])).toEqual([ + ['2026-11-07', 'Harbour'], + ['2026-11-08', 'Market'], + ]); + }); +}); diff --git a/client/src/components/Layout/NativeWidgetsSync.tsx b/client/src/components/Layout/NativeWidgetsSync.tsx index aa9c24ab2..0b741a2e8 100644 --- a/client/src/components/Layout/NativeWidgetsSync.tsx +++ b/client/src/components/Layout/NativeWidgetsSync.tsx @@ -25,11 +25,10 @@ import { liveFlightOf, pickTrip, publishWidgets, - todayOf, + snapshotDays, tripDayState, widgetTripChoices, widgetsActive, - withBookings, type TripWidgetSnapshot, type WidgetLabels, } from '../../native/widgets'; @@ -191,11 +190,15 @@ export default function NativeWidgetsSync(): null { const tripSnapshot = async (trip: Trip | null, context: SyncContext, atlas: WidgetAtlas | null) => { const days = trip ? await offlineDb.days.where('trip_id').equals(trip.id).toArray() : []; const extra = trip ? await tripExtras(trip, days, context) : null; - const plain = trip - ? todayOf(trip, days, context.today, (n, m) => t('native.widget.dayOf', { n, m }), context.time) - : null; - const day = plain ? withBookings(plain, extra?.reservations ?? [], context.today, context.time) : null; - return { day, days, extra, snapshot: buildSnapshot(trip, day, labels(t), { ...extra?.extras, atlas }) }; + // Today and the days after it: the widgets turn to the next day at midnight by themselves. + const { today: day, ahead } = snapshotDays(trip, days, { + reservations: extra?.reservations ?? [], + from: context.today, + dayLabel: (n, m) => t('native.widget.dayOf', { n, m }), + formatTime: context.time, + }); + const snapshot = buildSnapshot(trip, day, labels(t), { ...extra?.extras, atlas, days: ahead }); + return { day, days, extra, snapshot }; }; /** The hero trip in full for the watch, with the ticks from it applied so far. */ diff --git a/client/src/native/widgets.test.ts b/client/src/native/widgets.test.ts index f220ae68a..a6664ce3a 100644 --- a/client/src/native/widgets.test.ts +++ b/client/src/native/widgets.test.ts @@ -18,8 +18,11 @@ import { liveDayDue, pickTrip, publishWidgets, + snapshotDays, todayOf, + tripDaysFrom, tripDayState, + WIDGET_DAYS_AHEAD, widgetTripChoices, withBookings, } from './widgets'; @@ -405,3 +408,90 @@ describe('widgets set to a trip', () => { expect(JSON.parse(calls[2].json)).toEqual([{ id: 2, title: 'Trip 2', start: '2026-12-01', end: '2026-12-05' }]); }); }); + +describe('the days ahead, for a widget that turns the day itself', () => { + const tripDays = [ + day(1, 1, '2026-11-06', [{ name: 'Museum', time: '09:00' }]), + day(2, 2, '2026-11-07', [{ name: 'Harbour', time: '10:00' }, { name: 'Market' }]), + day(3, 3, '2026-11-08', []), + ]; + const label = (n: number, m: number) => `${n}/${m}`; + + it('FE-NATIVE-WDAYS-001: carries every day from today on with its date, label and stops', () => { + const ahead = tripDaysFrom(trip(1, '2026-11-06', '2026-11-08'), tripDays, { + reservations: [], + from: '2026-11-07', + dayLabel: label, + formatTime: (t) => t, + }); + expect(ahead.map((d) => [d.date, d.dayLabel, d.stops.map((s) => s.name)])).toEqual([ + ['2026-11-07', '2/3', ['Harbour', 'Market']], + ['2026-11-08', '3/3', []], + ]); + }); + + it('FE-NATIVE-WDAYS-002: joins each day to the bookings of its own date', () => { + const reservations = [ + { id: 1, type: 'restaurant', title: 'Dinner', status: 'confirmed', reservation_time: '2026-11-08T19:30' }, + ] as never; + const ahead = tripDaysFrom(trip(1, '2026-11-06', '2026-11-08'), tripDays, { + reservations, + from: '2026-11-06', + dayLabel: label, + formatTime: (t) => t, + }); + expect(ahead.find((d) => d.date === '2026-11-08')?.stops.map((s) => s.name)).toEqual(['Dinner']); + expect(ahead.find((d) => d.date === '2026-11-06')?.stops.map((s) => s.name)).toEqual(['Museum']); + }); + + it('FE-NATIVE-WDAYS-003: holds a month at most and nothing of a trip that is over', () => { + const long = Array.from({ length: 40 }, (_, i) => + day(i + 1, i + 1, `2026-12-${String(i + 1).padStart(2, '0')}`, []) + ).map((d, i) => (i >= 31 ? { ...d, date: `2027-01-${String(i - 30).padStart(2, '0')}` } : d)) as Day[]; + const t = trip(1, '2026-12-01', '2027-01-09'); + expect( + tripDaysFrom(t, long, { reservations: [], from: '2026-12-01', dayLabel: label, formatTime: (x) => x }) + ).toHaveLength(WIDGET_DAYS_AHEAD); + expect( + tripDaysFrom(t, long, { reservations: [], from: '2027-02-01', dayLabel: label, formatTime: (x) => x }) + ).toEqual([]); + }); + + it('FE-NATIVE-WDAYS-004: the snapshot has today with its date and the days ahead, each held to 16 stops', () => { + const busy = day( + 4, + 1, + '2026-11-06', + Array.from({ length: 20 }, (_, i) => ({ name: `Stop ${i}` })) + ); + const t = trip(1, '2026-11-06', '2026-11-06'); + const ahead = tripDaysFrom(t, [busy], { + reservations: [], + from: '2026-11-06', + dayLabel: label, + formatTime: (x) => x, + }); + const snapshot = buildSnapshot(t, ahead[0] ?? null, labels, { days: ahead }); + expect(snapshot.today?.date).toBe('2026-11-06'); + // Today stays whole, as the app has always written it; the days ahead keep their first 16. + expect(snapshot.today?.stops).toHaveLength(20); + expect(snapshot.days?.[0]).toMatchObject({ date: '2026-11-06', dayLabel: '1/1' }); + expect(snapshot.days?.[0]?.stops).toHaveLength(16); + }); + + it('FE-NATIVE-WDAYS-005: a snapshot without days ahead leaves the field out', () => { + expect(buildSnapshot(trip(1, '2026-11-06', '2026-11-08'), null, labels, { days: [] })).not.toHaveProperty('days'); + }); + + it('FE-NATIVE-WDAYS-006: today is the first day ahead while the trip runs today, none before it starts or without a trip', () => { + const options = { reservations: [], dayLabel: label, formatTime: (x: string) => x }; + const t = trip(1, '2026-11-06', '2026-11-08'); + const running = snapshotDays(t, tripDays, { ...options, from: '2026-11-07' }); + expect(running.today?.date).toBe('2026-11-07'); + expect(running.ahead).toHaveLength(2); + const before = snapshotDays(t, tripDays, { ...options, from: '2026-11-01' }); + expect(before.today).toBeNull(); + expect(before.ahead.map((d) => d.date)).toEqual(['2026-11-06', '2026-11-07', '2026-11-08']); + expect(snapshotDays(null, tripDays, { ...options, from: '2026-11-07' })).toEqual({ today: null, ahead: [] }); + }); +}); diff --git a/client/src/native/widgets.ts b/client/src/native/widgets.ts index 62adf997e..864d3fae3 100644 --- a/client/src/native/widgets.ts +++ b/client/src/native/widgets.ts @@ -104,7 +104,14 @@ export interface WidgetSnapshot { placeCount?: number; memberCount?: number; } | null; - today: { dayLabel: string; stops: SnapshotStop[]; index?: number; total?: number } | null; + today: SnapshotDay | null; + /** + * Every day of the trip from the day it was written on, each with its date, + * so a widget turns to the next day by itself at midnight instead of showing + * the day the app last ran until it is opened again. A binary without it + * reads `today` as before. + */ + days?: SnapshotDay[]; weather?: WidgetWeather; bookings?: WidgetBooking[]; todos?: WidgetTodos; @@ -128,7 +135,18 @@ export interface WidgetWeather { } /** What goes along with the trip beyond its day; each part optional. */ +/** A trip day as the widgets read it; `date` (yyyy-MM-dd) says which day of the calendar it is. */ +interface SnapshotDay { + date?: string; + dayLabel: string; + stops: SnapshotStop[]; + index?: number; + total?: number; +} + interface SnapshotExtras { + /** The trip's days from today on (tripDaysFrom), for the widgets to turn the day themselves. */ + days?: TripDay[]; place?: string | null; cover?: string | null; placeCount?: number; @@ -152,8 +170,15 @@ export interface TripDay { /** 1-based position of the day in the trip, and the trip's day count. */ index?: number; total?: number; + /** The calendar day it is, yyyy-MM-dd. */ + date?: string; } +/** How many days ahead a snapshot carries: a month of a trip without the app being opened. */ +export const WIDGET_DAYS_AHEAD = 31; +/** The stops a day carries at most, which is more than the largest widget shows. */ +const WIDGET_DAY_STOPS = 16; + /** iOS (WidgetKit) and Android (Glance) read the same snapshot. */ export function widgetsActive(): boolean { return isNativeApp() && hasNativeFeature('widgets'); @@ -243,9 +268,45 @@ export function todayOf( dayId: day.id, index: index + 1, total: ordered.length, + date: today, }; } +/** + * The trip's days from `from` on, each with its stops and its timed bookings, at + * most WIDGET_DAYS_AHEAD of them: what a widget needs to show the right day on + * the days the app is not opened. + */ +/** What tripDaysFrom reads besides the trip and its days. */ +interface DaysFromOptions { + reservations: Reservation[]; + /** The first date, yyyy-MM-dd: today. */ + from: string; + dayLabel: (index: number, total: number) => string; + formatTime: (time: string) => string; +} + +export function tripDaysFrom( + trip: Trip, + days: Day[], + { reservations, from, dayLabel, formatTime }: DaysFromOptions +): TripDay[] { + const dates = [ + ...new Set( + days + .filter((d) => d.trip_id === trip.id) + .map((d) => (d.date ?? '').slice(0, 10)) + .filter((date) => date >= from) + ), + ] + .sort((a, b) => a.localeCompare(b)) + .slice(0, WIDGET_DAYS_AHEAD); + return dates.flatMap((date) => { + const day = todayOf(trip, days, date, dayLabel, formatTime); + return day ? [withBookings(day, reservations, date, formatTime)] : []; + }); +} + /** The day with its timed bookings (a flight, the table tonight) joined to the stops in time order. */ export function withBookings( day: TripDay, @@ -303,6 +364,29 @@ function snapshotStop({ time, name, minutes, color, symbol }: WidgetStop): Snaps }; } +/** + * The days a trip's snapshot carries: `today` while the trip runs today, and + * every day from today on for the widgets to turn to by themselves. + */ +export function snapshotDays( + trip: Trip | null, + days: Day[], + options: DaysFromOptions +): { today: TripDay | null; ahead: TripDay[] } { + const ahead = trip ? tripDaysFrom(trip, days, options) : []; + return { today: ahead[0]?.date === options.from ? ahead[0] : null, ahead }; +} + +/** A day for the snapshot; the days ahead keep their first `limit` stops, so a month of them stays small. */ +function snapshotDay(day: TripDay, limit = day.stops.length): SnapshotDay { + return { + ...(day.date ? { date: day.date } : {}), + dayLabel: day.dayLabel, + stops: day.stops.slice(0, limit).map(snapshotStop), + ...(day.index ? { index: day.index, total: day.total } : {}), + }; +} + export function buildSnapshot( trip: Trip | null, day: TripDay | null, @@ -323,15 +407,10 @@ export function buildSnapshot( ...(extras.memberCount ? { memberCount: extras.memberCount } : {}), } : null, - today: day - ? { - dayLabel: day.dayLabel, - stops: day.stops.map(snapshotStop), - ...(day.index ? { index: day.index, total: day.total } : {}), - } - : null, + today: day ? snapshotDay(day) : null, labels, }; + if (extras.days?.length) snapshot.days = extras.days.map((d) => snapshotDay(d, WIDGET_DAY_STOPS)); if (extras.weather) snapshot.weather = extras.weather; if (extras.bookings) snapshot.bookings = extras.bookings; if (extras.todos) snapshot.todos = extras.todos;