feat(native): a flight widget and a boarding-pass Live Activity

A new Flight widget on iOS (small to large and the lock screen) and Android
shows the trip's next flight or the one in the air: both airports, the arc
with the aircraft, a countdown the system keeps running, and the delay. It
follows the feed's phase, so a late departure is not flown along the arc.
Around a flight the travel day's Live Activity becomes a boarding pass with
a running bar and countdown, in the Dynamic Island too.
This commit is contained in:
Maurice
2026-11-13 15:29:21 +01:00
parent 4796615439
commit 27f12c2245
80 changed files with 1390 additions and 20 deletions
@@ -15,6 +15,7 @@ import androidx.glance.appwidget.GlanceRemoteViews
import com.liketrek.trek.tripday.TripDayNotification
import com.liketrek.trek.widget.AtlasWidget
import com.liketrek.trek.widget.BookingsWidget
import com.liketrek.trek.widget.FlightWidget
import com.liketrek.trek.widget.CollabWidget
import com.liketrek.trek.widget.PackingWidget
import com.liketrek.trek.widget.TodayWidget
@@ -74,6 +75,7 @@ class WidgetGalleryActivity : Activity() {
"trip" to TripWidget(),
"today" to TodayWidget(),
"bookings" to BookingsWidget(),
"flight" to FlightWidget(),
"todos" to TodosWidget(),
"packing" to PackingWidget(),
"atlas" to AtlasWidget(),
@@ -142,6 +142,15 @@
</intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_bookings" />
</receiver>
<receiver
android:name=".widget.FlightWidgetReceiver"
android:label="@string/widget_flight_name"
android:exported="false">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_flight" />
</receiver>
<receiver
android:name=".widget.TodosWidgetReceiver"
android:label="@string/widget_todos_name"
@@ -32,6 +32,10 @@ class BookingsWidgetReceiver : TrekWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget = BookingsWidget()
}
class FlightWidgetReceiver : TrekWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget = FlightWidget()
}
class TodosWidgetReceiver : TrekWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget = TodosWidget()
}
@@ -56,6 +60,7 @@ object TrekWidgetUpdater {
TripWidgetReceiver::class,
TodayWidgetReceiver::class,
BookingsWidgetReceiver::class,
FlightWidgetReceiver::class,
TodosWidgetReceiver::class,
PackingWidgetReceiver::class,
AtlasWidgetReceiver::class,
@@ -448,6 +448,170 @@ private fun BookingRow(booking: WidgetSnapshot.Booking, labels: WidgetSnapshot.L
}
}
// ---- Flight ----
/**
* Where a flight stands now (as FlightMoment on iOS). What the feed saw wins: a
* flight still at the gate past its planned departure is not flown along the
* arc, and it is only landed once confirmed. Only a flight the feed never heard
* of moves on by its schedule alone; a lost one stops two hours after arrival.
*/
private class FlightMoment(f: WidgetSnapshot.Flight, nowSeconds: Long) {
val start: Long = f.depActual ?: f.depExpected ?: f.dep
val end: Long = maxOf(f.arrExpected ?: f.arr, start + 60)
private val heard = f.seen != null
val landed = f.landed || (!heard && nowSeconds >= end) || nowSeconds >= end + 7200
val airborne = !landed && (f.airborne || f.depActual != null || (!heard && nowSeconds >= start))
val ready = !landed && !airborne && nowSeconds >= start
val progress: Float = when {
landed -> 1f
airborne -> ((nowSeconds - start).toFloat() / (end - start)).coerceIn(0f, 0.98f)
else -> 0f
}
}
/** A duration in the app's words: "2 d 4 h", "1 h 5 min", "12 min". */
private fun durationText(seconds: Long, labels: WidgetSnapshot.Labels): String {
val minutes = ((seconds + 59) / 60).coerceAtLeast(1)
val days = minutes / 1440
val hours = (minutes % 1440) / 60
val rest = minutes % 60
return when {
days > 0 -> labels.durDaysHours.replace("{d}", "$days").replace("{h}", "$hours")
hours > 0 -> labels.durHoursMinutes.replace("{h}", "$hours").replace("{m}", "$rest")
else -> labels.durMinutes.replace("{m}", "$rest")
}
}
/** "Departs in 2 h 10 min", "Lands in 1 h 5 min", "Landed". */
private fun momentText(m: FlightMoment, labels: WidgetSnapshot.Labels, nowSeconds: Long): String = when {
m.landed -> labels.flightLanded
m.ready -> labels.flightReady
m.airborne -> labels.flightLands.replace("{time}", durationText(m.end - nowSeconds, labels))
else -> labels.flightDeparts.replace("{time}", durationText(m.start - nowSeconds, labels))
}
/** The delay as a chip's text and colour; nothing to say without data. */
private fun delayChip(delay: Int?, labels: WidgetSnapshot.Labels): Pair<String, ColorProvider>? = when {
delay == null -> null
delay > 5 -> labels.flightLate.replace("{m}", "$delay") to (if (delay >= 30) TrekStatus.danger else TrekStatus.pending)
delay < -5 -> labels.flightEarly.replace("{m}", "${-delay}") to TrekStatus.confirmed
else -> labels.flightOnTime to TrekStatus.confirmed
}
private const val FLIGHT_BLUE = 0xFF4A7DDB.toInt()
/**
* The trip's next flight, or the one in the air: both airports large, the
* route as an arc with the aircraft on it, the moment in words and the delay.
* The arc and the words follow the clock each time the widget is drawn.
*/
class FlightWidget : TrekWidget() {
@Composable
override fun Content(snapshot: WidgetSnapshot?) {
val context = LocalContext.current
val size = LocalSize.current
val labels = snapshot?.labels ?: return EmptyWidget(WidgetSamples.emptyText(context))
val flight = snapshot.flight
WidgetFrame(onClick = openPath(context, flight?.path ?: snapshot.trip?.path ?: "/")) {
Column(modifier = GlanceModifier.fillMaxSize()) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = GlanceModifier.fillMaxWidth()) {
Icon(Icons.Rounded.Flight, GlanceTheme.colors.primary, 14.dp)
Spacer(GlanceModifier.width(5.dp))
Eyebrow(flight?.number ?: labels.flight, GlanceTheme.colors.primary, GlanceModifier.defaultWeight())
flight?.let { f ->
delayChip(f.delay, labels)?.let { (text, color) ->
if (size.isWide || (f.delay ?: 0) > 5) Chip(text, GlanceTheme.colors.surfaceVariant, color)
}
}
}
if (flight == null) {
Spacer(GlanceModifier.defaultWeight())
Line(labels.noFlight, 14.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium, maxLines = 2)
Spacer(GlanceModifier.defaultWeight())
} else {
FlightBody(flight, labels, size.isWide, size.isTall)
}
}
}
}
}
/** The origin stands on the right in a right-to-left layout, so the drawn arc is mirrored with it. */
@Composable
private fun isRtl(): Boolean =
LocalContext.current.resources.configuration.layoutDirection == android.view.View.LAYOUT_DIRECTION_RTL
@Composable
private fun ColumnScope.FlightBody(f: WidgetSnapshot.Flight, labels: WidgetSnapshot.Labels, wide: Boolean, tall: Boolean) {
val now = System.currentTimeMillis() / 1000
val m = FlightMoment(f, now)
val arrival = f.arrTimeExpected ?: f.arrTime
val momentColor = if (m.airborne) GlanceTheme.colors.primary else GlanceTheme.colors.onSurface
Spacer(GlanceModifier.defaultWeight())
if (!wide) Line(momentText(m, labels, now), 13.sp, momentColor, FontWeight.Bold, maxLines = 2)
Spacer(GlanceModifier.height(6.dp))
Row(verticalAlignment = Alignment.CenterVertically, modifier = GlanceModifier.fillMaxWidth()) {
Column(modifier = GlanceModifier.defaultWeight()) {
Line(f.from, if (wide) 26.sp else 22.sp, weight = FontWeight.Bold)
if (wide) f.fromCity?.let { Line(it, 11.sp, GlanceTheme.colors.onSurfaceVariant) }
}
if (wide) {
Image(
provider = ImageProvider(WidgetArt.flightArc(m.progress, FLIGHT_BLUE, android.graphics.Color.argb(90, 120, 120, 130), rtl = isRtl())),
contentDescription = null,
contentScale = ContentScale.Fit,
modifier = GlanceModifier.width(120.dp).height(26.dp),
)
}
Column(modifier = GlanceModifier.defaultWeight(), horizontalAlignment = Alignment.End) {
Line(f.to, if (wide) 26.sp else 22.sp, weight = FontWeight.Bold)
if (wide) f.toCity?.let { Line(it, 11.sp, GlanceTheme.colors.onSurfaceVariant) }
}
}
if (!wide) {
Image(
provider = ImageProvider(WidgetArt.flightArc(m.progress, FLIGHT_BLUE, android.graphics.Color.argb(90, 120, 120, 130), rtl = isRtl())),
contentDescription = null,
contentScale = ContentScale.FillBounds,
modifier = GlanceModifier.fillMaxWidth().height(22.dp),
)
}
Spacer(GlanceModifier.height(4.dp))
Row(modifier = GlanceModifier.fillMaxWidth()) {
Line(f.depTime, 12.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Bold, modifier = GlanceModifier.defaultWeight())
Line(arrival, 12.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Bold)
}
if (wide) {
Spacer(GlanceModifier.height(8.dp))
Line(momentText(m, labels, now), 13.sp, momentColor, FontWeight.Bold)
if (m.airborne) {
Spacer(GlanceModifier.height(5.dp))
Bar(m.progress, GlanceTheme.colors.primary, GlanceTheme.colors.surfaceVariant, 5.dp)
}
}
if (tall) {
Spacer(GlanceModifier.height(10.dp))
f.aircraft?.let { FlightFact(it) }
f.fromCity?.let { from -> f.toCity?.let { to -> FlightFact("$from \u2192 $to") } }
}
Spacer(GlanceModifier.defaultWeight())
}
@Composable
private fun FlightFact(text: String) {
Row(
modifier = GlanceModifier.fillMaxWidth().background(GlanceTheme.colors.surfaceVariant).cornerRadius(12.dp)
.padding(horizontal = 10.dp, vertical = 7.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(Icons.Rounded.Flight, GlanceTheme.colors.primary, 13.dp)
Spacer(GlanceModifier.width(7.dp))
Line(text, 12.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium)
}
Spacer(GlanceModifier.height(5.dp))
}
// ---- To-dos ----
/** What is still open for the trip, and how far the packing has come. */
@@ -149,4 +149,100 @@ object WidgetArt {
}
return bitmap
}
/**
* A flight's route as an arc: dashed ahead, solid where it has flown, a dot
* at either airport and an airliner riding the curve at its heading. White
* on a translucent track, like the ring; the widget tints nothing, so the
* caller passes the flight colour.
*/
fun flightArc(
progress: Float,
color: Int,
track: Int,
width: Int = 600,
height: Int = 120,
showPlane: Boolean = true,
rtl: Boolean = false,
): Bitmap {
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
// Right to left the origin stands on the right: the whole drawing is mirrored.
if (rtl) canvas.scale(-1f, 1f, width / 2f, height / 2f)
val p = progress.coerceIn(0f, 1f)
val inset = height * 0.14f
val sx = inset
val sy = height - inset
val ex = width - inset
val ey = height - inset
val cx = width / 2f
val cy = -height * 0.45f
val path = android.graphics.Path().apply {
moveTo(sx, sy)
quadTo(cx, cy, ex, ey)
}
val line = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
strokeCap = Paint.Cap.ROUND
strokeWidth = height * 0.035f
this.color = track
pathEffect = android.graphics.DashPathEffect(floatArrayOf(height * 0.02f, height * 0.07f), 0f)
}
canvas.drawPath(path, line)
val measure = android.graphics.PathMeasure(path, false)
if (p > 0f) {
val flown = android.graphics.Path()
measure.getSegment(0f, measure.length * p, flown, true)
line.pathEffect = null
line.strokeWidth = height * 0.045f
line.color = color
canvas.drawPath(flown, line)
}
val dot = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color }
canvas.drawCircle(sx, sy, height * 0.05f, dot)
val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = if (p >= 1f) Paint.Style.FILL else Paint.Style.STROKE
strokeWidth = height * 0.03f
this.color = color
}
canvas.drawCircle(ex, ey, height * 0.06f, ring)
if (showPlane) {
val pos = FloatArray(2)
val tan = FloatArray(2)
measure.getPosTan(measure.length * p, pos, tan)
canvas.save()
canvas.translate(pos[0], pos[1])
canvas.rotate(Math.toDegrees(kotlin.math.atan2(tan[1].toDouble(), tan[0].toDouble())).toFloat())
val scale = height * 0.012f
canvas.scale(scale, scale)
canvas.drawCircle(0f, 0f, 13f, Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = Color.WHITE })
canvas.drawPath(airliner(), Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color })
canvas.restore()
}
return bitmap
}
/** An airliner seen from above, nose along +x, about 18 units long, centred. */
private fun airliner(): android.graphics.Path = android.graphics.Path().apply {
moveTo(9f, 0f)
cubicTo(9f, -0.9f, 8.3f, -1.3f, 7.4f, -1.3f)
lineTo(3.2f, -1.3f)
lineTo(-1.6f, -7.6f)
lineTo(-3.7f, -7.6f)
lineTo(-1.4f, -1.3f)
lineTo(-5.5f, -1.3f)
lineTo(-7.2f, -3.7f)
lineTo(-8.8f, -3.7f)
lineTo(-7.8f, 0f)
lineTo(-8.8f, 3.7f)
lineTo(-7.2f, 3.7f)
lineTo(-5.5f, 1.3f)
lineTo(-1.4f, 1.3f)
lineTo(-3.7f, 7.6f)
lineTo(-1.6f, 7.6f)
lineTo(3.2f, 1.3f)
lineTo(7.4f, 1.3f)
cubicTo(8.3f, 1.3f, 9f, 0.9f, 9f, 0f)
close()
}
}
@@ -11,6 +11,19 @@ import org.json.JSONObject
* (WidgetSnapshot.sample in TrekFamily.swift).
*/
object WidgetSamples {
/** In the air on a running trip, two days ahead before one: the same LH 716 as the iOS sample. */
private fun flightJson(running: Boolean): String {
val now = System.currentTimeMillis() / 1000
val dep = if (running) now - 4 * 3600 else now + 2 * 86_400 + 5 * 3600
val live = if (running) {
""""depActual": ${dep + 18 * 60}, "arrExpected": ${dep + 12 * 3600 + 41 * 60}, "arrTimeExpected": "08:46", "delay": 16, "aircraft": "A359 D-AIXA","""
} else {
""
}
return """{"number": "LH 716", "from": "FRA", "to": "HND", "fromCity": "Frankfurt", "toCity": "Tokyo Haneda",
"dep": $dep, "arr": ${dep + 12 * 3600 + 25 * 60}, $live "depTime": "13:05", "arrTime": "08:30", "path": "/trips/1?booking=1"}"""
}
fun emptyText(context: Context): String = context.getString(R.string.widget_empty)
fun snapshot(running: Boolean, now: LocalDate = LocalDate.now()): WidgetSnapshot = WidgetSnapshot.fromJson(JSONObject(json(running, now)))
@@ -37,6 +50,7 @@ object WidgetSamples {
"place": "Kyoto, Japan", "dayCount": 9, "placeCount": 34, "memberCount": 3},
$today
"weather": {"temp": 18, "high": 21, "low": 11, "main": "${if (running) "Clear" else "Clouds"}", "label": "Mostly sunny", "place": "Kyoto", "rain": 10},
"flight": ${flightJson(running)},
"bookings": [
{"title": "LH 716", "kind": "flight", "date": "${iso(if (running) 6 else 12)}", "time": "13:05", "detail": "FRA → HND", "confirmed": true, "path": "/trips/1"},
{"title": "Shinkansen Nozomi 21", "kind": "train", "date": "${iso(if (running) 0 else 13)}", "time": "09:12", "detail": "Tokyo → Kyoto", "confirmed": true, "path": "/trips/1"},
@@ -25,6 +25,8 @@ data class WidgetSnapshot(
val atlas: Atlas?,
val collab: Collab?,
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,
) {
data class Trip(
val title: String,
@@ -105,6 +107,39 @@ data class WidgetSnapshot(
data class Collab(val members: List<Member>, val messages: List<Message>, val poll: Poll?, val path: String)
/**
* The flight widget's flight. Times are epoch seconds, so the widget moves on
* with the clock between two snapshots; the clock times at either airport
* come formatted, since the widget has no zone data.
*/
data class Flight(
val number: String,
val from: String,
val to: String,
val fromCity: String?,
val toCity: String?,
val dep: Long,
val arr: Long,
/** Observed take-off. */
val depActual: Long?,
/** Before take-off: the planned departure plus the delay seen so far. */
val depExpected: Long?,
/** The feed saw the aircraft in the air when the app last looked. */
val airborne: Boolean,
/** Touchdown once landed, else the estimate while in the air. */
val arrExpected: Long?,
val landed: Boolean,
val depTime: String,
val arrTime: String,
val arrTimeExpected: String?,
/** Minutes late against the schedule, negative when early. */
val delay: Int?,
val aircraft: String?,
/** When the feed last heard the aircraft; null for a flight it never heard of. */
val seen: Long?,
val path: String,
)
/** The labels, translated by the app. The optional ones fall back to English. */
data class Labels(private val raw: JSONObject) {
val nextTrip get() = text("nextTrip", "Next trip")
@@ -137,6 +172,23 @@ data class WidgetSnapshot(
val votes get() = text("votes", "votes")
val noMessages get() = text("noMessages", "No messages yet")
val departure get() = text("departure", "Departure")
val flight get() = text("flight", "Flight")
/** Contains "{time}". */
val flightDeparts get() = text("flightDeparts", "Departs in {time}")
/** Contains "{time}". */
val flightLands get() = text("flightLands", "Lands in {time}")
val flightLanded get() = text("flightLanded", "Landed")
val flightReady get() = text("flightReady", "Ready for departure")
val noFlight get() = text("noFlight", "No flight ahead")
val flightOnTime get() = text("flightOnTime", "On time")
/** Contains "{m}". */
val flightLate get() = text("flightLate", "+{m} min")
/** Contains "{m}". */
val flightEarly get() = text("flightEarly", "{m} min early")
/** Contain "{d}" and "{h}", "{h}" and "{m}", and "{m}". */
val durDaysHours get() = text("durDaysHours", "{d} d {h} h")
val durHoursMinutes get() = text("durHoursMinutes", "{h} h {m} min")
val durMinutes get() = text("durMinutes", "{m} min")
private fun text(key: String, fallback: String): String = raw.optString(key).ifBlank { fallback }
}
@@ -240,6 +292,29 @@ data class WidgetSnapshot(
)
},
labels = Labels(o.optJSONObject("labels") ?: JSONObject()),
flight = o.optJSONObject("flight")?.let { f ->
Flight(
number = f.optString("number"),
from = f.optString("from"),
to = f.optString("to"),
fromCity = f.str("fromCity"),
toCity = f.str("toCity"),
dep = f.optLong("dep"),
arr = f.optLong("arr"),
depActual = f.long("depActual"),
depExpected = f.long("depExpected"),
airborne = f.optBoolean("airborne"),
arrExpected = f.long("arrExpected"),
landed = f.optBoolean("landed"),
depTime = f.optString("depTime"),
arrTime = f.optString("arrTime"),
arrTimeExpected = f.str("arrTimeExpected"),
delay = f.int("delay"),
aircraft = f.str("aircraft"),
seen = f.long("seen"),
path = f.optString("path", "/"),
)
}?.takeIf { it.dep > 0 && it.arr > 0 },
)
fun day(iso: String?): LocalDate? {
@@ -258,6 +333,8 @@ data class WidgetSnapshot(
private fun JSONObject.int(key: String): Int? = if (has(key) && !isNull(key)) optInt(key) else null
private fun JSONObject.long(key: String): Long? = if (has(key) && !isNull(key)) optLong(key) else null
private fun JSONArray?.objects(): List<JSONObject> =
if (this == null) emptyList() else (0 until length()).mapNotNull { optJSONObject(it) }
@@ -8,6 +8,8 @@
<string name="widget_today_description">خطة اليوم كخط زمني، مع الطقس والمحطة التالية.</string>
<string name="widget_bookings_name">الحجوزات</string>
<string name="widget_bookings_description">رحلاتك وقطاراتك وفنادقك وحجوزات المطاعم القادمة ومواعيدها.</string>
<string name="widget_flight_name">الرحلة</string>
<string name="widget_flight_description">رحلتك القادمة مباشرة: عد تنازلي للإقلاع، والطائرة في طريقها، والتأخير والوصول.</string>
<string name="widget_todos_name">المهام</string>
<string name="widget_todos_description">ما تبقى للرحلة، ومدى تقدم تجهيز الأمتعة.</string>
<string name="widget_packing_name">قائمة الأمتعة</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Günün planı zaman xətti kimi, hava və növbəti dayanacaqla.</string>
<string name="widget_bookings_name">Bronlar</string>
<string name="widget_bookings_description">Növbəti uçuşlar, qatarlar, otellər və restoranlar, nə vaxt olduqları ilə.</string>
<string name="widget_flight_name">Uçuş</string>
<string name="widget_flight_description">Növbəti uçuşun canlı: uçuşa qədər geri sayım, yolda olan təyyarə, gecikmə və gəliş.</string>
<string name="widget_todos_name">Tapşırıqlar</string>
<string name="widget_todos_description">Səyahət üçün hələ nəyin qaldığı və yığışmağın nə yerdə olduğu.</string>
<string name="widget_packing_name">Yük siyahısı</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">以时间线显示今天的计划,附带天气和下一站。</string>
<string name="widget_bookings_name">预订</string>
<string name="widget_bookings_description">你接下来的航班、火车、酒店和餐厅,以及时间。</string>
<string name="widget_flight_name">航班</string>
<string name="widget_flight_description">实时查看下一班航班:起飞倒计时、飞行中的飞机、延误和到达。</string>
<string name="widget_todos_name">待办</string>
<string name="widget_todos_description">旅行还剩哪些事没做,以及行李收拾到哪一步。</string>
<string name="widget_packing_name">行李</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">以時間軸顯示今天的計畫,附上天氣與下一站。</string>
<string name="widget_bookings_name">預訂</string>
<string name="widget_bookings_description">你接下來的航班、火車、飯店與餐廳,以及時間。</string>
<string name="widget_flight_name">航班</string>
<string name="widget_flight_description">即時查看下一班航班:起飛倒數、飛行中的飛機、延誤和抵達。</string>
<string name="widget_todos_name">待辦</string>
<string name="widget_todos_description">旅行還剩哪些事沒做,以及行李整理到哪一步。</string>
<string name="widget_packing_name">行李</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">El pla del dia com a línia de temps, amb el temps i la propera parada.</string>
<string name="widget_bookings_name">Reserves</string>
<string name="widget_bookings_description">Els teus propers vols, trens, hotels i taules, i quan toquen.</string>
<string name="widget_flight_name">Vol</string>
<string name="widget_flight_description">El teu proper vol en directe: compte enrere de la sortida, l’avió en camí, retard i arribada.</string>
<string name="widget_todos_name">Tasques</string>
<string name="widget_todos_description">El que encara queda per al viatge i com va l\'equipatge.</string>
<string name="widget_packing_name">Equipatge</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Plán dne jako časová osa, s počasím a další zastávkou.</string>
<string name="widget_bookings_name">Rezervace</string>
<string name="widget_bookings_description">Tvoje další lety, vlaky, hotely a stoly, a kdy tě čekají.</string>
<string name="widget_flight_name">Let</string>
<string name="widget_flight_description">Tvůj další let živě: odpočet do odletu, letadlo na cestě, zpoždění a přílet.</string>
<string name="widget_todos_name">Úkoly</string>
<string name="widget_todos_description">Co ještě zbývá k cestě a jak daleko je balení.</string>
<string name="widget_packing_name">Balení</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Der Tagesplan als Zeitleiste, mit dem Wetter und dem nächsten Stopp.</string>
<string name="widget_bookings_name">Buchungen</string>
<string name="widget_bookings_description">Deine nächsten Flüge, Züge, Hotels und Tische, und wann sie anstehen.</string>
<string name="widget_flight_name">Flug</string>
<string name="widget_flight_description">Dein nächster Flug live: Countdown bis zum Abflug, die Maschine unterwegs, Verspätung und Ankunft.</string>
<string name="widget_todos_name">To-dos</string>
<string name="widget_todos_description">Was für die Reise noch offen ist und wie weit das Packen ist.</string>
<string name="widget_packing_name">Packliste</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Το πρόγραμμα της ημέρας ως χρονολόγιο, με τον καιρό και την επόμενη στάση.</string>
<string name="widget_bookings_name">Κρατήσεις</string>
<string name="widget_bookings_description">Οι επόμενες πτήσεις, τα τρένα, τα ξενοδοχεία και τα τραπέζια σου, και πότε είναι.</string>
<string name="widget_flight_name">Πτήση</string>
<string name="widget_flight_description">Η επόμενη πτήση σου ζωντανά: αντίστροφη μέτρηση για την αναχώρηση, το αεροσκάφος καθ’ οδόν, καθυστέρηση και άφιξη.</string>
<string name="widget_todos_name">Εκκρεμότητες</string>
<string name="widget_todos_description">Τι μένει ακόμα για το ταξίδι και πόσο έχει προχωρήσει το πακετάρισμα.</string>
<string name="widget_packing_name">Αποσκευές</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">El plan del día como línea de tiempo, con el tiempo y la próxima parada.</string>
<string name="widget_bookings_name">Reservas</string>
<string name="widget_bookings_description">Tus próximos vuelos, trenes, hoteles y mesas, y cuándo tocan.</string>
<string name="widget_flight_name">Vuelo</string>
<string name="widget_flight_description">Tu próximo vuelo en directo: cuenta atrás de la salida, el avión en camino, retraso y llegada.</string>
<string name="widget_todos_name">Tareas</string>
<string name="widget_todos_description">Lo que aún queda para el viaje y cómo va la maleta.</string>
<string name="widget_packing_name">Equipaje</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Päeva plaan ajajoonena, koos ilma ja järgmise peatusega.</string>
<string name="widget_bookings_name">Broneeringud</string>
<string name="widget_bookings_description">Sinu järgmised lennud, rongid, hotellid ja lauad ning millal need on.</string>
<string name="widget_flight_name">Lend</string>
<string name="widget_flight_description">Sinu järgmine lend otse: loendus väljumiseni, lennuk teel, hilinemine ja saabumine.</string>
<string name="widget_todos_name">Ülesanded</string>
<string name="widget_todos_description">Mis reisi jaoks veel tegemata on ja kui kaugel pakkimine on.</string>
<string name="widget_packing_name">Pakkimine</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Le programme du jour en frise, avec la météo et la prochaine étape.</string>
<string name="widget_bookings_name">Réservations</string>
<string name="widget_bookings_description">Vos prochains vols, trains, hôtels et tables, et quand ils arrivent.</string>
<string name="widget_flight_name">Vol</string>
<string name="widget_flight_description">Votre prochain vol en direct : compte à rebours du départ, l’avion en route, retard et arrivée.</string>
<string name="widget_todos_name">À faire</string>
<string name="widget_todos_description">Ce qui reste à faire pour le voyage et où en sont les bagages.</string>
<string name="widget_packing_name">Bagages</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">A nap terve idővonalon, az időjárással és a következő megállóval.</string>
<string name="widget_bookings_name">Foglalások</string>
<string name="widget_bookings_description">A következő járataid, vonataid, szállásaid és asztalfoglalásaid, és hogy mikor esedékesek.</string>
<string name="widget_flight_name">Járat</string>
<string name="widget_flight_description">A következő járatod élőben: visszaszámlálás az indulásig, a gép útközben, késés és érkezés.</string>
<string name="widget_todos_name">Teendők</string>
<string name="widget_todos_description">Ami még hátravan az utazáshoz, és hol tart a csomagolás.</string>
<string name="widget_packing_name">Csomagolás</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Rencana hari ini sebagai linimasa, dengan cuaca dan perhentian berikutnya.</string>
<string name="widget_bookings_name">Pemesanan</string>
<string name="widget_bookings_description">Penerbangan, kereta, hotel, dan meja berikutnya, beserta waktunya.</string>
<string name="widget_flight_name">Penerbangan</string>
<string name="widget_flight_description">Penerbangan berikutnya secara langsung: hitung mundur keberangkatan, pesawat dalam perjalanan, keterlambatan, dan kedatangan.</string>
<string name="widget_todos_name">Tugas</string>
<string name="widget_todos_description">Yang masih tersisa untuk perjalanan dan sejauh mana persiapan barang.</string>
<string name="widget_packing_name">Barang bawaan</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Il programma del giorno come linea del tempo, con il meteo e la prossima tappa.</string>
<string name="widget_bookings_name">Prenotazioni</string>
<string name="widget_bookings_description">I tuoi prossimi voli, treni, hotel e tavoli, e quando sono.</string>
<string name="widget_flight_name">Volo</string>
<string name="widget_flight_description">Il tuo prossimo volo in tempo reale: conto alla rovescia per la partenza, l’aereo in viaggio, ritardo e arrivo.</string>
<string name="widget_todos_name">Da fare</string>
<string name="widget_todos_description">Cosa manca ancora per il viaggio e a che punto è la valigia.</string>
<string name="widget_packing_name">Bagagli</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">תוכנית היום כציר זמן, עם מזג האוויר והעצירה הבאה.</string>
<string name="widget_bookings_name">הזמנות</string>
<string name="widget_bookings_description">הטיסות, הרכבות, המלונות והשולחנות הבאים שלך, ומתי הם.</string>
<string name="widget_flight_name">טיסה</string>
<string name="widget_flight_description">הטיסה הבאה שלך בזמן אמת: ספירה לאחור עד ההמראה, המטוס בדרך, עיכוב והגעה.</string>
<string name="widget_todos_name">משימות</string>
<string name="widget_todos_description">מה עוד פתוח לטיול וכמה התקדמה האריזה.</string>
<string name="widget_packing_name">אריזה</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">今日の予定をタイムラインで、天気と次の予定とともに表示します。</string>
<string name="widget_bookings_name">予約</string>
<string name="widget_bookings_description">次のフライト、列車、ホテル、レストランとその日時。</string>
<string name="widget_flight_name">フライト</string>
<string name="widget_flight_description">次のフライトをライブで:出発までのカウントダウン、飛行中の機体、遅延と到着。</string>
<string name="widget_todos_name">やること</string>
<string name="widget_todos_description">旅行のために残っていることと、荷造りの進み具合。</string>
<string name="widget_packing_name">持ち物</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">오늘 일정을 타임라인으로, 날씨와 다음 장소와 함께 보여 줍니다.</string>
<string name="widget_bookings_name">예약</string>
<string name="widget_bookings_description">다가오는 항공편, 기차, 호텔, 식당과 그 시간.</string>
<string name="widget_flight_name">항공편</string>
<string name="widget_flight_description">다음 항공편을 실시간으로: 출발 카운트다운, 비행 중인 항공기, 지연과 도착.</string>
<string name="widget_todos_name">할 일</string>
<string name="widget_todos_description">여행을 위해 남은 일과 짐 싸기 진행 상황.</string>
<string name="widget_packing_name">짐 싸기</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Het dagplan als tijdlijn, met het weer en de volgende stop.</string>
<string name="widget_bookings_name">Boekingen</string>
<string name="widget_bookings_description">Je volgende vluchten, treinen, hotels en tafels, en wanneer ze zijn.</string>
<string name="widget_flight_name">Vlucht</string>
<string name="widget_flight_description">Je volgende vlucht live: aftellen tot vertrek, het toestel onderweg, vertraging en aankomst.</string>
<string name="widget_todos_name">Taken</string>
<string name="widget_todos_description">Wat er nog openstaat voor de reis en hoe ver het inpakken is.</string>
<string name="widget_packing_name">Bagage</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Plan dnia jako oś czasu, z pogodą i kolejnym przystankiem.</string>
<string name="widget_bookings_name">Rezerwacje</string>
<string name="widget_bookings_description">Twoje najbliższe loty, pociągi, hotele i stoliki oraz ich terminy.</string>
<string name="widget_flight_name">Lot</string>
<string name="widget_flight_description">Twój następny lot na żywo: odliczanie do odlotu, samolot w drodze, opóźnienie i przylot.</string>
<string name="widget_todos_name">Zadania</string>
<string name="widget_todos_description">Co jeszcze zostało do zrobienia przed podróżą i jak idzie pakowanie.</string>
<string name="widget_packing_name">Pakowanie</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">O plano do dia como linha do tempo, com o clima e a próxima parada.</string>
<string name="widget_bookings_name">Reservas</string>
<string name="widget_bookings_description">Seus próximos voos, trens, hotéis e mesas, e quando acontecem.</string>
<string name="widget_flight_name">Voo</string>
<string name="widget_flight_description">Seu próximo voo ao vivo: contagem regressiva para a partida, o avião a caminho, atraso e chegada.</string>
<string name="widget_todos_name">Tarefas</string>
<string name="widget_todos_description">O que ainda falta para a viagem e quanto da mala já está pronto.</string>
<string name="widget_packing_name">Bagagem</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">План дня в виде ленты времени, с погодой и следующей остановкой.</string>
<string name="widget_bookings_name">Бронирования</string>
<string name="widget_bookings_description">Ближайшие рейсы, поезда, отели и столики и когда они.</string>
<string name="widget_flight_name">Рейс</string>
<string name="widget_flight_description">Ваш следующий рейс в реальном времени: отсчёт до вылета, самолёт в пути, задержка и прибытие.</string>
<string name="widget_todos_name">Задачи</string>
<string name="widget_todos_description">Что ещё осталось сделать к поездке и как идут сборы.</string>
<string name="widget_packing_name">Сборы</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Plán dňa ako časová os, s počasím a ďalšou zastávkou.</string>
<string name="widget_bookings_name">Rezervácie</string>
<string name="widget_bookings_description">Tvoje ďalšie lety, vlaky, hotely a stoly a kedy ťa čakajú.</string>
<string name="widget_flight_name">Let</string>
<string name="widget_flight_description">Tvoj ďalší let naživo: odpočet do odletu, lietadlo na ceste, meškanie a prílet.</string>
<string name="widget_todos_name">Úlohy</string>
<string name="widget_todos_description">Čo ešte zostáva na cestu a ako ďaleko je balenie.</string>
<string name="widget_packing_name">Balenie</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Dagens plan som tidslinje, med vädret och nästa stopp.</string>
<string name="widget_bookings_name">Bokningar</string>
<string name="widget_bookings_description">Dina nästa flyg, tåg, hotell och bord, och när de är.</string>
<string name="widget_flight_name">Flyg</string>
<string name="widget_flight_description">Ditt nästa flyg live: nedräkning till avgång, planet på väg, försening och ankomst.</string>
<string name="widget_todos_name">Att göra</string>
<string name="widget_todos_description">Vad som återstår inför resan och hur långt packningen har kommit.</string>
<string name="widget_packing_name">Packning</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">แผนของวันนี้เป็นไทม์ไลน์ พร้อมสภาพอากาศและจุดหมายถัดไป</string>
<string name="widget_bookings_name">การจอง</string>
<string name="widget_bookings_description">เที่ยวบิน รถไฟ โรงแรม และร้านอาหารถัดไปของคุณ และเวลาของแต่ละรายการ</string>
<string name="widget_flight_name">เที่ยวบิน</string>
<string name="widget_flight_description">เที่ยวบินถัดไปแบบสด: นับถอยหลังถึงเวลาออกเดินทาง เครื่องบินระหว่างทาง ความล่าช้า และเวลาถึง</string>
<string name="widget_todos_name">สิ่งที่ต้องทำ</string>
<string name="widget_todos_description">สิ่งที่ยังค้างอยู่สำหรับทริป และความคืบหน้าการจัดกระเป๋า</string>
<string name="widget_packing_name">จัดกระเป๋า</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Günün planı zaman çizelgesi olarak, hava durumu ve sonraki durakla.</string>
<string name="widget_bookings_name">Rezervasyonlar</string>
<string name="widget_bookings_description">Sıradaki uçuşların, trenlerin, otellerin ve masaların, ne zaman oldukları ile.</string>
<string name="widget_flight_name">Uçuş</string>
<string name="widget_flight_description">Bir sonraki uçuşun canlı: kalkışa geri sayım, yoldaki uçak, gecikme ve varış.</string>
<string name="widget_todos_name">Yapılacaklar</string>
<string name="widget_todos_description">Seyahat için hâlâ açık olanlar ve bavulun ne durumda olduğu.</string>
<string name="widget_packing_name">Bavul</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">План дня у вигляді стрічки часу, з погодою і наступною зупинкою.</string>
<string name="widget_bookings_name">Бронювання</string>
<string name="widget_bookings_description">Найближчі рейси, поїзди, готелі й столики та коли вони.</string>
<string name="widget_flight_name">Рейс</string>
<string name="widget_flight_description">Ваш наступний рейс наживо: відлік до вильоту, літак у дорозі, затримка й прибуття.</string>
<string name="widget_todos_name">Завдання</string>
<string name="widget_todos_description">Що ще лишилося зробити до подорожі і як просувається пакування.</string>
<string name="widget_packing_name">Пакування</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Kế hoạch hôm nay dạng dòng thời gian, kèm thời tiết và điểm dừng tiếp theo.</string>
<string name="widget_bookings_name">Đặt chỗ</string>
<string name="widget_bookings_description">Các chuyến bay, tàu, khách sạn và bàn sắp tới của bạn, cùng thời gian.</string>
<string name="widget_flight_name">Chuyến bay</string>
<string name="widget_flight_description">Chuyến bay tiếp theo trực tiếp: đếm ngược giờ khởi hành, máy bay đang bay, độ trễ và giờ đến.</string>
<string name="widget_todos_name">Việc cần làm</string>
<string name="widget_todos_description">Những gì còn lại cho chuyến đi và việc soạn hành lý đã tới đâu.</string>
<string name="widget_packing_name">Hành lý</string>
@@ -8,6 +8,8 @@
<string name="widget_today_description">Today\'s plan as a timeline, with the weather and what is next.</string>
<string name="widget_bookings_name">Bookings</string>
<string name="widget_bookings_description">Your next flights, trains, hotels and tables, and when they are due.</string>
<string name="widget_flight_name">Flight</string>
<string name="widget_flight_description">Your next flight live: departure countdown, the aircraft on its way, delay and arrival.</string>
<string name="widget_todos_name">To-dos</string>
<string name="widget_todos_description">What is still open for the trip, and how far the packing has come.</string>
<string name="widget_packing_name">Packing</string>
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- The flight widget (widget/TrekWidgets.kt). Sizes in cells for Android 12+, dp before.
No previewImage: Glance draws the picker preview from the sample trip (providePreview). -->
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/widget_flight_description"
android:initialLayout="@layout/glance_default_loading_layout"
android:minWidth="110dp"
android:minHeight="110dp"
android:minResizeWidth="110dp"
android:minResizeHeight="110dp"
android:maxResizeWidth="530dp"
android:maxResizeHeight="450dp"
android:targetCellWidth="4"
android:targetCellHeight="2"
android:resizeMode="horizontal|vertical"
android:updatePeriodMillis="1800000"
android:widgetCategory="home_screen"
android:configure="com.liketrek.trek.widget.WidgetConfigActivity"
android:widgetFeatures="reconfigurable|configuration_optional" />
@@ -37,6 +37,7 @@
512499AF65E091B2BBC9A7BB /* UniformTypeIdentifiers.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E45050B942C96E1ACCAB7CE9 /* UniformTypeIdentifiers.framework */; };
5480CCC12F42E9605044AB6B /* ShareHandoff.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56050CCA8DE4BEB4680D9E0B /* ShareHandoff.swift */; };
5A4D344328829E0F0B4D2B94 /* BookingsContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6D2F4930E5F152C8090C4F8 /* BookingsContent.swift */; };
F11E0C0A9B7D4E2A8C3F5A01 /* FlightContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = F11E0C0A9B7D4E2A8C3F5A02 /* FlightContent.swift */; };
5BBE9EE02A47EC67C31F5E21 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = D0A4B2C6C93971E884561CFA /* Localizable.strings */; };
612BB9680DC27BB8BF553060 /* TrekFamily.swift in Sources */ = {isa = PBXBuildFile; fileRef = A030A06726542A2D7F61C54B /* TrekFamily.swift */; };
634F4E63DC7C2A0027F0D118 /* Details.swift in Sources */ = {isa = PBXBuildFile; fileRef = F406A4A31BD875A880A7CA14 /* Details.swift */; };
@@ -305,6 +306,7 @@
E5800E4ECECED54A47CDABAA /* tr */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = tr; path = tr.lproj/Localizable.strings; sourceTree = "<group>"; };
E6831E849332626BE8D54CEF /* ShareView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ShareView.swift; sourceTree = "<group>"; };
E6D2F4930E5F152C8090C4F8 /* BookingsContent.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = BookingsContent.swift; sourceTree = "<group>"; };
F11E0C0A9B7D4E2A8C3F5A02 /* FlightContent.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FlightContent.swift; sourceTree = "<group>"; };
EAFBDD97043B34E4B64FDA86 /* pt-BR */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.strings; name = "pt-BR"; path = "pt-BR.lproj/Localizable.strings"; sourceTree = "<group>"; };
EC8D1292C9FC6430C059960A /* nl */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.strings; name = nl; path = nl.lproj/Localizable.strings; sourceTree = "<group>"; };
ECC80E1314B31ED2D2347411 /* ar */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = ar; path = ar.lproj/Localizable.strings; sourceTree = "<group>"; };
@@ -538,6 +540,7 @@
DE6873D246AC6B8E2CB6C8B4 /* TripContent.swift */,
24B175DE91E1E6E850DB0285 /* TodayContent.swift */,
E6D2F4930E5F152C8090C4F8 /* BookingsContent.swift */,
F11E0C0A9B7D4E2A8C3F5A02 /* FlightContent.swift */,
AEF7DCAA1AEE67F1291668D1 /* TodosContent.swift */,
);
name = TREKWidgets;
@@ -849,6 +852,7 @@
8FC5873BE6A8CB2AFB31A46A /* TripContent.swift in Sources */,
9A175689CFCC630BE9BB9EE1 /* TodayContent.swift in Sources */,
5A4D344328829E0F0B4D2B94 /* BookingsContent.swift in Sources */,
F11E0C0A9B7D4E2A8C3F5A01 /* FlightContent.swift in Sources */,
F1E29B18C5B1E75A5BC01B57 /* TodosContent.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
+15 -1
View File
@@ -174,7 +174,8 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
nextName: nextName,
nextTime: call.getString("nextTime"),
done: call.getInt("done") ?? 0,
total: call.getInt("total") ?? 0
total: call.getInt("total") ?? 0,
flight: TrekShellPlugin.activityFlight(call.getObject("flight"))
)
// Stale at the end of the day, so a forgotten one fades out on its own.
let stale = Calendar.current.startOfDay(for: Date().addingTimeInterval(86_400))
@@ -194,6 +195,19 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
call.resolve(["running": false])
}
/// The day's flight the UI sent along (native/widgets.ts tripDayState), when complete.
@available(iOS 16.1, *)
static func activityFlight(_ raw: JSObject?) -> TripDayAttributes.Flight? {
guard let raw, let number = raw["number"] as? String, let from = raw["from"] as? String, let to = raw["to"] as? String,
let dep = (raw["dep"] as? NSNumber)?.doubleValue, let arr = (raw["arr"] as? NSNumber)?.doubleValue, arr > dep,
let depTime = raw["depTime"] as? String, let arrTime = raw["arrTime"] as? String else { return nil }
return TripDayAttributes.Flight(
number: number, from: from, to: to, dep: dep, arr: arr, depTime: depTime, arrTime: arrTime,
delay: (raw["delay"] as? NSNumber)?.intValue,
airborne: (raw["airborne"] as? Bool) ?? false
)
}
@objc func endTripDay(_ call: CAPPluginCall) {
#if canImport(ActivityKit)
if #available(iOS 16.2, *) {
@@ -0,0 +1,266 @@
import SwiftUI
/// The trip's next flight, or the one in the air: both airports large, the
/// route as an arc with the aircraft riding it, the moment in words with a
/// countdown the system keeps running, and the delay. Between two snapshots
/// the widget moves on with the clock: it takes off at the observed (or
/// planned) time, flies along the arc and lands at the expected (or planned)
/// arrival.
struct FlightContent: View {
let snapshot: WidgetSnapshot?
let family: TrekFamily
let now: Date
@Environment(\.colorScheme) private var scheme
private let accent = Trek.booking("flight").color
var body: some View {
if let flight = snapshot?.flight, let labels = snapshot?.labels {
let moment = FlightMoment(flight, now: now)
switch family {
case .circular: circular(flight, moment)
case .rectangular: rectangular(flight, moment, labels)
case .inline: inline(flight, moment, labels)
case .small: small(flight, moment, labels)
case .medium: medium(flight, moment, labels)
default: large(flight, moment, labels)
}
} else {
empty(snapshot?.labels)
}
}
// MARK: Small: the moment above, the route below
private func small(_ f: WidgetSnapshot.Flight, _ m: FlightMoment, _ labels: WidgetSnapshot.Labels) -> some View {
VStack(alignment: .leading, spacing: 0) {
HStack(spacing: 6) {
Image(systemName: "airplane").font(.system(size: 12, weight: .bold)).foregroundStyle(accent)
Text(f.number).font(.system(size: 12, weight: .heavy)).foregroundStyle(Trek.ink(scheme)).lineLimit(1)
Spacer(minLength: 0)
delayChip(f, labels, compact: true)
}
Spacer(minLength: 0)
momentText(f, m, labels)
.font(.system(size: 13, weight: .bold))
.foregroundStyle(m.stage == .airborne ? accent : Trek.ink(scheme))
.lineLimit(2)
.minimumScaleFactor(0.85)
Spacer(minLength: 6)
HStack(alignment: .firstTextBaseline) {
Text(f.from).font(Trek.number(24, .heavy)).foregroundStyle(Trek.ink(scheme))
Spacer(minLength: 2)
Text(f.to).font(Trek.number(24, .heavy)).foregroundStyle(Trek.ink(scheme))
}
RouteArc(progress: m.progress, color: accent).flipsForRightToLeftLayoutDirection(true).frame(height: 20).padding(.vertical, 3)
HStack {
Text(f.depTime).font(Trek.number(12, .bold)).foregroundStyle(Trek.muted(scheme))
Spacer(minLength: 2)
Text(f.arrTimeExpected ?? f.arrTime).font(Trek.number(12, .bold)).foregroundStyle(Trek.muted(scheme))
}
}
}
// MARK: Medium: a boarding pass
private func medium(_ f: WidgetSnapshot.Flight, _ m: FlightMoment, _ labels: WidgetSnapshot.Labels) -> some View {
VStack(alignment: .leading, spacing: 0) {
HStack(spacing: 7) {
Text(labels.flight ?? "").trekEyebrow(scheme)
Text(f.number).font(.system(size: 11, weight: .heavy)).foregroundStyle(accent)
Spacer(minLength: 4)
delayChip(f, labels, compact: false)
}
Spacer(minLength: 4)
HStack(alignment: .center, spacing: 10) {
airport(f.from, f.fromCity, time: f.depTime, planned: nil, align: .leading)
VStack(spacing: 4) {
RouteArc(progress: m.progress, color: accent).flipsForRightToLeftLayoutDirection(true).frame(height: 30)
progressBar(m)
}
.frame(maxWidth: .infinity)
airport(f.to, f.toCity, time: f.arrTimeExpected ?? f.arrTime, planned: f.arrTimeExpected.flatMap { $0 == f.arrTime ? nil : f.arrTime }, align: .trailing)
}
Spacer(minLength: 6)
momentText(f, m, labels)
.font(.system(size: 13, weight: .bold))
.foregroundStyle(m.stage == .airborne ? accent : Trek.ink(scheme))
.lineLimit(1)
.minimumScaleFactor(0.85)
}
}
// MARK: Large and extra large: the pass with the details under it
private func large(_ f: WidgetSnapshot.Flight, _ m: FlightMoment, _ labels: WidgetSnapshot.Labels) -> some View {
VStack(alignment: .leading, spacing: 12) {
medium(f, m, labels).frame(maxHeight: 150)
Rectangle().fill(Trek.track(scheme)).frame(height: 0.8)
LazyVGrid(columns: [GridItem(.flexible(), spacing: 8), GridItem(.flexible(), spacing: 8)], spacing: 8) {
if let aircraft = f.aircraft { detail(systemImage: "airplane.circle", value: aircraft) }
detail(systemImage: "clock", value: "\(f.depTime) → \(f.arrTimeExpected ?? f.arrTime)")
if let fromCity = f.fromCity { detail(systemImage: "airplane.departure", value: fromCity) }
if let toCity = f.toCity { detail(systemImage: "airplane.arrival", value: toCity) }
}
Spacer(minLength: 0)
}
}
// MARK: Lock screen
private func circular(_ f: WidgetSnapshot.Flight, _ m: FlightMoment) -> some View {
ProgressRing(value: m.progress, lineWidth: 5, colors: [.white], trackColor: Color.white.opacity(0.25)) {
Image(systemName: m.stage == .landed ? "airplane.arrival" : m.stage == .airborne ? "airplane" : "airplane.departure")
.font(.system(size: 17, weight: .bold))
}
.padding(4)
}
private func rectangular(_ f: WidgetSnapshot.Flight, _ m: FlightMoment, _ labels: WidgetSnapshot.Labels) -> some View {
VStack(alignment: .leading, spacing: 2) {
HStack(spacing: 4) {
Image(systemName: "airplane").font(.system(size: 11, weight: .bold))
Text("\(f.number) \(f.from) → \(f.to)").font(.system(size: 12, weight: .heavy)).lineLimit(1)
}
momentText(f, m, labels).font(.system(size: 13, weight: .semibold)).lineLimit(1)
if m.stage == .airborne {
ProgressView(timerInterval: m.start...m.end, countsDown: false) { EmptyView() } currentValueLabel: { EmptyView() }
.progressViewStyle(.linear)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
}
private func inline(_ f: WidgetSnapshot.Flight, _ m: FlightMoment, _ labels: WidgetSnapshot.Labels) -> some View {
Text("\(Image(systemName: "airplane")) \(f.number) ") + momentText(f, m, labels)
}
// MARK: Parts
private func airport(_ code: String, _ city: String?, time: String, planned: String?, align: HorizontalAlignment) -> some View {
VStack(alignment: align, spacing: 1) {
Text(code).font(Trek.number(28, .heavy)).foregroundStyle(Trek.ink(scheme))
if let city { Text(city).font(.system(size: 10.5, weight: .semibold)).foregroundStyle(Trek.faint(scheme)).lineLimit(1) }
if let planned { Text(planned).font(Trek.number(10.5, .bold)).strikethrough().foregroundStyle(Trek.faint(scheme)) }
Text(time).font(Trek.number(14, .heavy)).foregroundStyle(Trek.ink(scheme))
}
.frame(maxWidth: 96, alignment: align == .leading ? .leading : .trailing)
}
@ViewBuilder
private func progressBar(_ m: FlightMoment) -> some View {
if m.stage == .airborne {
// The system runs this bar on its own, so it fills between two snapshots too.
ProgressView(timerInterval: m.start...m.end, countsDown: false) { EmptyView() } currentValueLabel: { EmptyView() }
.progressViewStyle(.linear)
.tint(accent)
} else {
Capsule().fill(m.stage == .landed ? accent : Trek.track(scheme)).frame(height: 4)
}
}
private func detail(systemImage: String, value: String) -> some View {
HStack(spacing: 6) {
Image(systemName: systemImage).font(.system(size: 12, weight: .semibold)).foregroundStyle(accent)
Text(value).font(.system(size: 12, weight: .semibold)).foregroundStyle(Trek.muted(scheme)).lineLimit(1)
Spacer(minLength: 0)
}
.padding(.horizontal, 10)
.padding(.vertical, 8)
.background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(Trek.card(scheme)))
}
/// "Departs in 2 hr, 10 min", "Lands in 1 hr", "Landed": the countdowns are the system's own running text.
private func momentText(_ f: WidgetSnapshot.Flight, _ m: FlightMoment, _ labels: WidgetSnapshot.Labels) -> Text {
switch m.stage {
case .upcoming:
return Countdown.text(labels.flightDeparts ?? "{time}", until: m.start)
case .ready:
return Text(labels.flightReady ?? "")
case .airborne:
// "In the air" is what the blue line and the moving aircraft say; the words count down to landing.
return Countdown.text(labels.flightLands ?? "{time}", until: m.end)
case .landed:
return Text(labels.flightLanded ?? "")
}
}
@ViewBuilder
private func delayChip(_ f: WidgetSnapshot.Flight, _ labels: WidgetSnapshot.Labels, compact: Bool) -> some View {
if let delay = f.delay {
let late = delay > 5
let early = delay < -5
let color = late ? (delay >= 30 ? Trek.danger : Trek.pending) : Trek.confirmed
let text = late
? (labels.flightLate ?? "+{m}").replacingOccurrences(of: "{m}", with: "\(delay)")
: early ? (labels.flightEarly ?? "{m}").replacingOccurrences(of: "{m}", with: "\(-delay)") : (labels.flightOnTime ?? "")
if !(compact && !late) {
Text(text)
.font(.system(size: 10.5, weight: .heavy))
.foregroundStyle(color)
.padding(.horizontal, 7)
.padding(.vertical, 3)
.background(Capsule().fill(color.opacity(scheme == .dark ? 0.22 : 0.14)))
.lineLimit(1)
}
}
}
private func empty(_ labels: WidgetSnapshot.Labels?) -> some View {
VStack(alignment: .leading, spacing: 6) {
Text(labels?.flight ?? "").trekEyebrow(scheme)
Spacer(minLength: 0)
Image(systemName: "airplane").font(.system(size: 30, weight: .bold)).foregroundStyle(accent.opacity(0.35))
Text(labels?.noFlight ?? labels?.noBookings ?? "").font(.system(size: 13, weight: .semibold)).foregroundStyle(Trek.muted(scheme)).lineLimit(2)
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
}
}
/// Where a flight stands at a given moment, from the snapshot's times. What the
/// feed saw wins: a flight still at the gate past its planned departure is not
/// flown along the arc, and a flight is only landed once confirmed. Only a
/// flight the feed never heard of moves on by its schedule alone.
struct FlightMoment {
enum Stage { case upcoming, ready, airborne, landed }
let stage: Stage
/// 0 at the gate, 1 at the destination.
let progress: Double
/// Take-off and touchdown the moment is measured between: observed or expected where known, planned otherwise.
let start: Date
let end: Date
init(_ f: WidgetSnapshot.Flight, now: Date) {
let start = Date(timeIntervalSince1970: f.depActual ?? f.depExpected ?? f.dep)
let end = max(Date(timeIntervalSince1970: f.arrExpected ?? f.arr), start.addingTimeInterval(60))
self.start = start
self.end = end
let heard = f.seen != nil
let flying = f.airborne == true || f.depActual != nil || (!heard && now >= start)
// A flight the feed lost stops counting two hours after its arrival.
if f.landed == true || (!heard && now >= end) || now >= end.addingTimeInterval(7200) {
stage = .landed
progress = 1
} else if flying {
stage = .airborne
// Unconfirmed, it never quite arrives on the arc.
progress = min(0.98, max(0, now.timeIntervalSince(start) / end.timeIntervalSince(start)))
} else if now >= start {
stage = .ready
progress = 0
} else {
stage = .upcoming
progress = 0
}
}
}
/// A sentence with "{time}" in it, the placeholder replaced by a countdown the system keeps running.
enum Countdown {
static func text(_ sentence: String, until date: Date) -> Text {
let parts = sentence.components(separatedBy: "{time}")
guard parts.count == 2 else { return Text(sentence) }
return Text(parts[0]) + Text(date, style: .relative) + Text(parts[1])
}
}
@@ -158,6 +158,30 @@ private struct BookingsFamilyView: View {
var body: some View { BookingsContent(snapshot: entry.snapshot, family: TrekFamily(family), now: entry.date) }
}
// MARK: - Flight
struct FlightWidget: Widget {
var body: some WidgetConfiguration {
AppIntentConfiguration(kind: "TripFlight", intent: SelectTripIntent.self, provider: TrekTripProvider()) { entry in
TrekContainer(link: entry.snapshot?.flight.flatMap { WidgetSnapshot.link($0.path) }) {
FlightFamilyView(entry: entry)
} background: {
TrekPaper()
}
}
.configurationDisplayName("widget.flight.name")
.description("widget.flight.description")
.supportedFamilies([.systemSmall, .systemMedium, .systemLarge, .accessoryCircular, .accessoryRectangular, .accessoryInline])
}
}
private struct FlightFamilyView: View {
@Environment(\.widgetFamily) private var family
let entry: TrekEntry
var body: some View { FlightContent(snapshot: entry.snapshot, family: TrekFamily(family), now: entry.date) }
}
// MARK: - To-dos
struct TodosWidget: Widget {
@@ -1,7 +1,7 @@
import SwiftUI
import WidgetKit
/// The TREK widgets: the trip, today's plan, the bookings ahead, the to-dos,
/// The TREK widgets: the trip, today's plan, the bookings ahead, the next flight, the to-dos,
/// the packing list, the Atlas and the travel group on the home and lock
/// screen, and the travel day as a Live Activity.
@main
@@ -10,6 +10,7 @@ struct TREKWidgetsBundle: WidgetBundle {
NextTripWidget()
TodayWidget()
BookingsWidget()
FlightWidget()
TodosWidget()
PackingWidget()
AtlasWidget()
@@ -115,6 +115,29 @@ extension WidgetSnapshot {
poll: "Poll", votes: "votes", noMessages: "No messages yet", departure: "Departure"
)
)
// In the air on a running trip, two days ahead before one.
let departure = running ? now.addingTimeInterval(-4 * 3600) : now.addingTimeInterval(2 * 86_400 + 5 * 3600)
snapshot.flight = Flight(
number: "LH 716", from: "FRA", to: "HND", fromCity: "Frankfurt", toCity: "Tokyo Haneda",
dep: departure.timeIntervalSince1970, arr: departure.addingTimeInterval(12 * 3600 + 25 * 60).timeIntervalSince1970,
depActual: running ? departure.addingTimeInterval(18 * 60).timeIntervalSince1970 : nil,
depExpected: nil, airborne: running ? true : nil,
arrExpected: running ? departure.addingTimeInterval(12 * 3600 + 41 * 60).timeIntervalSince1970 : nil,
landed: nil, depTime: "13:05", arrTime: "08:30", arrTimeExpected: running ? "08:46" : nil,
delay: running ? 16 : nil, aircraft: running ? "A359 D-AIXA" : nil, seen: running ? now.timeIntervalSince1970 : nil,
path: "/trips/1?booking=1"
)
snapshot.labels.flight = "Flight"
snapshot.labels.flightDeparts = "Departs in {time}"
snapshot.labels.flightInAir = "In the air"
snapshot.labels.flightLands = "Lands in {time}"
snapshot.labels.flightLanded = "Landed"
snapshot.labels.flightOnTime = "On time"
snapshot.labels.flightLate = "+{m} min"
snapshot.labels.flightEarly = "{m} min early"
snapshot.labels.flightEstimated = "estimated"
snapshot.labels.flightReady = "Ready for departure"
snapshot.labels.noFlight = "No flight ahead"
snapshot.packing?.bags = [
.init(name: "Suitcase", color: "#4A7DDB", grams: 14_200, limit: 23_000, packed: 15, total: 19),
.init(name: "Daypack", color: "#2FA37A", grams: 4_100, limit: 8_000, packed: 8, total: 12),
@@ -174,6 +197,7 @@ extension WidgetSnapshot {
snapshot.packing = nil
snapshot.atlas = Atlas(count: 0, codes: [], recent: [], continents: [])
snapshot.collab = nil
snapshot.flight = nil
return snapshot
}
}
@@ -16,6 +16,27 @@ struct TripDayAttributes: ActivityAttributes {
/// Stops behind, out of the day's stops.
var done: Int
var total: Int
/// The day's flight while it is near or in the air, so the activity turns into
/// a boarding pass. Optional: a state written by an older app decodes without it.
var flight: Flight?
}
/// A flight the activity follows on its own between two updates: the system
/// runs the bar and the countdown from the two times.
struct Flight: Codable, Hashable {
var number: String
var from: String
var to: String
/// Take-off and touchdown, epoch seconds: observed or expected where known.
var dep: Double
var arr: Double
/// The clock at either airport, formatted by the app.
var depTime: String
var arrTime: String
/// Minutes late, for the colour of the arrival time.
var delay: Int?
/// In the air when the app last looked: the countdown runs to touchdown.
var airborne: Bool?
}
var tripTitle: String
@@ -7,11 +7,17 @@ import WidgetKit
struct TripDayLiveActivity: Widget {
var body: some WidgetConfiguration {
ActivityConfiguration(for: TripDayAttributes.self) { context in
TripDayBanner(
tripTitle: context.attributes.tripTitle, dayLabel: context.state.dayLabel,
nextName: context.state.nextName, nextTime: context.state.nextTime,
done: context.state.done, total: context.state.total
)
Group {
if let flight = context.state.flight {
FlightBanner(flight: flight, tripTitle: context.attributes.tripTitle)
} else {
TripDayBanner(
tripTitle: context.attributes.tripTitle, dayLabel: context.state.dayLabel,
nextName: context.state.nextName, nextTime: context.state.nextTime,
done: context.state.done, total: context.state.total
)
}
}
.activityBackgroundTint(Color(hex: 0x0C0C0F).opacity(0.92))
.activitySystemActionForegroundColor(.white)
.widgetURL(WidgetSnapshot.link(context.attributes.path))
@@ -33,17 +39,32 @@ struct TripDayLiveActivity: Widget {
}
}
DynamicIslandExpandedRegion(.bottom) {
VStack(alignment: .leading, spacing: 8) {
Text(state.nextName).font(.system(size: 17, weight: .heavy)).lineLimit(1)
DayStopProgress(done: state.done, total: state.total)
if let flight = state.flight {
FlightPass(flight: flight).padding(.horizontal, 4)
} else {
VStack(alignment: .leading, spacing: 8) {
Text(state.nextName).font(.system(size: 17, weight: .heavy)).lineLimit(1)
DayStopProgress(done: state.done, total: state.total)
}
.padding(.horizontal, 4)
}
.padding(.horizontal, 4)
}
} compactLeading: {
Image(systemName: "mappin.circle.fill").foregroundStyle(Trek.confirmed)
if let flight = state.flight {
HStack(spacing: 3) {
Image(systemName: "airplane").foregroundStyle(Trek.info)
Text(flight.to).font(Trek.number(13, .heavy))
}
} else {
Image(systemName: "mappin.circle.fill").foregroundStyle(Trek.confirmed)
}
} compactTrailing: {
Text(state.nextTime ?? "\(state.done)/\(state.total)")
.font(Trek.number(13, .heavy))
if let flight = state.flight {
FlightCountdown(flight: flight).font(Trek.number(13, .heavy)).frame(maxWidth: 64)
} else {
Text(state.nextTime ?? "\(state.done)/\(state.total)")
.font(Trek.number(13, .heavy))
}
} minimal: {
ZStack {
Circle().stroke(Color.white.opacity(0.25), lineWidth: 2.5)
@@ -59,3 +80,76 @@ struct TripDayLiveActivity: Widget {
}
}
}
/// The day's flight on the lock screen: both airports, the bar the system runs
/// from take-off to touchdown, and a countdown to whichever comes next.
struct FlightBanner: View {
let flight: TripDayAttributes.Flight
let tripTitle: String
var body: some View {
VStack(alignment: .leading, spacing: 10) {
HStack(spacing: 6) {
Image(systemName: "airplane").font(.system(size: 12, weight: .bold)).foregroundStyle(Trek.info)
Text(flight.number).font(.system(size: 12, weight: .heavy)).foregroundStyle(.white)
Text(tripTitle)
.font(.system(size: 11, weight: .bold))
.tracking(0.5)
.textCase(.uppercase)
.foregroundStyle(.white.opacity(0.55))
.lineLimit(1)
Spacer(minLength: 4)
FlightCountdown(flight: flight).font(Trek.number(15, .heavy)).foregroundStyle(.white)
}
FlightPass(flight: flight)
}
.padding(16)
}
}
/// The two airports with their times and the bar between them.
struct FlightPass: View {
let flight: TripDayAttributes.Flight
var body: some View {
let start = Date(timeIntervalSince1970: flight.dep)
let end = Date(timeIntervalSince1970: flight.arr)
let late = (flight.delay ?? 0) > 5
HStack(alignment: .center, spacing: 12) {
VStack(alignment: .leading, spacing: 0) {
Text(flight.from).font(Trek.number(26, .heavy)).foregroundStyle(.white)
Text(flight.depTime).font(Trek.number(13, .bold)).foregroundStyle(.white.opacity(0.7))
}
VStack(spacing: 4) {
Image(systemName: "airplane").font(.system(size: 13, weight: .bold)).foregroundStyle(Trek.info)
ProgressView(timerInterval: start...end, countsDown: false) { EmptyView() } currentValueLabel: { EmptyView() }
.progressViewStyle(.linear)
.tint(Trek.info)
}
.frame(maxWidth: .infinity)
VStack(alignment: .trailing, spacing: 0) {
Text(flight.to).font(Trek.number(26, .heavy)).foregroundStyle(.white)
Text(flight.arrTime).font(Trek.number(13, .bold)).foregroundStyle(late ? Trek.pending : .white.opacity(0.7))
}
}
}
}
/// A running countdown, in the system's own format: to touchdown once the app saw
/// the aircraft in the air, to take-off before. The system runs it between two
/// updates; the stage changes with the app's next update after take-off.
struct FlightCountdown: View {
let flight: TripDayAttributes.Flight
var body: some View {
let start = Date(timeIntervalSince1970: flight.dep)
let end = Date(timeIntervalSince1970: flight.arr)
let flying = flight.airborne == true
let target = flying ? end : start
HStack(spacing: 3) {
Image(systemName: flying ? "airplane.arrival" : "airplane.departure")
Text(timerInterval: min(Date(), target)...target, countsDown: true)
.multilineTextAlignment(.trailing)
}
}
}
@@ -160,6 +160,38 @@ struct WidgetSnapshot: Codable {
}
}
/// The trip's next flight or the one in the air, for the flight widget.
/// Times are epoch seconds, so the widget moves its countdown and its
/// aircraft on with the clock between two snapshots; the clock times at
/// either airport come formatted, the widget has no zone data.
struct Flight: Codable {
var number: String
var from: String
var to: String
var fromCity: String?
var toCity: String?
var dep: Double
var arr: Double
/// Observed take-off.
var depActual: Double?
/// Before take-off: the planned departure plus the delay seen so far.
var depExpected: Double?
/// The feed saw the aircraft in the air when the app last looked.
var airborne: Bool?
/// Touchdown once landed, else the estimate while in the air.
var arrExpected: Double?
var landed: Bool?
var depTime: String
var arrTime: String
var arrTimeExpected: String?
/// Minutes late against the schedule, negative when early.
var delay: Int?
var aircraft: String?
/// When the feed last heard the aircraft.
var seen: Double?
var path: String
}
struct Labels: Codable {
var nextTrip: String
var today: String
@@ -193,6 +225,22 @@ struct WidgetSnapshot: Codable {
var votes: String?
var noMessages: String?
var departure: String?
var flight: String?
/// Contains "{time}", where the widget puts its running countdown.
var flightDeparts: String?
var flightInAir: String?
/// Contains "{time}".
var flightLands: String?
var flightLanded: String?
var flightOnTime: String?
/// Contains "{m}".
var flightLate: String?
/// Contains "{m}".
var flightEarly: String?
var flightEstimated: String?
/// Past the departure time with the aircraft not yet in the air.
var flightReady: String?
var noFlight: String?
}
var trip: Trip?
@@ -203,6 +251,7 @@ struct WidgetSnapshot: Codable {
var packing: Packing?
var atlas: Atlas?
var collab: Collab?
var flight: Flight?
var labels: Labels
/// The dashboard's snapshot.
@@ -5,6 +5,8 @@
"widget.today.description" = "خطة اليوم كخط زمني، مع الطقس والمحطة التالية.";
"widget.bookings.name" = "الحجوزات";
"widget.bookings.description" = "رحلاتك وقطاراتك وفنادقك وحجوزات المطاعم القادمة ومواعيدها.";
"widget.flight.name" = "الرحلة";
"widget.flight.description" = "رحلتك القادمة مباشرة: عد تنازلي للإقلاع، والطائرة في طريقها، والتأخير والوصول.";
"widget.todos.name" = "المهام";
"widget.todos.description" = "ما تبقى للرحلة، ومدى تقدم تجهيز الأمتعة.";
"widget.packing.name" = "قائمة الأمتعة";
@@ -5,6 +5,8 @@
"widget.today.description" = "Günün planı zaman xətti kimi, hava və növbəti dayanacaqla.";
"widget.bookings.name" = "Bronlar";
"widget.bookings.description" = "Növbəti uçuşlar, qatarlar, otellər və restoranlar, nə vaxt olduqları ilə.";
"widget.flight.name" = "Uçuş";
"widget.flight.description" = "Növbəti uçuşun canlı: uçuşa qədər geri sayım, yolda olan təyyarə, gecikmə və gəliş.";
"widget.todos.name" = "Tapşırıqlar";
"widget.todos.description" = "Səyahət üçün hələ nəyin qaldığı və yığışmağın nə yerdə olduğu.";
"widget.packing.name" = "Yük siyahısı";
@@ -5,6 +5,8 @@
"widget.today.description" = "El pla del dia com a línia de temps, amb el temps i la propera parada.";
"widget.bookings.name" = "Reserves";
"widget.bookings.description" = "Els teus propers vols, trens, hotels i taules, i quan toquen.";
"widget.flight.name" = "Vol";
"widget.flight.description" = "El teu proper vol en directe: compte enrere de la sortida, l’avió en camí, retard i arribada.";
"widget.todos.name" = "Tasques";
"widget.todos.description" = "El que encara queda per al viatge i com va l'equipatge.";
"widget.packing.name" = "Equipatge";
@@ -5,6 +5,8 @@
"widget.today.description" = "Plán dne jako časová osa, s počasím a další zastávkou.";
"widget.bookings.name" = "Rezervace";
"widget.bookings.description" = "Tvoje další lety, vlaky, hotely a stoly, a kdy tě čekají.";
"widget.flight.name" = "Let";
"widget.flight.description" = "Tvůj další let živě: odpočet do odletu, letadlo na cestě, zpoždění a přílet.";
"widget.todos.name" = "Úkoly";
"widget.todos.description" = "Co ještě zbývá k cestě a jak daleko je balení.";
"widget.packing.name" = "Balení";
@@ -5,6 +5,8 @@
"widget.today.description" = "Der Tagesplan als Zeitleiste, mit dem Wetter und dem nächsten Stopp.";
"widget.bookings.name" = "Buchungen";
"widget.bookings.description" = "Deine nächsten Flüge, Züge, Hotels und Tische, und wann sie anstehen.";
"widget.flight.name" = "Flug";
"widget.flight.description" = "Dein nächster Flug live: Countdown bis zum Abflug, die Maschine unterwegs, Verspätung und Ankunft.";
"widget.todos.name" = "To-dos";
"widget.todos.description" = "Was für die Reise noch offen ist und wie weit das Packen ist.";
"widget.packing.name" = "Packliste";
@@ -5,6 +5,8 @@
"widget.today.description" = "Το πρόγραμμα της ημέρας ως χρονολόγιο, με τον καιρό και την επόμενη στάση.";
"widget.bookings.name" = "Κρατήσεις";
"widget.bookings.description" = "Οι επόμενες πτήσεις, τα τρένα, τα ξενοδοχεία και τα τραπέζια σου, και πότε είναι.";
"widget.flight.name" = "Πτήση";
"widget.flight.description" = "Η επόμενη πτήση σου ζωντανά: αντίστροφη μέτρηση για την αναχώρηση, το αεροσκάφος καθ’ οδόν, καθυστέρηση και άφιξη.";
"widget.todos.name" = "Εκκρεμότητες";
"widget.todos.description" = "Τι μένει ακόμα για το ταξίδι και πόσο έχει προχωρήσει το πακετάρισμα.";
"widget.packing.name" = "Αποσκευές";
@@ -5,6 +5,8 @@
"widget.today.description" = "Today's plan as a timeline, with the weather and what is next.";
"widget.bookings.name" = "Bookings";
"widget.bookings.description" = "Your next flights, trains, hotels and tables, and when they are due.";
"widget.flight.name" = "Flight";
"widget.flight.description" = "Your next flight live: departure countdown, the aircraft on its way, delay and arrival.";
"widget.todos.name" = "To-dos";
"widget.todos.description" = "What is still open for the trip, and how far the packing has come.";
"widget.packing.name" = "Packing";
@@ -5,6 +5,8 @@
"widget.today.description" = "El plan del día como línea de tiempo, con el tiempo y la próxima parada.";
"widget.bookings.name" = "Reservas";
"widget.bookings.description" = "Tus próximos vuelos, trenes, hoteles y mesas, y cuándo tocan.";
"widget.flight.name" = "Vuelo";
"widget.flight.description" = "Tu próximo vuelo en directo: cuenta atrás de la salida, el avión en camino, retraso y llegada.";
"widget.todos.name" = "Tareas";
"widget.todos.description" = "Lo que aún queda para el viaje y cómo va la maleta.";
"widget.packing.name" = "Equipaje";
@@ -5,6 +5,8 @@
"widget.today.description" = "Päeva plaan ajajoonena, koos ilma ja järgmise peatusega.";
"widget.bookings.name" = "Broneeringud";
"widget.bookings.description" = "Sinu järgmised lennud, rongid, hotellid ja lauad ning millal need on.";
"widget.flight.name" = "Lend";
"widget.flight.description" = "Sinu järgmine lend otse: loendus väljumiseni, lennuk teel, hilinemine ja saabumine.";
"widget.todos.name" = "Ülesanded";
"widget.todos.description" = "Mis reisi jaoks veel tegemata on ja kui kaugel pakkimine on.";
"widget.packing.name" = "Pakkimine";
@@ -5,6 +5,8 @@
"widget.today.description" = "Le programme du jour en frise, avec la météo et la prochaine étape.";
"widget.bookings.name" = "Réservations";
"widget.bookings.description" = "Vos prochains vols, trains, hôtels et tables, et quand ils arrivent.";
"widget.flight.name" = "Vol";
"widget.flight.description" = "Votre prochain vol en direct : compte à rebours du départ, l’avion en route, retard et arrivée.";
"widget.todos.name" = "À faire";
"widget.todos.description" = "Ce qui reste à faire pour le voyage et où en sont les bagages.";
"widget.packing.name" = "Bagages";
@@ -5,6 +5,8 @@
"widget.today.description" = "תוכנית היום כציר זמן, עם מזג האוויר והעצירה הבאה.";
"widget.bookings.name" = "הזמנות";
"widget.bookings.description" = "הטיסות, הרכבות, המלונות והשולחנות הבאים שלך, ומתי הם.";
"widget.flight.name" = "טיסה";
"widget.flight.description" = "הטיסה הבאה שלך בזמן אמת: ספירה לאחור עד ההמראה, המטוס בדרך, עיכוב והגעה.";
"widget.todos.name" = "משימות";
"widget.todos.description" = "מה עוד פתוח לטיול וכמה התקדמה האריזה.";
"widget.packing.name" = "אריזה";
@@ -5,6 +5,8 @@
"widget.today.description" = "A nap terve idővonalon, az időjárással és a következő megállóval.";
"widget.bookings.name" = "Foglalások";
"widget.bookings.description" = "A következő járataid, vonataid, szállásaid és asztalfoglalásaid, és hogy mikor esedékesek.";
"widget.flight.name" = "Járat";
"widget.flight.description" = "A következő járatod élőben: visszaszámlálás az indulásig, a gép útközben, késés és érkezés.";
"widget.todos.name" = "Teendők";
"widget.todos.description" = "Ami még hátravan az utazáshoz, és hol tart a csomagolás.";
"widget.packing.name" = "Csomagolás";
@@ -5,6 +5,8 @@
"widget.today.description" = "Rencana hari ini sebagai linimasa, dengan cuaca dan perhentian berikutnya.";
"widget.bookings.name" = "Pemesanan";
"widget.bookings.description" = "Penerbangan, kereta, hotel, dan meja berikutnya, beserta waktunya.";
"widget.flight.name" = "Penerbangan";
"widget.flight.description" = "Penerbangan berikutnya secara langsung: hitung mundur keberangkatan, pesawat dalam perjalanan, keterlambatan, dan kedatangan.";
"widget.todos.name" = "Tugas";
"widget.todos.description" = "Yang masih tersisa untuk perjalanan dan sejauh mana persiapan barang.";
"widget.packing.name" = "Barang bawaan";
@@ -5,6 +5,8 @@
"widget.today.description" = "Il programma del giorno come linea del tempo, con il meteo e la prossima tappa.";
"widget.bookings.name" = "Prenotazioni";
"widget.bookings.description" = "I tuoi prossimi voli, treni, hotel e tavoli, e quando sono.";
"widget.flight.name" = "Volo";
"widget.flight.description" = "Il tuo prossimo volo in tempo reale: conto alla rovescia per la partenza, l’aereo in viaggio, ritardo e arrivo.";
"widget.todos.name" = "Da fare";
"widget.todos.description" = "Cosa manca ancora per il viaggio e a che punto è la valigia.";
"widget.packing.name" = "Bagagli";
@@ -5,6 +5,8 @@
"widget.today.description" = "今日の予定をタイムラインで、天気と次の予定とともに表示します。";
"widget.bookings.name" = "予約";
"widget.bookings.description" = "次のフライト、列車、ホテル、レストランとその日時。";
"widget.flight.name" = "フライト";
"widget.flight.description" = "次のフライトをライブで:出発までのカウントダウン、飛行中の機体、遅延と到着。";
"widget.todos.name" = "やること";
"widget.todos.description" = "旅行のために残っていることと、荷造りの進み具合。";
"widget.packing.name" = "持ち物";
@@ -5,6 +5,8 @@
"widget.today.description" = "오늘 일정을 타임라인으로, 날씨와 다음 장소와 함께 보여 줍니다.";
"widget.bookings.name" = "예약";
"widget.bookings.description" = "다가오는 항공편, 기차, 호텔, 식당과 그 시간.";
"widget.flight.name" = "항공편";
"widget.flight.description" = "다음 항공편을 실시간으로: 출발 카운트다운, 비행 중인 항공기, 지연과 도착.";
"widget.todos.name" = "할 일";
"widget.todos.description" = "여행을 위해 남은 일과 짐 싸기 진행 상황.";
"widget.packing.name" = "짐 싸기";
@@ -5,6 +5,8 @@
"widget.today.description" = "Het dagplan als tijdlijn, met het weer en de volgende stop.";
"widget.bookings.name" = "Boekingen";
"widget.bookings.description" = "Je volgende vluchten, treinen, hotels en tafels, en wanneer ze zijn.";
"widget.flight.name" = "Vlucht";
"widget.flight.description" = "Je volgende vlucht live: aftellen tot vertrek, het toestel onderweg, vertraging en aankomst.";
"widget.todos.name" = "Taken";
"widget.todos.description" = "Wat er nog openstaat voor de reis en hoe ver het inpakken is.";
"widget.packing.name" = "Bagage";
@@ -5,6 +5,8 @@
"widget.today.description" = "Plan dnia jako oś czasu, z pogodą i kolejnym przystankiem.";
"widget.bookings.name" = "Rezerwacje";
"widget.bookings.description" = "Twoje najbliższe loty, pociągi, hotele i stoliki oraz ich terminy.";
"widget.flight.name" = "Lot";
"widget.flight.description" = "Twój następny lot na żywo: odliczanie do odlotu, samolot w drodze, opóźnienie i przylot.";
"widget.todos.name" = "Zadania";
"widget.todos.description" = "Co jeszcze zostało do zrobienia przed podróżą i jak idzie pakowanie.";
"widget.packing.name" = "Pakowanie";
@@ -5,6 +5,8 @@
"widget.today.description" = "O plano do dia como linha do tempo, com o clima e a próxima parada.";
"widget.bookings.name" = "Reservas";
"widget.bookings.description" = "Seus próximos voos, trens, hotéis e mesas, e quando acontecem.";
"widget.flight.name" = "Voo";
"widget.flight.description" = "Seu próximo voo ao vivo: contagem regressiva para a partida, o avião a caminho, atraso e chegada.";
"widget.todos.name" = "Tarefas";
"widget.todos.description" = "O que ainda falta para a viagem e quanto da mala já está pronto.";
"widget.packing.name" = "Bagagem";
@@ -5,6 +5,8 @@
"widget.today.description" = "План дня в виде ленты времени, с погодой и следующей остановкой.";
"widget.bookings.name" = "Бронирования";
"widget.bookings.description" = "Ближайшие рейсы, поезда, отели и столики и когда они.";
"widget.flight.name" = "Рейс";
"widget.flight.description" = "Ваш следующий рейс в реальном времени: отсчёт до вылета, самолёт в пути, задержка и прибытие.";
"widget.todos.name" = "Задачи";
"widget.todos.description" = "Что ещё осталось сделать к поездке и как идут сборы.";
"widget.packing.name" = "Сборы";
@@ -5,6 +5,8 @@
"widget.today.description" = "Plán dňa ako časová os, s počasím a ďalšou zastávkou.";
"widget.bookings.name" = "Rezervácie";
"widget.bookings.description" = "Tvoje ďalšie lety, vlaky, hotely a stoly a kedy ťa čakajú.";
"widget.flight.name" = "Let";
"widget.flight.description" = "Tvoj ďalší let naživo: odpočet do odletu, lietadlo na ceste, meškanie a prílet.";
"widget.todos.name" = "Úlohy";
"widget.todos.description" = "Čo ešte zostáva na cestu a ako ďaleko je balenie.";
"widget.packing.name" = "Balenie";
@@ -5,6 +5,8 @@
"widget.today.description" = "Dagens plan som tidslinje, med vädret och nästa stopp.";
"widget.bookings.name" = "Bokningar";
"widget.bookings.description" = "Dina nästa flyg, tåg, hotell och bord, och när de är.";
"widget.flight.name" = "Flyg";
"widget.flight.description" = "Ditt nästa flyg live: nedräkning till avgång, planet på väg, försening och ankomst.";
"widget.todos.name" = "Att göra";
"widget.todos.description" = "Vad som återstår inför resan och hur långt packningen har kommit.";
"widget.packing.name" = "Packning";
@@ -5,6 +5,8 @@
"widget.today.description" = "แผนของวันนี้เป็นไทม์ไลน์ พร้อมสภาพอากาศและจุดหมายถัดไป";
"widget.bookings.name" = "การจอง";
"widget.bookings.description" = "เที่ยวบิน รถไฟ โรงแรม และร้านอาหารถัดไปของคุณ และเวลาของแต่ละรายการ";
"widget.flight.name" = "เที่ยวบิน";
"widget.flight.description" = "เที่ยวบินถัดไปแบบสด: นับถอยหลังถึงเวลาออกเดินทาง เครื่องบินระหว่างทาง ความล่าช้า และเวลาถึง";
"widget.todos.name" = "สิ่งที่ต้องทำ";
"widget.todos.description" = "สิ่งที่ยังค้างอยู่สำหรับทริป และความคืบหน้าการจัดกระเป๋า";
"widget.packing.name" = "จัดกระเป๋า";
@@ -5,6 +5,8 @@
"widget.today.description" = "Günün planı zaman çizelgesi olarak, hava durumu ve sonraki durakla.";
"widget.bookings.name" = "Rezervasyonlar";
"widget.bookings.description" = "Sıradaki uçuşların, trenlerin, otellerin ve masaların, ne zaman oldukları ile.";
"widget.flight.name" = "Uçuş";
"widget.flight.description" = "Bir sonraki uçuşun canlı: kalkışa geri sayım, yoldaki uçak, gecikme ve varış.";
"widget.todos.name" = "Yapılacaklar";
"widget.todos.description" = "Seyahat için hâlâ açık olanlar ve bavulun ne durumda olduğu.";
"widget.packing.name" = "Bavul";
@@ -5,6 +5,8 @@
"widget.today.description" = "План дня у вигляді стрічки часу, з погодою і наступною зупинкою.";
"widget.bookings.name" = "Бронювання";
"widget.bookings.description" = "Найближчі рейси, поїзди, готелі й столики та коли вони.";
"widget.flight.name" = "Рейс";
"widget.flight.description" = "Ваш наступний рейс наживо: відлік до вильоту, літак у дорозі, затримка й прибуття.";
"widget.todos.name" = "Завдання";
"widget.todos.description" = "Що ще лишилося зробити до подорожі і як просувається пакування.";
"widget.packing.name" = "Пакування";
@@ -5,6 +5,8 @@
"widget.today.description" = "Kế hoạch hôm nay dạng dòng thời gian, kèm thời tiết và điểm dừng tiếp theo.";
"widget.bookings.name" = "Đặt chỗ";
"widget.bookings.description" = "Các chuyến bay, tàu, khách sạn và bàn sắp tới của bạn, cùng thời gian.";
"widget.flight.name" = "Chuyến bay";
"widget.flight.description" = "Chuyến bay tiếp theo trực tiếp: đếm ngược giờ khởi hành, máy bay đang bay, độ trễ và giờ đến.";
"widget.todos.name" = "Việc cần làm";
"widget.todos.description" = "Những gì còn lại cho chuyến đi và việc soạn hành lý đã tới đâu.";
"widget.packing.name" = "Hành lý";
@@ -5,6 +5,8 @@
"widget.today.description" = "以时间线显示今天的计划,附带天气和下一站。";
"widget.bookings.name" = "预订";
"widget.bookings.description" = "你接下来的航班、火车、酒店和餐厅,以及时间。";
"widget.flight.name" = "航班";
"widget.flight.description" = "实时查看下一班航班:起飞倒计时、飞行中的飞机、延误和到达。";
"widget.todos.name" = "待办";
"widget.todos.description" = "旅行还剩哪些事没做,以及行李收拾到哪一步。";
"widget.packing.name" = "行李";
@@ -5,6 +5,8 @@
"widget.today.description" = "以時間軸顯示今天的計畫,附上天氣與下一站。";
"widget.bookings.name" = "預訂";
"widget.bookings.description" = "你接下來的航班、火車、飯店與餐廳,以及時間。";
"widget.flight.name" = "航班";
"widget.flight.description" = "即時查看下一班航班:起飛倒數、飛行中的飛機、延誤和抵達。";
"widget.todos.name" = "待辦";
"widget.todos.description" = "旅行還剩哪些事沒做,以及行李整理到哪一步。";
"widget.packing.name" = "行李";
@@ -375,6 +375,7 @@ struct LockAccessory: View {
switch kind {
case .trip: TripContent(snapshot: snapshot, family: family, now: now)
case .bookings: BookingsContent(snapshot: snapshot, family: family, now: now)
case .flight: FlightContent(snapshot: snapshot, family: family, now: now)
case .todos: TodosContent(snapshot: snapshot, family: family, now: now)
case .packing: PackingContent(snapshot: snapshot, family: family, now: now)
case .atlas: AtlasContent(snapshot: snapshot, family: family)
@@ -107,13 +107,14 @@ struct Render {
}
enum WidgetKind: String, CaseIterable {
case trip, today, bookings, todos, packing, atlas, collab
case trip, today, bookings, flight, todos, packing, atlas, collab
var families: [TrekFamily] {
switch self {
case .trip: return [.small, .medium, .large, .extraLarge, .circular, .rectangular, .inline]
case .today: return [.medium, .large, .extraLarge]
case .bookings: return [.small, .medium, .large, .extraLarge, .rectangular, .inline]
case .flight: return [.small, .medium, .large, .circular, .rectangular, .inline]
case .todos: return [.small, .medium, .large, .circular, .rectangular]
case .packing: return [.small, .medium, .large, .circular, .rectangular]
case .atlas: return [.small, .medium, .large, .circular, .rectangular, .inline]
@@ -158,6 +159,7 @@ struct WidgetFrame: View {
case .trip: TripContent(snapshot: snapshot, family: family, now: now)
case .today: TodayContent(snapshot: snapshot, family: family, now: now)
case .bookings: BookingsContent(snapshot: snapshot, family: family, now: now)
case .flight: FlightContent(snapshot: snapshot, family: family, now: now)
case .todos: TodosContent(snapshot: snapshot, family: family, now: now)
case .packing: PackingContent(snapshot: snapshot, family: family, now: now)
case .atlas: AtlasContent(snapshot: snapshot, family: family)
@@ -16,11 +16,13 @@ import { TrekShell } from '../../native/trekShell';
import { applyWatchActions, buildWatchSnapshot, publishWatch, takeWatchActions, watchActive } from '../../native/watch';
import { onWatchListsChange } from '../../native/watchListChanges';
import { bookingsAhead, packingSummary, todosSummary, tripPlace } from '../../native/widgetExtras';
import { widgetFlight } from '../../native/widgetFlight';
import { widgetCover, widgetWeather } from '../../native/widgetMedia';
import { atlasSummary, collabSummary, packingDetail, type WidgetAtlas } from '../../native/widgetOnline';
import {
buildSnapshot,
liveDayDue,
liveFlightOf,
pickTrip,
publishWidgets,
todayOf,
@@ -32,9 +34,10 @@ import {
type WidgetLabels,
} from '../../native/widgets';
import { useAuthStore } from '../../store/authStore';
import { useFlightLiveStore } from '../../store/flightLiveStore';
import { useSettingsStore } from '../../store/settingsStore';
import { useTripStore } from '../../store/tripStore';
import type { Day, Place, TranslationFn, Trip } from '../../types';
import type { Day, Place, Reservation, TranslationFn, Trip } from '../../types';
import { formatTime } from '../../utils/formatters';
import { localDateStr } from '../../vacay/monthGrid';
@@ -72,6 +75,20 @@ function labels(t: TranslationFn): WidgetLabels {
votes: t('native.widget.votes'),
noMessages: t('native.widget.noMessages'),
departure: t('native.widget.departure'),
flight: t('reservations.type.flight'),
flightDeparts: t('flightLive.departsIn'),
flightInAir: t('flightLive.airborne'),
flightLands: t('flightLive.landsIn'),
flightLanded: t('flightLive.landed'),
flightOnTime: t('flightLive.onTime'),
flightLate: t('flightLive.late'),
flightEarly: t('flightLive.early'),
flightEstimated: t('flightLive.estimated'),
flightReady: t('flightLive.taxiing'),
noFlight: t('flightLive.noFlight'),
durDaysHours: t('flightLive.durDaysHours'),
durHoursMinutes: t('flightLive.durHoursMinutes'),
durMinutes: t('flightLive.durMinutes'),
};
}
@@ -88,9 +105,24 @@ interface SyncContext {
language: string;
unit: string | undefined;
time: (value: string) => string;
timeFormat: string;
}
async function tripExtras(trip: Trip, days: Day[], { today, language, unit, time }: SyncContext) {
/**
* The trip's next or current flight for the flight widget, from the live
* states the server worked out (its schedule in UTC, the feed's position). Read
* fresh before the snapshot when the trip has flights and the device is online;
* offline the last states held in memory serve.
*/
async function flightOf(trip: Trip, reservations: Reservation[], path: string, context: SyncContext) {
if (!reservations.some((r) => r.type === 'flight')) return undefined;
await useFlightLiveStore.getState().load(trip.id);
const legs = Object.values(useFlightLiveStore.getState().trips[trip.id]?.legs ?? {});
return widgetFlight(legs, Date.now(), path, { locale: context.language, timeFormat: context.timeFormat });
}
async function tripExtras(trip: Trip, days: Day[], context: SyncContext) {
const { today, language, unit, time } = context;
const [places, reservations, todos, packing, memberRows] = await Promise.all([
offlineDb.places.where('trip_id').equals(trip.id).toArray(),
offlineDb.reservations.where('trip_id').equals(trip.id).toArray(),
@@ -110,7 +142,7 @@ async function tripExtras(trip: Trip, days: Day[], { today, language, unit, time
days.find((d) => (d.date ?? '').slice(0, 10) === weatherDate),
places
);
const [weather, cover, bags, collab] = await Promise.all([
const [weather, cover, bags, collab, flight] = await Promise.all([
spot && inRange ? widgetWeather(spot, { date: weatherDate, lang: language, unit, place }) : Promise.resolve(null),
widgetCover(trip.cover_image),
packingDetail(trip.id, packing),
@@ -120,6 +152,7 @@ async function tripExtras(trip: Trip, days: Day[], { today, language, unit, time
[...new Set(names)],
useAuthStore.getState().user?.id ?? null
),
flightOf(trip, reservations, path, context),
]);
const packed = packingSummary(packing, `/trips/${trip.id}?tab=listen`);
const dayDates = new Map(days.map((d) => [d.id, (d.date ?? '').slice(0, 10)]));
@@ -137,6 +170,7 @@ async function tripExtras(trip: Trip, days: Day[], { today, language, unit, time
todos: todosSummary(todos, `${path}?tab=listen`),
packing: packed && bags ? { ...packed, ...bags } : packed,
collab,
flight,
},
};
}
@@ -189,7 +223,13 @@ export default function NativeWidgetsSync(): null {
const sync = async () => {
const now = new Date();
const today = localDateStr(now.getFullYear(), now.getMonth(), now.getDate());
const context: SyncContext = { today, language, unit, time: (value) => formatTime(value, language, timeFormat) };
const context: SyncContext = {
today,
language,
unit,
time: (value) => formatTime(value, language, timeFormat),
timeFormat: timeFormat || '24h',
};
const trips = await offlineDb.trips.toArray();
const hero = pickTrip(trips, today);
// The countries do not depend on a trip: the atlas widget fills without one.
@@ -210,8 +250,11 @@ export default function NativeWidgetsSync(): null {
if (cancelled) return;
// The Live Activity from three hours before the day's first timed stop, not all day long.
const minutes = now.getHours() * 60 + now.getMinutes();
const live =
const flight = liveFlightOf(main.extra?.extras.flight, Math.round(now.getTime() / 1000));
const day =
main.day && liveDayDue(main.day, minutes) ? tripDayState(main.day, minutes, t('native.widget.dayDone')) : null;
// A flight near or in the air holds the activity as a boarding pass.
const live = day ? { ...day, ...(flight ? { flight } : {}) } : null;
await publishWidgets(main.snapshot, live, choices);
await publishToWatch(hero, main, today);
};
+12
View File
@@ -106,6 +106,18 @@ export interface TrekShellPlugin {
nextMinutes?: number;
/** Android: each stop's colour (#rrggbb) for the Live Update's segments. */
colors?: (string | null)[];
/** iOS: the day's flight near or in the air, drawn as a boarding pass; older binaries ignore it. */
flight?: {
number: string;
from: string;
to: string;
dep: number;
arr: number;
depTime: string;
arrTime: string;
delay?: number;
airborne?: boolean;
};
}): Promise<{ running: boolean }>;
endTripDay(): Promise<void>;
/** Feature storeKit (iOS) or playBilling (Android): the store's price strings for the products it knows. */
+143
View File
@@ -0,0 +1,143 @@
// FE-NATIVE-WIDGETFLIGHT-001 to FE-NATIVE-WIDGETFLIGHT-008
import type { FlightLiveLeg } from '@trek/shared';
import { describe, expect, it } from 'vitest';
import { pickWidgetLeg, widgetFlight } from './widgetFlight';
import { liveFlightOf } from './widgets';
const DEP = Date.parse('2026-06-11T11:50:00Z');
const ARR = Date.parse('2026-06-11T20:35:00Z');
const H = 3_600_000;
const CLOCK = { locale: 'en-GB', timeFormat: '24h' };
function leg(over: Partial<FlightLiveLeg> = {}): FlightLiveLeg {
return {
reservation_id: 6,
leg_index: 0,
callsign: 'DLH400',
flight_number: 'LH 400',
service_date: '2026-06-11',
origin: { code: 'FRA', name: 'Frankfurt', lat: 50.03, lng: 8.57, timezone: 'Europe/Berlin' },
destination: { code: 'JFK', name: 'New York JFK', lat: 40.64, lng: -73.78, timezone: 'America/New_York' },
phase: 'scheduled',
scheduled_departure: new Date(DEP).toISOString(),
scheduled_arrival: new Date(ARR).toISOString(),
departed_at: null,
landed_at: null,
estimated_arrival: null,
departure_delay_min: null,
arrival_delay_min: null,
progress: null,
distance_total_km: null,
distance_remaining_km: null,
position: null,
aircraft: null,
last_seen_at: null,
fetched_at: null,
stale: false,
source: null,
...over,
};
}
describe('pickWidgetLeg', () => {
it('FE-NATIVE-WIDGETFLIGHT-001: prefers the flight in the air', () => {
const ahead = leg({ reservation_id: 7 });
const flying = leg({ reservation_id: 8, phase: 'airborne' });
expect(pickWidgetLeg([ahead, flying], DEP)?.reservation_id).toBe(8);
});
it('FE-NATIVE-WIDGETFLIGHT-002: takes the earliest within a week and drops one more than two hours landed', () => {
const later = leg({
reservation_id: 9,
scheduled_departure: new Date(DEP + 48 * H).toISOString(),
scheduled_arrival: new Date(ARR + 48 * H).toISOString(),
});
expect(pickWidgetLeg([later, leg()], DEP - H)?.reservation_id).toBe(6);
expect(pickWidgetLeg([leg()], ARR + 3 * H)).toBeNull();
expect(pickWidgetLeg([leg()], DEP - 8 * 24 * H)).toBeNull();
});
});
describe('widgetFlight', () => {
it('FE-NATIVE-WIDGETFLIGHT-003: sends the schedule in seconds and the clock at each airport', () => {
const flight = widgetFlight([leg()], DEP - H, '/trips/1', CLOCK);
expect(flight).toMatchObject({
number: 'LH 400',
from: 'FRA',
to: 'JFK',
dep: DEP / 1000,
arr: ARR / 1000,
depTime: '13:50',
arrTime: '16:35',
path: '/trips/1?booking=6',
});
expect(flight?.arrExpected).toBeUndefined();
expect(flight?.landed).toBeUndefined();
});
it('FE-NATIVE-WIDGETFLIGHT-004: adds what the feed observed while the flight is in the air', () => {
const flight = widgetFlight(
[
leg({
phase: 'airborne',
departed_at: new Date(DEP + 20 * 60_000).toISOString(),
estimated_arrival: new Date(ARR + 15 * 60_000).toISOString(),
arrival_delay_min: 15,
aircraft: { registration: 'D-AIXA', type: 'A359' },
last_seen_at: new Date(DEP + 2 * H).toISOString(),
}),
],
DEP + 2 * H,
'/trips/1',
CLOCK
);
expect(flight).toMatchObject({
depActual: (DEP + 20 * 60_000) / 1000,
arrExpected: (ARR + 15 * 60_000) / 1000,
arrTimeExpected: '16:50',
delay: 15,
aircraft: 'A359 D-AIXA',
});
});
it('FE-NATIVE-WIDGETFLIGHT-005: says landed once touched down, and nothing without a flight', () => {
expect(
widgetFlight([leg({ phase: 'landed', landed_at: new Date(ARR).toISOString() })], ARR + H, '/trips/1', CLOCK)
?.landed
).toBe(true);
expect(widgetFlight([], DEP, '/trips/1', CLOCK)).toBeUndefined();
});
});
describe('liveFlightOf', () => {
it('FE-NATIVE-WIDGETFLIGHT-006: holds the Live Activity from three hours before take-off to an hour after touchdown', () => {
const flight = widgetFlight([leg()], DEP - H, '/trips/1', CLOCK);
const at = (ms: number) => liveFlightOf(flight, ms / 1000);
expect(at(DEP - 4 * H)).toBeUndefined();
expect(at(DEP - 2 * H)).toMatchObject({
number: 'LH 400',
from: 'FRA',
to: 'JFK',
depTime: '13:50',
arrTime: '16:35',
});
expect(at(ARR + 2 * H)).toBeUndefined();
expect(liveFlightOf({ ...(flight as NonNullable<typeof flight>), landed: true }, (DEP + H) / 1000)).toBeUndefined();
expect(liveFlightOf(undefined, DEP / 1000)).toBeUndefined();
});
});
describe('widget phase', () => {
it('FE-NATIVE-WIDGETFLIGHT-007: a late departure goes along as the expected one, and the flight in the air says so', () => {
const late = widgetFlight([leg({ departure_delay_min: 40 })], DEP, '/trips/1', CLOCK);
expect(late?.depExpected).toBe(DEP / 1000 + 40 * 60);
expect(late?.airborne).toBeUndefined();
expect(widgetFlight([leg({ phase: 'airborne' })], DEP + H, '/trips/1', CLOCK)?.airborne).toBe(true);
expect(liveFlightOf(late, DEP / 1000)?.dep).toBe(DEP / 1000 + 40 * 60);
});
it('FE-NATIVE-WIDGETFLIGHT-008: a flight the feed lost in the air stops being picked two hours after arrival', () => {
expect(pickWidgetLeg([leg({ phase: 'airborne' })], ARR + 3 * H)).toBeNull();
});
});
+114
View File
@@ -0,0 +1,114 @@
import type { FlightLiveLeg } from '@trek/shared';
import { airportTime, toMs } from '../utils/flightLiveModel';
/**
* The flight a home-screen widget follows: the trip's next one or the one in
* the air. Times go along as epoch seconds so the widget moves its countdown
* and its aircraft on with the clock between two snapshots; the clock times
* at either airport go along formatted, since the widget has no zone data.
* Optional on the native side (WidgetSnapshot.swift, WidgetSnapshot.kt): an
* older app binary ignores it.
*/
export interface WidgetFlight {
number: string;
from: string;
to: string;
fromCity?: string;
toCity?: string;
/** Planned departure and arrival, epoch seconds. */
dep: number;
arr: number;
/** Observed take-off, epoch seconds. */
depActual?: number;
/** Before take-off: the planned departure plus the delay seen so far, epoch seconds. */
depExpected?: number;
/** The feed sees the aircraft in the air right now. */
airborne?: boolean;
/** Touchdown once landed, else the estimate while in the air, epoch seconds. */
arrExpected?: number;
landed?: boolean;
/** Clock times at the airports: planned departure, planned arrival, expected arrival. */
depTime: string;
arrTime: string;
arrTimeExpected?: string;
/** Minutes late against the schedule (negative when early). */
delay?: number;
/** "A359 D-AIXA". */
aircraft?: string;
/** When the feed last heard the aircraft, epoch seconds. */
seen?: number;
path: string;
}
/** How long after landing the widget keeps the flight before moving on to the next. */
const KEEP_AFTER_LANDING_S = 2 * 60 * 60;
/** How far ahead a flight is worth the widget's attention. */
const LOOK_AHEAD_S = 7 * 24 * 60 * 60;
const sec = (ms: number | null): number | undefined => (ms == null ? undefined : Math.round(ms / 1000));
/**
* The leg to show: one in the air or rolling first, else the earliest whose
* arrival (with two hours' grace) is still ahead and that departs within a week.
*/
export function pickWidgetLeg(legs: FlightLiveLeg[], nowMs: number): FlightLiveLeg | null {
const now = nowMs / 1000;
const arrivalOf = (l: FlightLiveLeg) =>
sec(toMs(l.landed_at) ?? toMs(l.estimated_arrival) ?? toMs(l.scheduled_arrival));
// A leg the feed lost in the air still counts only until two hours after its arrival.
const moving = legs.find((l) => {
const arr = arrivalOf(l);
return (l.phase === 'airborne' || l.phase === 'taxiing') && (arr == null || arr + KEEP_AFTER_LANDING_S > now);
});
if (moving) return moving;
return (
legs
.filter((l) => {
const dep = sec(toMs(l.scheduled_departure));
const arr = sec(toMs(l.landed_at) ?? toMs(l.scheduled_arrival));
return dep != null && arr != null && arr + KEEP_AFTER_LANDING_S > now && dep - now < LOOK_AHEAD_S;
})
.sort((a, b) => (toMs(a.scheduled_departure) ?? 0) - (toMs(b.scheduled_departure) ?? 0))[0] ?? null
);
}
export function widgetFlight(
legs: FlightLiveLeg[],
nowMs: number,
tripPath: string,
clock: { locale: string; timeFormat: string }
): WidgetFlight | undefined {
const leg = pickWidgetLeg(legs, nowMs);
const dep = leg ? toMs(leg.scheduled_departure) : null;
const arr = leg ? toMs(leg.scheduled_arrival) : null;
if (!leg || dep == null || arr == null) return undefined;
const time = (ms: number, tz: string | null) => airportTime(ms, tz, clock.locale, clock.timeFormat);
const landed = toMs(leg.landed_at);
const expected = landed ?? (leg.phase === 'airborne' ? toMs(leg.estimated_arrival) : null);
const aircraft = [leg.aircraft?.type, leg.aircraft?.registration].filter(Boolean).join(' ');
const delay = leg.arrival_delay_min ?? leg.departure_delay_min;
return {
number: leg.flight_number,
from: leg.origin.code,
to: leg.destination.code,
...(leg.origin.name ? { fromCity: leg.origin.name } : {}),
...(leg.destination.name ? { toCity: leg.destination.name } : {}),
dep: Math.round(dep / 1000),
arr: Math.round(arr / 1000),
...(leg.departed_at ? { depActual: sec(toMs(leg.departed_at)) } : {}),
...(!leg.departed_at && leg.departure_delay_min != null && leg.departure_delay_min > 0
? { depExpected: Math.round(dep / 1000) + leg.departure_delay_min * 60 }
: {}),
...(leg.phase === 'airborne' ? { airborne: true } : {}),
...(expected != null
? { arrExpected: sec(expected), arrTimeExpected: time(expected, leg.destination.timezone) }
: {}),
...(landed != null ? { landed: true } : {}),
depTime: time(dep, leg.origin.timezone),
arrTime: time(arr, leg.destination.timezone),
...(delay != null ? { delay } : {}),
...(aircraft ? { aircraft } : {}),
...(leg.last_seen_at ? { seen: sec(toMs(leg.last_seen_at)) } : {}),
path: `${tripPath}?booking=${leg.reservation_id}`,
};
}
+60
View File
@@ -7,6 +7,7 @@ import { isNativeApp } from './platform';
import { reportNativeFailure } from './reportFailure';
import { TrekShell } from './trekShell';
import { stopLook, type WidgetBooking, type WidgetPacking, type WidgetTodos } from './widgetExtras';
import type { WidgetFlight } from './widgetFlight';
import type { WidgetAtlas, WidgetCollab, WidgetPackingDetail } from './widgetOnline';
/**
@@ -48,6 +49,27 @@ export interface WidgetLabels {
votes?: string;
noMessages?: string;
departure?: string;
/** The flight widget: its title and the words around the moment. */
flight?: string;
/** Contains "{time}", where the widget puts its own running countdown. */
flightDeparts?: string;
flightInAir?: string;
/** Contains "{time}". */
flightLands?: string;
flightLanded?: string;
flightOnTime?: string;
/** Contains "{m}". */
flightLate?: string;
/** Contains "{m}". */
flightEarly?: string;
flightEstimated?: string;
/** Past the departure time with the aircraft not yet in the air. */
flightReady?: string;
noFlight?: string;
/** Android, which has no running countdown text: "{d} d {h} h", "{h} h {m} min", "{m} min". */
durDaysHours?: string;
durHoursMinutes?: string;
durMinutes?: string;
}
interface WidgetStop {
@@ -89,6 +111,7 @@ export interface WidgetSnapshot {
packing?: WidgetPacking & Partial<WidgetPackingDetail>;
atlas?: WidgetAtlas;
collab?: WidgetCollab;
flight?: WidgetFlight;
labels: WidgetLabels;
}
@@ -116,6 +139,7 @@ interface SnapshotExtras {
packing?: (WidgetPacking & Partial<WidgetPackingDetail>) | null;
atlas?: WidgetAtlas | null;
collab?: WidgetCollab | null;
flight?: WidgetFlight;
}
export interface TripDay {
@@ -314,6 +338,7 @@ export function buildSnapshot(
if (extras.packing) snapshot.packing = extras.packing;
if (extras.atlas) snapshot.atlas = extras.atlas;
if (extras.collab) snapshot.collab = extras.collab;
if (extras.flight) snapshot.flight = extras.flight;
return snapshot;
}
@@ -330,6 +355,41 @@ interface TripDayState {
colors?: (string | null)[];
done: number;
total: number;
/** iOS: the day's flight while it is near or in the air, drawn as a boarding pass. */
flight?: LiveFlight;
}
/** The flight a Live Activity follows: times in epoch seconds, the clocks formatted. */
interface LiveFlight {
number: string;
from: string;
to: string;
dep: number;
arr: number;
depTime: string;
arrTime: string;
delay?: number;
/** In the air when the app last looked: the countdown then runs to touchdown. */
airborne?: boolean;
}
/** From three hours before take-off until an hour after touchdown the activity is about the flight. */
export function liveFlightOf(flight: WidgetFlight | undefined, nowSeconds: number): LiveFlight | undefined {
if (!flight || flight.landed) return undefined;
const dep = flight.depActual ?? flight.depExpected ?? flight.dep;
const arr = flight.arrExpected ?? flight.arr;
if (nowSeconds < dep - 3 * 3600 || nowSeconds > arr + 3600) return undefined;
return {
number: flight.number,
from: flight.from,
to: flight.to,
dep,
arr,
depTime: flight.depTime,
arrTime: flight.arrTimeExpected ?? flight.arrTime,
...(flight.delay != null ? { delay: flight.delay } : {}),
...(flight.airborne ? { airborne: true } : {}),
};
}
/**