mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-20 19:16:08 +00:00
Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fe7847fc08 | |||
| 77b9252577 |
@@ -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",
|
||||
|
||||
@@ -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" = "與儀表板相同的旅行";
|
||||
|
||||
@@ -108,7 +108,7 @@ export default function JourneyEntryCover({
|
||||
// growing its box moved every card after it once a swipe had landed, and the
|
||||
// snap then pulled the strip again, which read as a jolt (carousels keep the
|
||||
// room for it with their gap and top padding).
|
||||
className={`relative h-[152px] w-[136px] flex-none origin-bottom overflow-hidden rounded-[18px] text-start transition-[transform,box-shadow] duration-300 ease-[cubic-bezier(.2,.8,.2,1)] motion-reduce:transition-none ${
|
||||
className={`relative h-[152px] w-[136px] flex-none origin-bottom overflow-hidden rounded-[18px] text-start transition-[transform,box-shadow] duration-200 ease-[cubic-bezier(.2,.8,.2,1)] motion-reduce:transition-none ${
|
||||
isActive ? 'z-[1] scale-[1.18] shadow-[0_18px_40px_-16px_rgba(0,0,0,.55)]' : 'scale-100 shadow-[0_10px_24px_-14px_rgba(0,0,0,.5)]'
|
||||
} ${src ? '' : emptyGround} ${isSuggestion ? 'opacity-90' : ''}`}
|
||||
// backgroundImage, not background: the shorthand would drop the opaque colour
|
||||
|
||||
@@ -693,8 +693,10 @@ function JourneyMap(
|
||||
/>
|
||||
{/* A finger zooms with a pinch, and on a phone these sat under the bottom bar (#3001). */}
|
||||
<div
|
||||
className="[@media(pointer:coarse)]:hidden"
|
||||
style={{ position: 'absolute', bottom: 12, right: 12, zIndex: 400, display: 'flex', flexDirection: 'column', gap: 4 }}
|
||||
// The display lives in the classes, not the style: an inline display beat the
|
||||
// hidden class and left the buttons on phones.
|
||||
className="flex flex-col gap-1 [@media(pointer:coarse)]:hidden"
|
||||
style={{ position: 'absolute', bottom: 12, right: 12, zIndex: 400 }}
|
||||
>
|
||||
<button type="button" onClick={() => zoom(true)} style={zoomButtonStyle(dark)}>+</button>
|
||||
<button type="button" onClick={() => zoom(false)} style={zoomButtonStyle(dark)}>−</button>
|
||||
|
||||
@@ -69,7 +69,7 @@ export default function MobileMapTimeline({
|
||||
controlsTop,
|
||||
}: Props) {
|
||||
const {
|
||||
mapRef, carouselRef, cardRefs, activeIndex, setActiveIndex, scrubberDays,
|
||||
mapRef, carouselRef, cardRefs, activeIndex, focusIndex, setActiveIndex, scrubberDays,
|
||||
syncMapToCard: syncMapToCarousel, handleMarkerClick, handleCardTap, openEntryById, jumpToDay,
|
||||
} = useJourneyCarouselSync({ entries, mapEntries, onOpenEntry: onEntryClick })
|
||||
// The delayed initial focus reads both through refs so it always works off
|
||||
@@ -207,7 +207,7 @@ export default function MobileMapTimeline({
|
||||
<JourneyEntryCover
|
||||
entry={entry}
|
||||
dayColor={dayColorOf(scrubberDays, entry.entry_date)}
|
||||
isActive={i === activeIndex}
|
||||
isActive={i === focusIndex}
|
||||
onClick={() => handleCardTap(entry, i)}
|
||||
showMood={showMood}
|
||||
showWeather={showWeather}
|
||||
|
||||
@@ -129,7 +129,7 @@ describe('useJourneyCarouselSync', () => {
|
||||
carousel.dispatchEvent(new Event('scroll'));
|
||||
act(() => vi.advanceTimersByTime(100));
|
||||
carousel.dispatchEvent(new Event('scroll'));
|
||||
act(() => vi.advanceTimersByTime(149));
|
||||
act(() => vi.advanceTimersByTime(89));
|
||||
expect(hook.result.current.activeIndex).toBe(0);
|
||||
act(() => vi.advanceTimersByTime(1));
|
||||
// Centre 250: card 1 spans 200 to 300.
|
||||
@@ -170,7 +170,7 @@ describe('useJourneyCarouselSync', () => {
|
||||
Object.defineProperty(carousel, 'scrollLeft', { value: scrollLeft, configurable: true });
|
||||
carousel.dispatchEvent(new Event('scroll'));
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(150);
|
||||
vi.advanceTimersByTime(90);
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -25,6 +25,13 @@ export interface JourneyCarouselSyncOptions<E extends CarouselEntry> {
|
||||
* once scrolling settles, and the map follows it; a marker, a day on the scrubber or a
|
||||
* tap brings its card to the centre.
|
||||
*/
|
||||
/**
|
||||
* How long the strip has to be still before the swipe counts as landed: long
|
||||
* enough to see past the gaps between scroll events of a momentum swipe, short
|
||||
* enough that the map follows the card without a noticeable wait.
|
||||
*/
|
||||
const SETTLE_MS = 90;
|
||||
|
||||
export function useJourneyCarouselSync<E extends CarouselEntry>({
|
||||
entries,
|
||||
mapEntries,
|
||||
@@ -35,6 +42,10 @@ export function useJourneyCarouselSync<E extends CarouselEntry>({
|
||||
const carouselRef = useRef<HTMLDivElement>(null);
|
||||
const cardRefs = useRef<Map<number, HTMLDivElement>>(new Map());
|
||||
const [activeIndex, setActiveIndex] = useState(0);
|
||||
// The card nearest the centre while a swipe is still moving: drawn larger at
|
||||
// once (a transform, so nothing reflows), while the active card and the map
|
||||
// only follow once the strip settles. Null when not swiping.
|
||||
const [liveIndex, setLiveIndex] = useState<number | null>(null);
|
||||
|
||||
const scrubberDays = useMemo(() => journeyDays(entries), [entries]);
|
||||
|
||||
@@ -57,9 +68,9 @@ export function useJourneyCarouselSync<E extends CarouselEntry>({
|
||||
// Pick the card closest to the horizontal centre. More stable than
|
||||
// IntersectionObserver thresholds when the active card can drift toward the
|
||||
// viewport edge with proximity snapping.
|
||||
const pickNearestCard = useCallback(() => {
|
||||
const nearestCard = useCallback((): number | null => {
|
||||
const el = carouselRef.current;
|
||||
if (!el) return;
|
||||
if (!el) return null;
|
||||
const center = el.getBoundingClientRect().left + el.clientWidth / 2;
|
||||
let bestIdx = 0;
|
||||
let bestDist = Infinity;
|
||||
@@ -79,11 +90,18 @@ export function useJourneyCarouselSync<E extends CarouselEntry>({
|
||||
const scrolled = Math.abs(el.scrollLeft);
|
||||
if (travel > 1 && scrolled >= travel - 1) bestIdx = cardRefs.current.size - 1;
|
||||
else if (travel > 1 && scrolled <= 0) bestIdx = 0;
|
||||
return bestIdx;
|
||||
}, []);
|
||||
|
||||
const pickNearestCard = useCallback(() => {
|
||||
const bestIdx = nearestCard();
|
||||
if (bestIdx == null) return;
|
||||
setLiveIndex(null);
|
||||
setActiveIndex((prev) => {
|
||||
if (prev !== bestIdx) syncMapToCard(bestIdx);
|
||||
return bestIdx;
|
||||
});
|
||||
}, [syncMapToCard]);
|
||||
}, [nearestCard, syncMapToCard]);
|
||||
|
||||
// Defer every state update until scrolling settles: updating the active card
|
||||
// mid swipe resizes the cards and reflows the layout on every frame.
|
||||
@@ -91,9 +109,16 @@ export function useJourneyCarouselSync<E extends CarouselEntry>({
|
||||
const el = carouselRef.current;
|
||||
if (!el || entries.length === 0) return;
|
||||
let settleTimer: number | null = null;
|
||||
let frame: number | null = null;
|
||||
const onScroll = () => {
|
||||
if (frame == null) {
|
||||
frame = window.requestAnimationFrame(() => {
|
||||
frame = null;
|
||||
setLiveIndex(nearestCard());
|
||||
});
|
||||
}
|
||||
if (settleTimer != null) window.clearTimeout(settleTimer);
|
||||
settleTimer = window.setTimeout(pickNearestCard, 150);
|
||||
settleTimer = window.setTimeout(pickNearestCard, SETTLE_MS);
|
||||
};
|
||||
// Where the browser says when the snap has landed, the card grows right then
|
||||
// instead of a beat later; the timer stays for the ones that do not.
|
||||
@@ -108,8 +133,9 @@ export function useJourneyCarouselSync<E extends CarouselEntry>({
|
||||
el.removeEventListener('scroll', onScroll);
|
||||
el.removeEventListener('scrollend', onScrollEnd);
|
||||
if (settleTimer != null) window.clearTimeout(settleTimer);
|
||||
if (frame != null) window.cancelAnimationFrame(frame);
|
||||
};
|
||||
}, [entries.length, pickNearestCard]);
|
||||
}, [entries.length, pickNearestCard, nearestCard]);
|
||||
|
||||
const scrollCardIntoCenter = useCallback((idx: number) => {
|
||||
cardRefs.current.get(idx)?.scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'nearest' });
|
||||
@@ -168,6 +194,8 @@ export function useJourneyCarouselSync<E extends CarouselEntry>({
|
||||
carouselRef,
|
||||
cardRefs,
|
||||
activeIndex,
|
||||
/** The card to draw as the active one: the one at the centre while swiping, else the active card. */
|
||||
focusIndex: liveIndex ?? activeIndex,
|
||||
setActiveIndex,
|
||||
scrubberDays,
|
||||
syncMapToCard,
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -102,7 +102,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
)
|
||||
|
||||
const {
|
||||
mapRef, carouselRef, cardRefs, activeIndex, setActiveIndex, scrubberDays,
|
||||
mapRef, carouselRef, cardRefs, activeIndex, focusIndex, setActiveIndex, scrubberDays,
|
||||
syncMapToCard, handleMarkerClick, handleCardTap, openEntryById, jumpToDay,
|
||||
} = useJourneyCarouselSync<JourneyEntry>({ entries, mapEntries: sidebarMapItems, onOpenEntry: setEditingEntry, syncMapOnTap: true })
|
||||
|
||||
@@ -510,7 +510,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
<JourneyEntryCover
|
||||
entry={entry}
|
||||
dayColor={dayColorOf(scrubberDays, entry.entry_date)}
|
||||
isActive={i === activeIndex}
|
||||
isActive={i === focusIndex}
|
||||
onClick={() => handleCardTap(entry, i)}
|
||||
showMood={current.show_mood !== 0}
|
||||
showWeather={current.show_weather !== 0}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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.
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
@@ -78,7 +93,8 @@ export async function packingDetail(
|
||||
const grams = b.total_weight_grams ?? inBag.reduce((sum, i) => sum + (i.weight_grams ?? 0) * (i.quantity ?? 1), 0);
|
||||
return {
|
||||
name: b.name,
|
||||
color: HEX.test(b.color) ? b.color : '#4A7DDB',
|
||||
// Empty when the bag has no usable colour: the widget then uses its own blue.
|
||||
color: HEX.test(b.color) ? b.color : '',
|
||||
grams,
|
||||
...(b.weight_limit_grams ? { limit: b.weight_limit_grams } : {}),
|
||||
packed: inBag.filter((i) => i.checked).length,
|
||||
@@ -172,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 ?? [];
|
||||
|
||||
@@ -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' }]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user