feat(native): pick the trip a widget shows in Edit Widget

Widgets followed the dashboard's trip only, which is the one under way, so a
packing list or to-dos for a trip still being planned could not sit on the
home screen. The trip, today, bookings, to-dos, packing and group widgets now
take a trip in Edit Widget (an AppIntent with the trips running or ahead,
Automatic by default, which keeps following the dashboard); the world map
needs none.

- The app writes a snapshot per trip running or ahead (at most six, the
  dashboard's order) and the list to pick from, under their own keys
  (feature widgetTrips, so an older binary never mistakes one for the
  dashboard's); bags, chat and polls are kept ten minutes, covers per trip
- The widget extension targets iOS 17, which configurable widgets need; the
  apps are not released, so no installed widget goes away
- The choices and their texts in the 28 languages of the gallery
This commit is contained in:
Maurice
2026-11-06 21:41:21 +01:00
parent 77b9252577
commit 20298cfe5a
39 changed files with 403 additions and 42 deletions
+6 -2
View File
@@ -26,6 +26,7 @@
7A1E00052C0000000000A005 /* TrekBridgeViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A1E00042C0000000000A004 /* TrekBridgeViewController.swift */; };
7A1E00072C0000000000A007 /* TrekShellPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A1E00062C0000000000A006 /* TrekShellPlugin.swift */; };
7FB730DC35C234816EAE65AF /* WidgetSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = DBF6D74B7888714BF264E0E6 /* WidgetSnapshot.swift */; };
D3C699E2258FBA6A11C1DDE4 /* TripIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8442B4B8988AF5D1BFA3ADE3 /* TripIntent.swift */; };
157A7B737E3FFB610A218D47 /* AtlasContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4D004544572B0E85DE29A7B8 /* AtlasContent.swift */; };
FEB91385917AC44D5CDAA59C /* PackingContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 04C0771C8582246A26E0C98E /* PackingContent.swift */; };
EA5EDDD4E5F9BC9BC46C563F /* CollabContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D5041DDDAFF5B491B053999 /* CollabContent.swift */; };
@@ -108,6 +109,7 @@
BE41D7212DCB0C78E00A8462 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
C7064A9DA92FCC8ACAA4F22A /* NextTripWidget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = NextTripWidget.swift; sourceTree = "<group>"; };
DBF6D74B7888714BF264E0E6 /* WidgetSnapshot.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = WidgetSnapshot.swift; sourceTree = "<group>"; };
8442B4B8988AF5D1BFA3ADE3 /* TripIntent.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = TripIntent.swift; sourceTree = "<group>"; };
4D004544572B0E85DE29A7B8 /* AtlasContent.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AtlasContent.swift; sourceTree = "<group>"; };
04C0771C8582246A26E0C98E /* PackingContent.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PackingContent.swift; sourceTree = "<group>"; };
7D5041DDDAFF5B491B053999 /* CollabContent.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CollabContent.swift; sourceTree = "<group>"; };
@@ -262,6 +264,7 @@
337775CD9091673D0ADDF325 /* TripDayAttributes.swift */,
3259F6C40216CECEBAC6F307 /* TripDayLiveActivity.swift */,
DBF6D74B7888714BF264E0E6 /* WidgetSnapshot.swift */,
8442B4B8988AF5D1BFA3ADE3 /* TripIntent.swift */,
4D004544572B0E85DE29A7B8 /* AtlasContent.swift */,
04C0771C8582246A26E0C98E /* PackingContent.swift */,
7D5041DDDAFF5B491B053999 /* CollabContent.swift */,
@@ -470,6 +473,7 @@
492FA24FBB57059B0B5007CE /* TripDayAttributes.swift in Sources */,
DF633789F2F667C4CF264C9E /* TripDayLiveActivity.swift in Sources */,
7FB730DC35C234816EAE65AF /* WidgetSnapshot.swift in Sources */,
D3C699E2258FBA6A11C1DDE4 /* TripIntent.swift in Sources */,
157A7B737E3FFB610A218D47 /* AtlasContent.swift in Sources */,
FEB91385917AC44D5CDAA59C /* PackingContent.swift in Sources */,
EA5EDDD4E5F9BC9BC46C563F /* CollabContent.swift in Sources */,
@@ -564,7 +568,7 @@
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = TREKWidgets/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 16.2;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -795,7 +799,7 @@
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = TREKWidgets/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 16.2;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
+9 -2
View File
@@ -46,7 +46,7 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
/// and a server can require a minimum (minNativeShellApi in /api/health/features).
static let shellApi = 2
/// The native features by name, so the UI can turn each on by itself.
static let features: [String] = ["capabilities", "edgeBack", "tileCache", "biometricLock", "geolocation", "sharedFiles", "nativePush", "widgets", "liveActivity"]
static let features: [String] = ["capabilities", "edgeBack", "tileCache", "biometricLock", "geolocation", "sharedFiles", "nativePush", "widgets", "liveActivity", "widgetTrips"]
// MARK: - Shared booking documents
@@ -63,12 +63,19 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
/// Stores what the home-screen widget shows (native/widgets.ts builds it, texts
/// already translated) where the widget extension reads it, and redraws it.
/// `key` (feature widgetTrips) stores one trip's snapshot ("trip.<id>") or the
/// list of trips a widget can be set to ("trips"); without it, the dashboard's.
@objc func setWidgetSnapshot(_ call: CAPPluginCall) {
guard let json = call.getString("json"), let data = json.data(using: .utf8) else {
call.reject("json is required")
return
}
TrekSharedKeychain.write("widget.snapshot", data)
let key = call.getString("key") ?? "snapshot"
guard key == "snapshot" || key == "trips" || key.range(of: "^trip\\.[0-9]{1,12}$", options: .regularExpression) != nil else {
call.reject("key must be snapshot, trips or trip.<id>")
return
}
TrekSharedKeychain.write("widget.\(key)", data)
WidgetCenter.shared.reloadAllTimelines()
call.resolve()
}
@@ -1,7 +1,8 @@
import SwiftUI
import WidgetKit
/// The home-screen and lock-screen widgets; their gallery names and
/// The home-screen and lock-screen widgets; all but the Atlas show one trip,
/// the dashboard's or the one picked in Edit Widget (TripIntent.swift). Their gallery names and
/// descriptions are in <language>.lproj/Localizable.strings. Each reads the snapshot the app
/// last wrote (WidgetSnapshot) and draws it with the views in *Content.swift,
/// which know nothing of WidgetKit so the preview renderer can draw them too.
@@ -27,7 +28,10 @@ struct TrekProvider: TimelineProvider {
/// the next stop move on without the app; the app reloads the timeline
/// whenever it writes a new snapshot.
func getTimeline(in context: Context, completion: @escaping (Timeline<TrekEntry>) -> Void) {
let snapshot = WidgetSnapshot.load()
completion(TrekProvider.timeline(WidgetSnapshot.load()))
}
static func timeline(_ snapshot: WidgetSnapshot?) -> Timeline<TrekEntry> {
let now = Date()
let calendar = Calendar.current
let minute = calendar.component(.minute, from: now)
@@ -38,7 +42,7 @@ struct TrekProvider: TimelineProvider {
entries.append(TrekEntry(date: calendar.date(bySetting: .second, value: 0, of: date) ?? date, snapshot: snapshot))
}
}
completion(Timeline(entries: entries, policy: .atEnd))
return Timeline(entries: entries, policy: .atEnd)
}
}
@@ -83,7 +87,7 @@ struct TrekContainer<Content: View, Background: View>: View {
struct NextTripWidget: Widget {
var body: some WidgetConfiguration {
// The kind stays "NextTrip" so widgets placed before the redesign keep working.
StaticConfiguration(kind: "NextTrip", provider: TrekProvider()) { entry in
AppIntentConfiguration(kind: "NextTrip", intent: SelectTripIntent.self, provider: TrekTripProvider()) { entry in
TripWidgetView(entry: entry)
}
.configurationDisplayName("widget.trip.name")
@@ -110,7 +114,7 @@ struct TripWidgetView: View {
struct TodayWidget: Widget {
var body: some WidgetConfiguration {
StaticConfiguration(kind: "TripToday", provider: TrekProvider()) { entry in
AppIntentConfiguration(kind: "TripToday", intent: SelectTripIntent.self, provider: TrekTripProvider()) { entry in
TrekContainer(link: entry.snapshot?.trip.flatMap { WidgetSnapshot.link($0.path) }) {
TodayFamilyView(entry: entry)
} background: {
@@ -133,7 +137,7 @@ private struct TodayFamilyView: View {
struct BookingsWidget: Widget {
var body: some WidgetConfiguration {
StaticConfiguration(kind: "TripBookings", provider: TrekProvider()) { entry in
AppIntentConfiguration(kind: "TripBookings", intent: SelectTripIntent.self, provider: TrekTripProvider()) { entry in
TrekContainer(link: entry.snapshot?.bookings?.first.flatMap { WidgetSnapshot.link($0.path) }) {
BookingsFamilyView(entry: entry)
} background: {
@@ -156,7 +160,7 @@ private struct BookingsFamilyView: View {
struct TodosWidget: Widget {
var body: some WidgetConfiguration {
StaticConfiguration(kind: "TripTodos", provider: TrekProvider()) { entry in
AppIntentConfiguration(kind: "TripTodos", intent: SelectTripIntent.self, provider: TrekTripProvider()) { entry in
TrekContainer(link: entry.snapshot?.todos.flatMap { WidgetSnapshot.link($0.path) }) {
TodosFamilyView(entry: entry)
} background: {
@@ -179,7 +183,7 @@ private struct TodosFamilyView: View {
struct PackingWidget: Widget {
var body: some WidgetConfiguration {
StaticConfiguration(kind: "TripPacking", provider: TrekProvider()) { entry in
AppIntentConfiguration(kind: "TripPacking", intent: SelectTripIntent.self, provider: TrekTripProvider()) { entry in
TrekContainer(link: entry.snapshot?.packing.flatMap { WidgetSnapshot.link($0.path) }) {
PackingFamilyView(entry: entry)
} background: {
@@ -225,7 +229,7 @@ private struct AtlasFamilyView: View {
struct CollabWidget: Widget {
var body: some WidgetConfiguration {
StaticConfiguration(kind: "TripCollab", provider: TrekProvider()) { entry in
AppIntentConfiguration(kind: "TripCollab", intent: SelectTripIntent.self, provider: TrekTripProvider()) { entry in
TrekContainer(link: entry.snapshot?.collab.flatMap { WidgetSnapshot.link($0.path) }) {
CollabFamilyView(entry: entry)
} background: {
@@ -0,0 +1,72 @@
import AppIntents
import WidgetKit
/// The trip a widget shows, picked in "Edit Widget": the dashboard's trip by
/// default ("Automatic"), or any trip the app listed in widget.trips.
struct TripChoice: AppEntity {
static var typeDisplayRepresentation: TypeDisplayRepresentation = "widget.intent.trip"
static var defaultQuery = TripChoiceQuery()
/// The id of the automatic choice, which follows the dashboard's trip.
static let automaticID = "auto"
var id: String
var title: String
var dates: String?
var displayRepresentation: DisplayRepresentation {
if id == TripChoice.automaticID {
return DisplayRepresentation(title: "widget.intent.auto", subtitle: "widget.intent.autoHint")
}
return DisplayRepresentation(title: "\(title)", subtitle: dates.map { "\($0)" })
}
static var automatic: TripChoice { TripChoice(id: automaticID, title: "", dates: nil) }
}
struct TripChoiceQuery: EntityQuery {
func entities(for identifiers: [TripChoice.ID]) async throws -> [TripChoice] {
all().filter { identifiers.contains($0.id) }
}
func suggestedEntities() async throws -> [TripChoice] {
all()
}
func defaultResult() async -> TripChoice? {
.automatic
}
/// Automatic first, then the trips the app sent, soonest first.
private func all() -> [TripChoice] {
[.automatic] + WidgetSnapshot.tripIndex().map {
TripChoice(id: String($0.id), title: $0.title, dates: RelativeDay.range($0.start, $0.end))
}
}
}
struct SelectTripIntent: WidgetConfigurationIntent {
static var title: LocalizedStringResource = "widget.intent.title"
static var description = IntentDescription("widget.intent.description")
@Parameter(title: "widget.intent.trip")
var trip: TripChoice?
}
/// Like TrekProvider, for the widgets that show one trip: the snapshot of the
/// trip picked for the widget, or the dashboard's.
struct TrekTripProvider: AppIntentTimelineProvider {
func placeholder(in context: Context) -> TrekEntry {
TrekEntry(date: Date(), snapshot: .sample(running: false))
}
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)
}
func timeline(for configuration: SelectTripIntent, in context: Context) async -> Timeline<TrekEntry> {
TrekProvider.timeline(WidgetSnapshot.load(trip: configuration.trip?.id))
}
}
@@ -205,16 +205,42 @@ struct WidgetSnapshot: Codable {
var collab: Collab?
var labels: Labels
/// The dashboard's snapshot.
static func load() -> WidgetSnapshot? {
read("widget.snapshot").flatMap { try? JSONDecoder().decode(WidgetSnapshot.self, from: $0) }
}
/// The snapshot of the trip a widget is set to, the dashboard's for none or
/// "auto", and the dashboard's too while the app has not written that trip yet.
static func load(trip id: String?) -> WidgetSnapshot? {
guard let id, id != "auto", let data = read("widget.trip.\(id)"),
var snapshot = try? JSONDecoder().decode(WidgetSnapshot.self, from: data) else { return load() }
if snapshot.atlas == nil { snapshot.atlas = load()?.atlas }
return snapshot
}
/// A trip a widget can be set to, as the app lists them.
struct TripRef: Codable {
var id: Int
var title: String
var start: String
var end: String
}
static func tripIndex() -> [TripRef] {
read("widget.trips").flatMap { try? JSONDecoder().decode([TripRef].self, from: $0) } ?? []
}
private static func read(_ account: String) -> Data? {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: "com.liketrek.trek.push",
kSecAttrAccount as String: "widget.snapshot",
kSecAttrAccount as String: account,
kSecReturnData as String: true,
]
var result: CFTypeRef?
guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
return try? JSONDecoder().decode(WidgetSnapshot.self, from: data)
guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess else { return nil }
return result as? Data
}
/// Whole days from today to the trip's start, in the device's calendar.
@@ -13,3 +13,8 @@
"widget.atlas.description" = "الدول التي زرتها مضيئة على الخريطة.";
"widget.collab.name" = "مجموعة السفر";
"widget.collab.description" = "من يرافقك وأحدث الرسائل والتصويت المفتوح.";
"widget.intent.title" = "اختر الرحلة";
"widget.intent.description" = "الرحلة التي تعرضها هذه الأداة.";
"widget.intent.trip" = "الرحلة";
"widget.intent.auto" = "تلقائي";
"widget.intent.autoHint" = "نفس رحلة لوحة التحكم";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "Olduğun ölkələr xəritədə parlayır.";
"widget.collab.name" = "Səyahət qrupu";
"widget.collab.description" = "Kim gəlir, son mesajlar və açıq səsvermə.";
"widget.intent.title" = "Səyahəti seç";
"widget.intent.description" = "Bu vidcetin göstərdiyi səyahət.";
"widget.intent.trip" = "Səyahət";
"widget.intent.auto" = "Avtomatik";
"widget.intent.autoHint" = "İdarə panelindəki səyahət";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "Els països on has estat, brillant al mapa.";
"widget.collab.name" = "Grup de viatge";
"widget.collab.description" = "Qui ve, els darrers missatges i la votació oberta.";
"widget.intent.title" = "Tria el viatge";
"widget.intent.description" = "El viatge que mostra aquest giny.";
"widget.intent.trip" = "Viatge";
"widget.intent.auto" = "Automàtic";
"widget.intent.autoHint" = "El mateix viatge que el tauler";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "Země, kde jsi byl, zářící na mapě.";
"widget.collab.name" = "Cestovní skupina";
"widget.collab.description" = "Kdo jede s tebou, nejnovější zprávy a otevřené hlasování.";
"widget.intent.title" = "Vybrat cestu";
"widget.intent.description" = "Cesta, kterou tento widget zobrazuje.";
"widget.intent.trip" = "Cesta";
"widget.intent.auto" = "Automaticky";
"widget.intent.autoHint" = "Stejná cesta jako na nástěnce";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "Die Länder, in denen du warst, leuchtend auf der Karte.";
"widget.collab.name" = "Reisegruppe";
"widget.collab.description" = "Wer mitreist, die neuesten Nachrichten und die offene Abstimmung.";
"widget.intent.title" = "Reise wählen";
"widget.intent.description" = "Die Reise, die dieses Widget zeigt.";
"widget.intent.trip" = "Reise";
"widget.intent.auto" = "Automatisch";
"widget.intent.autoHint" = "Dieselbe Reise wie im Dashboard";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "Οι χώρες που έχεις επισκεφθεί, φωτεινές στον χάρτη.";
"widget.collab.name" = "Ομάδα ταξιδιού";
"widget.collab.description" = "Ποιος έρχεται, τα τελευταία μηνύματα και η ανοιχτή ψηφοφορία.";
"widget.intent.title" = "Επιλογή ταξιδιού";
"widget.intent.description" = "Το ταξίδι που δείχνει αυτό το widget.";
"widget.intent.trip" = "Ταξίδι";
"widget.intent.auto" = "Αυτόματα";
"widget.intent.autoHint" = "Το ίδιο ταξίδι με τον πίνακα";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "The countries you have been to, glowing on the map.";
"widget.collab.name" = "Travel group";
"widget.collab.description" = "Who comes along, the latest messages and the open poll.";
"widget.intent.title" = "Choose trip";
"widget.intent.description" = "The trip this widget shows.";
"widget.intent.trip" = "Trip";
"widget.intent.auto" = "Automatic";
"widget.intent.autoHint" = "Same trip as the dashboard";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "Los países donde has estado, brillando en el mapa.";
"widget.collab.name" = "Grupo de viaje";
"widget.collab.description" = "Quién viene, los últimos mensajes y la votación abierta.";
"widget.intent.title" = "Elegir viaje";
"widget.intent.description" = "El viaje que muestra este widget.";
"widget.intent.trip" = "Viaje";
"widget.intent.auto" = "Automático";
"widget.intent.autoHint" = "El mismo viaje que el panel";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "Riigid, kus oled käinud, kaardil helendamas.";
"widget.collab.name" = "Reisiseltskond";
"widget.collab.description" = "Kes tuleb kaasa, viimased sõnumid ja avatud hääletus.";
"widget.intent.title" = "Vali reis";
"widget.intent.description" = "Reis, mida see vidin näitab.";
"widget.intent.trip" = "Reis";
"widget.intent.auto" = "Automaatne";
"widget.intent.autoHint" = "Sama reis mis töölaual";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "Les pays où vous êtes allé, illuminés sur la carte.";
"widget.collab.name" = "Groupe de voyage";
"widget.collab.description" = "Qui vient, les derniers messages et le sondage ouvert.";
"widget.intent.title" = "Choisir le voyage";
"widget.intent.description" = "Le voyage affiché par ce widget.";
"widget.intent.trip" = "Voyage";
"widget.intent.auto" = "Automatique";
"widget.intent.autoHint" = "Le même voyage que le tableau de bord";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "המדינות שביקרת בהן, זוהרות על המפה.";
"widget.collab.name" = "קבוצת הטיול";
"widget.collab.description" = "מי מצטרף, ההודעות האחרונות והסקר הפתוח.";
"widget.intent.title" = "בחירת טיול";
"widget.intent.description" = "הטיול שהווידג׳ט הזה מציג.";
"widget.intent.trip" = "טיול";
"widget.intent.auto" = "אוטומטי";
"widget.intent.autoHint" = "אותו טיול כמו בלוח הבקרה";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "Az országok, ahol jártál, világítva a térképen.";
"widget.collab.name" = "Útitársak";
"widget.collab.description" = "Ki jön veled, a legújabb üzenetek és a nyitott szavazás.";
"widget.intent.title" = "Utazás választása";
"widget.intent.description" = "Az utazás, amelyet ez a widget mutat.";
"widget.intent.trip" = "Utazás";
"widget.intent.auto" = "Automatikus";
"widget.intent.autoHint" = "Ugyanaz az utazás, mint az irányítópulton";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "Negara yang pernah kamu kunjungi, bersinar di peta.";
"widget.collab.name" = "Rombongan";
"widget.collab.description" = "Siapa yang ikut, pesan terbaru, dan polling yang terbuka.";
"widget.intent.title" = "Pilih perjalanan";
"widget.intent.description" = "Perjalanan yang ditampilkan widget ini.";
"widget.intent.trip" = "Perjalanan";
"widget.intent.auto" = "Otomatis";
"widget.intent.autoHint" = "Perjalanan yang sama dengan dasbor";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "I paesi in cui sei stato, illuminati sulla mappa.";
"widget.collab.name" = "Gruppo di viaggio";
"widget.collab.description" = "Chi viene, gli ultimi messaggi e il sondaggio aperto.";
"widget.intent.title" = "Scegli viaggio";
"widget.intent.description" = "Il viaggio mostrato da questo widget.";
"widget.intent.trip" = "Viaggio";
"widget.intent.auto" = "Automatico";
"widget.intent.autoHint" = "Lo stesso viaggio della dashboard";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "訪れた国が地図上で光ります。";
"widget.collab.name" = "旅行グループ";
"widget.collab.description" = "一緒に行くメンバー、最新のメッセージ、受付中の投票。";
"widget.intent.title" = "旅行を選択";
"widget.intent.description" = "このウィジェットに表示する旅行。";
"widget.intent.trip" = "旅行";
"widget.intent.auto" = "自動";
"widget.intent.autoHint" = "ダッシュボードと同じ旅行";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "다녀온 나라가 지도 위에서 빛납니다.";
"widget.collab.name" = "여행 그룹";
"widget.collab.description" = "함께 가는 사람, 최근 메시지, 진행 중인 투표.";
"widget.intent.title" = "여행 선택";
"widget.intent.description" = "이 위젯에 표시할 여행.";
"widget.intent.trip" = "여행";
"widget.intent.auto" = "자동";
"widget.intent.autoHint" = "대시보드와 같은 여행";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "De landen waar je bent geweest, oplichtend op de kaart.";
"widget.collab.name" = "Reisgezelschap";
"widget.collab.description" = "Wie er meegaat, de nieuwste berichten en de open peiling.";
"widget.intent.title" = "Reis kiezen";
"widget.intent.description" = "De reis die deze widget toont.";
"widget.intent.trip" = "Reis";
"widget.intent.auto" = "Automatisch";
"widget.intent.autoHint" = "Dezelfde reis als het dashboard";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "Kraje, w których byłeś, świecące na mapie.";
"widget.collab.name" = "Grupa podróży";
"widget.collab.description" = "Kto jedzie, najnowsze wiadomości i otwarta ankieta.";
"widget.intent.title" = "Wybierz podróż";
"widget.intent.description" = "Podróż, którą pokazuje ten widżet.";
"widget.intent.trip" = "Podróż";
"widget.intent.auto" = "Automatycznie";
"widget.intent.autoHint" = "Ta sama podróż co na pulpicie";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "Os países em que você esteve, brilhando no mapa.";
"widget.collab.name" = "Grupo de viagem";
"widget.collab.description" = "Quem vai junto, as mensagens recentes e a votação aberta.";
"widget.intent.title" = "Escolher viagem";
"widget.intent.description" = "A viagem que este widget mostra.";
"widget.intent.trip" = "Viagem";
"widget.intent.auto" = "Automático";
"widget.intent.autoHint" = "A mesma viagem do painel";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "Страны, где вы были, светятся на карте.";
"widget.collab.name" = "Группа поездки";
"widget.collab.description" = "Кто едет, последние сообщения и открытый опрос.";
"widget.intent.title" = "Выбрать поездку";
"widget.intent.description" = "Поездка, которую показывает этот виджет.";
"widget.intent.trip" = "Поездка";
"widget.intent.auto" = "Автоматически";
"widget.intent.autoHint" = "Та же поездка, что и на главной";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "Krajiny, kde si bol, žiariace na mape.";
"widget.collab.name" = "Cestovná skupina";
"widget.collab.description" = "Kto ide s tebou, najnovšie správy a otvorené hlasovanie.";
"widget.intent.title" = "Vybrať cestu";
"widget.intent.description" = "Cesta, ktorú zobrazuje tento widget.";
"widget.intent.trip" = "Cesta";
"widget.intent.auto" = "Automaticky";
"widget.intent.autoHint" = "Rovnaká cesta ako na nástenke";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "Länderna du har besökt, lysande på kartan.";
"widget.collab.name" = "Resesällskap";
"widget.collab.description" = "Vem som följer med, de senaste meddelandena och den öppna omröstningen.";
"widget.intent.title" = "Välj resa";
"widget.intent.description" = "Resan som den här widgeten visar.";
"widget.intent.trip" = "Resa";
"widget.intent.auto" = "Automatiskt";
"widget.intent.autoHint" = "Samma resa som på startsidan";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "ประเทศที่คุณเคยไป ส่องแสงบนแผนที่";
"widget.collab.name" = "กลุ่มเดินทาง";
"widget.collab.description" = "ใครไปด้วย ข้อความล่าสุด และโหวตที่เปิดอยู่";
"widget.intent.title" = "เลือกทริป";
"widget.intent.description" = "ทริปที่วิดเจ็ตนี้แสดง";
"widget.intent.trip" = "ทริป";
"widget.intent.auto" = "อัตโนมัติ";
"widget.intent.autoHint" = "ทริปเดียวกับแดชบอร์ด";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "Bulunduğun ülkeler haritada parlıyor.";
"widget.collab.name" = "Seyahat grubu";
"widget.collab.description" = "Kimler geliyor, son mesajlar ve açık anket.";
"widget.intent.title" = "Seyahat seç";
"widget.intent.description" = "Bu widget'ın gösterdiği seyahat.";
"widget.intent.trip" = "Seyahat";
"widget.intent.auto" = "Otomatik";
"widget.intent.autoHint" = "Paneldeki seyahatin aynısı";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "Країни, де ви були, світяться на мапі.";
"widget.collab.name" = "Група подорожі";
"widget.collab.description" = "Хто їде, останні повідомлення і відкрите опитування.";
"widget.intent.title" = "Вибрати подорож";
"widget.intent.description" = "Подорож, яку показує цей віджет.";
"widget.intent.trip" = "Подорож";
"widget.intent.auto" = "Автоматично";
"widget.intent.autoHint" = "Та сама подорож, що й на панелі";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "Những quốc gia bạn đã đến, sáng lên trên bản đồ.";
"widget.collab.name" = "Nhóm du lịch";
"widget.collab.description" = "Ai đi cùng, tin nhắn mới nhất và cuộc bình chọn đang mở.";
"widget.intent.title" = "Chọn chuyến đi";
"widget.intent.description" = "Chuyến đi mà tiện ích này hiển thị.";
"widget.intent.trip" = "Chuyến đi";
"widget.intent.auto" = "Tự động";
"widget.intent.autoHint" = "Cùng chuyến đi với bảng điều khiển";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "你去过的国家在地图上亮起。";
"widget.collab.name" = "旅行小组";
"widget.collab.description" = "谁一起去、最新消息和进行中的投票。";
"widget.intent.title" = "选择旅行";
"widget.intent.description" = "此小组件显示的旅行。";
"widget.intent.trip" = "旅行";
"widget.intent.auto" = "自动";
"widget.intent.autoHint" = "与仪表板相同的旅行";
@@ -13,3 +13,8 @@
"widget.atlas.description" = "你去過的國家在地圖上亮起。";
"widget.collab.name" = "旅行小組";
"widget.collab.description" = "誰一起去、最新訊息與進行中的投票。";
"widget.intent.title" = "選擇旅行";
"widget.intent.description" = "此小工具顯示的旅行。";
"widget.intent.trip" = "旅行";
"widget.intent.auto" = "自動";
"widget.intent.autoHint" = "與儀表板相同的旅行";
@@ -12,15 +12,17 @@ import { useTranslation } from '../../i18n';
import { useNativeCapabilities } from '../../native/capabilities';
import { bookingsAhead, packingSummary, todosSummary, tripPlace } from '../../native/widgetExtras';
import { widgetCover, widgetWeather } from '../../native/widgetMedia';
import { atlasSummary, collabSummary, packingDetail } from '../../native/widgetOnline';
import { atlasSummary, collabSummary, packingDetail, type WidgetAtlas } from '../../native/widgetOnline';
import {
buildSnapshot,
pickTrip,
publishWidgets,
todayOf,
tripDayState,
widgetTripChoices,
widgetsActive,
withBookings,
type TripWidgetSnapshot,
type WidgetLabels,
} from '../../native/widgets';
import { useAuthStore } from '../../store/authStore';
@@ -141,24 +143,43 @@ export default function NativeWidgetsSync(): null {
if (!widgetsActive()) return;
let cancelled = false;
/** One trip's snapshot with its day, as the widgets set to that trip show it. */
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, snapshot: buildSnapshot(trip, day, labels(t), { ...extra?.extras, atlas }) };
};
const sync = async () => {
const now = new Date();
const today = localDateStr(now.getFullYear(), now.getMonth(), now.getDate());
const time = (value: string) => formatTime(value, language, timeFormat);
const context: SyncContext = { today, language, unit, time: (value) => formatTime(value, language, timeFormat) };
const trips = await offlineDb.trips.toArray();
const trip = pickTrip(trips, today);
const days = trip ? await offlineDb.days.where('trip_id').equals(trip.id).toArray() : [];
const [extra, atlas] = await Promise.all([
trip ? tripExtras(trip, days, { today, language, unit, time }) : Promise.resolve(null),
// The countries do not depend on a trip: the atlas widget fills without one.
atlasSummary(language),
]);
const plain = trip ? todayOf(trip, days, today, (n, m) => t('native.widget.dayOf', { n, m }), time) : null;
const day = plain ? withBookings(plain, extra?.reservations ?? [], today, time) : null;
const hero = pickTrip(trips, today);
// The countries do not depend on a trip: the atlas widget fills without one.
const atlas = await atlasSummary(language);
const main = await tripSnapshot(hero, context, atlas);
// Every trip running or ahead also gets its own, for widgets set to it in Edit Widget.
const choices: TripWidgetSnapshot[] = [];
for (const trip of widgetTripChoices(trips, today)) {
const own = trip.id === hero?.id ? main : await tripSnapshot(trip, context, null);
choices.push({
id: trip.id,
title: trip.title,
start: trip.start_date ?? '',
end: trip.end_date ?? '',
snapshot: own.snapshot,
});
}
if (cancelled) return;
const snapshot = buildSnapshot(trip, day, labels(t), { ...extra?.extras, atlas });
const live = day ? tripDayState(day, now.getHours() * 60 + now.getMinutes(), t('native.widget.dayDone')) : null;
await publishWidgets(snapshot, live);
const live = main.day
? tripDayState(main.day, now.getHours() * 60 + now.getMinutes(), t('native.widget.dayDone'))
: null;
await publishWidgets(main.snapshot, live, choices);
};
void sync();
+2 -1
View File
@@ -60,7 +60,8 @@ export interface TrekShellPlugin {
/** Feature nativePush: the notification the app was opened from, before the UI ran. */
takeOpenedPush(): Promise<{ url: string | null }>;
/** Feature widgets: what the home-screen widget shows (native/widgets.ts), as JSON. */
setWidgetSnapshot(options: { json: string }): Promise<void>;
/** Feature widgetTrips adds `key`: "trip.<id>" for one trip's snapshot, "trips" for the list a widget picks from. */
setWidgetSnapshot(options: { json: string; key?: string }): Promise<void>;
/** Feature liveActivity: starts the travel day's Live Activity, or updates the running one. */
syncTripDay(options: {
tripTitle: string;
+14 -6
View File
@@ -42,25 +42,33 @@ export async function widgetWeather(
return value;
}
const COVER_KEY = 'trek.widgetCover';
const COVER_KEY = 'trek.widgetCovers';
/** Covers kept, one per trip a widget can show (widgetTripChoices). */
const COVER_KEEP = 6;
const COVER_MAX_PX = 720;
const COVER_MAX_BYTES = 15 * 1024 * 1024;
/** Kept under this so the keychain item the widget reads stays small. */
const COVER_MAX_BASE64 = 160_000;
function storedCover(url: string): string | null {
function storedCovers(): { url: string; data: string }[] {
try {
const raw = localStorage.getItem(COVER_KEY);
const parsed = raw ? (JSON.parse(raw) as { url?: string; data?: string }) : null;
return parsed?.url === url && parsed.data ? parsed.data : null;
const parsed: unknown = raw ? JSON.parse(raw) : [];
return Array.isArray(parsed) ? (parsed as { url: string; data: string }[]) : [];
} catch {
return null;
return [];
}
}
function storedCover(url: string): string | null {
return storedCovers().find((c) => c.url === url)?.data ?? null;
}
/** Newest first, the oldest dropped past COVER_KEEP. */
function storeCover(url: string, data: string): void {
try {
localStorage.setItem(COVER_KEY, JSON.stringify({ url, data }));
const rest = storedCovers().filter((c) => c.url !== url);
localStorage.setItem(COVER_KEY, JSON.stringify([{ url, data }, ...rest].slice(0, COVER_KEEP)));
} catch {
// Storage full: the cover is fetched again next time, nothing else depends on it.
}
+18 -3
View File
@@ -42,6 +42,21 @@ export interface WidgetCollab {
const HEX = /^#[0-9a-f]{6}$/i;
/**
* Server answers kept for a while: the widgets sync every quarter hour for up
* to six trips, and bags, chat and polls do not change that fast.
*/
const NETWORK_TTL_MS = 10 * 60 * 1000;
const networkCache = new Map<string, { at: number; value: unknown }>();
async function cached<T>(key: string, read: () => Promise<T>): Promise<T> {
const hit = networkCache.get(key);
if (hit && Date.now() - hit.at < NETWORK_TTL_MS) return hit.value as T;
const value = await read();
networkCache.set(key, { at: Date.now(), value });
return value;
}
function initials(name: string): string {
const parts = name
.trim()
@@ -66,7 +81,7 @@ export async function packingDetail(
total_weight_grams?: number;
}[] = [];
try {
const res = (await packingApi.listBags(tripId)) as { bags?: typeof bags };
const res = await cached(`bags:${tripId}`, () => packingApi.listBags(tripId) as Promise<{ bags?: typeof bags }>);
bags = res.bags ?? [];
} catch {
// Offline or no bags: the widget shows the items without them.
@@ -173,8 +188,8 @@ export async function collabSummary(
let polls: Poll[] = [];
try {
const [m, p] = await Promise.all([
collabApi.getMessages(tripId) as Promise<{ messages?: Message[] }>,
collabApi.getPolls(tripId) as Promise<{ polls?: Poll[] }>,
cached(`messages:${tripId}`, () => collabApi.getMessages(tripId) as Promise<{ messages?: Message[] }>),
cached(`polls:${tripId}`, () => collabApi.getPolls(tripId) as Promise<{ polls?: Poll[] }>),
]);
messages = m.messages ?? [];
polls = p.polls ?? [];
+34 -1
View File
@@ -13,7 +13,15 @@ vi.mock('./trekShell', () => ({
}));
import { TrekShell } from './trekShell';
import { buildSnapshot, pickTrip, publishWidgets, todayOf, tripDayState, withBookings } from './widgets';
import {
buildSnapshot,
pickTrip,
publishWidgets,
todayOf,
tripDayState,
widgetTripChoices,
withBookings,
} from './widgets';
const trip = (id: number, start: string | null, end: string | null, archived = 0) =>
({ id, title: `Trip ${id}`, start_date: start, end_date: end, is_archived: archived }) as unknown as Trip;
@@ -220,3 +228,28 @@ describe('the richer snapshot', () => {
expect(snapshot).not.toHaveProperty('packing');
});
});
describe('widgets set to a trip', () => {
it('offers the trips running or ahead, in the dashboard order, at most six', () => {
const trips = [
trip(1, '2026-01-01', '2026-01-05'),
trip(2, '2026-12-01', '2026-12-05'),
trip(3, '2026-11-04', '2026-11-12'),
trip(4, '2026-11-20', '2026-11-22', 1),
trip(5, null, null),
...[6, 7, 8, 9, 10, 11].map((id) => trip(id, `2027-0${id - 5}-01`, `2027-0${id - 5}-03`)),
];
expect(widgetTripChoices(trips, '2026-11-06').map((t) => t.id)).toEqual([3, 2, 6, 7, 8, 9]);
});
it('writes each trip under its own key and the list to pick from', async () => {
vi.mocked(TrekShell.setWidgetSnapshot).mockClear();
const snapshot = buildSnapshot(trip(2, '2026-12-01', '2026-12-05'), null, labels);
await publishWidgets(snapshot, null, [
{ id: 2, title: 'Trip 2', start: '2026-12-01', end: '2026-12-05', snapshot },
]);
const calls = vi.mocked(TrekShell.setWidgetSnapshot).mock.calls.map(([options]) => options);
expect(calls.map((c) => c.key)).toEqual([undefined, 'trip.2', 'trips']);
expect(JSON.parse(calls[2].json)).toEqual([{ id: 2, title: 'Trip 2', start: '2026-12-01', end: '2026-12-05' }]);
});
});
+31 -1
View File
@@ -144,6 +144,16 @@ export function pickTrip(trips: Trip[], today: string): Trip | null {
return heroTrip(sortTripsByRelevance(active, today), today);
}
/**
* The trips a widget can be set to in Edit Widget: the ones running or coming
* up, in the dashboard's order (so the hero's trip comes first), at most `limit`,
* each of which gets a snapshot of its own.
*/
export function widgetTripChoices(trips: Trip[], today: string, limit = 6): Trip[] {
const ahead = trips.filter((t) => !t.is_archived && t.start_date && (t.end_date ?? t.start_date) >= today);
return sortTripsByRelevance(ahead, today).slice(0, limit);
}
/** The symbols of the booking kinds a day's timeline shows next to its stops. */
const RESERVATION_SYMBOLS: Record<string, string> = {
flight: 'airplane',
@@ -294,12 +304,32 @@ export function tripDayState(day: TripDay, nowMinutes: number, allDone: string)
};
}
/** A trip a widget can be set to in Edit Widget, and its snapshot. */
export interface TripWidgetSnapshot {
id: number;
title: string;
start: string;
end: string;
snapshot: WidgetSnapshot;
}
export async function publishWidgets(
snapshot: WidgetSnapshot,
liveDay: ReturnType<typeof tripDayState> | null
liveDay: ReturnType<typeof tripDayState> | null,
trips: TripWidgetSnapshot[] = []
): Promise<void> {
if (!widgetsActive()) return;
await TrekShell.setWidgetSnapshot({ json: JSON.stringify(snapshot) }).catch(reportNativeFailure);
// An app binary without widgetTrips would take every one of these for the dashboard's snapshot.
if (hasNativeFeature('widgetTrips')) {
for (const trip of trips) {
await TrekShell.setWidgetSnapshot({ json: JSON.stringify(trip.snapshot), key: `trip.${trip.id}` }).catch(
reportNativeFailure
);
}
const index = trips.map(({ id, title, start, end }) => ({ id, title, start, end }));
await TrekShell.setWidgetSnapshot({ json: JSON.stringify(index), key: 'trips' }).catch(reportNativeFailure);
}
if (!hasNativeFeature('liveActivity')) return;
if (liveDay && liveDay.total > 0) await TrekShell.syncTripDay(liveDay).catch(reportNativeFailure);
else await TrekShell.endTripDay().catch(reportNativeFailure);