Skip to content

armgit / TREK

Public Imported from GitHub
0

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

feat(native): build the Apple Watch snapshot and take back what the watch ticks off

Maurice9755330113f2
diff --git a/client/src/components/Layout/NativeWidgetsSync.tsx b/client/src/components/Layout/NativeWidgetsSync.tsx
index 34ca64f1a..742281fa6 100644
--- a/client/src/components/Layout/NativeWidgetsSync.tsx
+++ b/client/src/components/Layout/NativeWidgetsSync.tsx
@@ -2,14 +2,18 @@
* NativeWidgetsSync: keeps the iOS widgets and the travel-day Live Activity in
* step with the trips stored on this device (native/widgets.ts). Runs at start,
* whenever the app comes back to the foreground and every quarter hour while it
- * is open, so the next stop moves on through the day. Renders nothing; outside
- * an iOS binary with the widgets it does nothing.
+ * is open, so the next stop moves on through the day. The paired Apple Watch
+ * gets the hero trip in full alongside (native/watch.ts), and what is ticked
+ * off on the watch comes back here and goes through the trip store's toggles.
+ * Renders nothing; outside an iOS binary with the widgets it does nothing.
*/
import { App } from '@capacitor/app';
-import { useEffect } from 'react';
+import { useEffect, useRef } from 'react';
import { offlineDb } from '../../db/offlineDb';
import { useTranslation } from '../../i18n';
import { useNativeCapabilities } from '../../native/capabilities';
+import { TrekShell } from '../../native/trekShell';
+import { applyWatchActions, buildWatchSnapshot, publishWatch, takeWatchActions, watchActive } from '../../native/watch';
import { bookingsAhead, packingSummary, todosSummary, tripPlace } from '../../native/widgetExtras';
import { widgetCover, widgetWeather } from '../../native/widgetMedia';
import { atlasSummary, collabSummary, packingDetail, type WidgetAtlas } from '../../native/widgetOnline';
@@ -27,6 +31,7 @@ import {
} from '../../native/widgets';
import { useAuthStore } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore';
+import { useTripStore } from '../../store/tripStore';
import type { Day, Place, TranslationFn, Trip } from '../../types';
import { formatTime } from '../../utils/formatters';
import { localDateStr } from '../../vacay/monthGrid';
@@ -118,6 +123,7 @@ async function tripExtras(trip: Trip, days: Day[], { today, language, unit, time
const dayDates = new Map(days.map((d) => [d.id, (d.date ?? '').slice(0, 10)]));
return {
reservations,
+ lists: { places, packing, todos },
extras: {
place,
cover,
@@ -138,6 +144,8 @@ export default function NativeWidgetsSync(): null {
const { caps } = useNativeCapabilities();
const timeFormat = useSettingsStore((s) => s.settings.time_format);
const unit = useSettingsStore((s) => s.settings.temperature_unit);
+ /** The ids of the watch's ticks applied in this session, which the watch drops from its pending ones. */
+ const applied = useRef<string[]>([]);
useEffect(() => {
if (!widgetsActive()) return;
@@ -151,7 +159,29 @@ export default function NativeWidgetsSync(): null {
? todayOf(trip, days, context.today, (n, m) => t('native.widget.dayOf', { n, m }), context.time)
: null;
const day = plain ? withBookings(plain, extra?.reservations ?? [], context.today, context.time) : null;
- return { day, snapshot: buildSnapshot(trip, day, labels(t), { ...extra?.extras, atlas }) };
+ return { day, days, extra, snapshot: buildSnapshot(trip, day, labels(t), { ...extra?.extras, atlas }) };
+ };
+
+ /** The hero trip in full for the watch, with the ticks from it applied so far. */
+ const publishToWatch = async (trip: Trip | null, main: Awaited<ReturnType<typeof tripSnapshot>>, today: string) => {
+ if (!watchActive()) return;
+ const lists = main.extra?.lists;
+ await publishWatch(
+ buildWatchSnapshot({
+ trip,
+ days: main.days,
+ places: lists?.places ?? [],
+ reservations: main.extra?.reservations ?? [],
+ packing: lists?.packing ?? [],
+ todos: lists?.todos ?? [],
+ today,
+ hour12: timeFormat === '12h',
+ place: main.extra?.extras.place,
+ cover: main.extra?.extras.cover,
+ weather: main.extra?.extras.weather,
+ applied: applied.current,
+ })
+ );
};
const sync = async () => {
@@ -180,17 +210,30 @@ export default function NativeWidgetsSync(): null {
? tripDayState(main.day, now.getHours() * 60 + now.getMinutes(), t('native.widget.dayDone'))
: null;
await publishWidgets(main.snapshot, live, choices);
+ await publishToWatch(hero, main, today);
+ };
+
+ /** The ticks made on the watch, written like a tap in the app, then the watch told. */
+ const drainWatch = async () => {
+ const actions = await takeWatchActions();
+ if (cancelled || actions.length === 0) return;
+ const { togglePackingItem, toggleTodoItem } = useTripStore.getState();
+ const ids = await applyWatchActions(actions, { packing: togglePackingItem, todo: toggleTodoItem });
+ applied.current = [...applied.current, ...ids].slice(-50);
+ await sync();
};
- void sync();
+ void sync().then(drainWatch);
const timer = window.setInterval(() => void sync(), REFRESH_MS);
const listener = App.addListener('appStateChange', ({ isActive }) => {
- if (isActive) void sync();
+ if (isActive) void sync().then(drainWatch);
});
+ const watchListener = watchActive() ? TrekShell.addListener('watchAction', () => void drainWatch()) : null;
return () => {
cancelled = true;
window.clearInterval(timer);
void listener.then((handle) => handle.remove());
+ void watchListener?.then((handle) => handle.remove());
};
}, [caps, t, language, timeFormat, unit]);
diff --git a/client/src/native/trekShell.ts b/client/src/native/trekShell.ts
index 2a7826a91..d2b364342 100644
--- a/client/src/native/trekShell.ts
+++ b/client/src/native/trekShell.ts
@@ -98,6 +98,12 @@ export interface TrekShellPlugin {
addToWallet(options: { data: string }): Promise<{ result: 'added' | 'opened' | 'cancelled' }>;
/** iOS, feature storeKit: the newest active subscription under `prefix` on this Apple ID, if any. */
storeRestore(options: { prefix: string }): Promise<{ jws?: string; transactionId?: string }>;
+ /** Feature watch: what the Apple Watch app shows (native/watch.ts), as JSON, sent on through WatchConnectivity. */
+ setWatchSnapshot(options: { json: string }): Promise<void>;
+ /** Feature watch: the ticks the watch sent since the last call, oldest first (parsed by parseWatchActions). */
+ takeWatchActions(): Promise<{ actions: unknown[] }>;
+ /** Feature watch: the watch sent a tick; takeWatchActions has it. */
+ addListener(event: 'watchAction', listener: () => void): Promise<{ remove: () => Promise<void> }>;
addListener(
event: 'pushOpened',
listener: (payload: { url: string }) => void
diff --git a/client/src/native/watch.test.ts b/client/src/native/watch.test.ts
new file mode 100644
index 000000000..1bd6cf081
--- /dev/null
+++ b/client/src/native/watch.test.ts
@@ -0,0 +1,376 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { Day, PackingItem, Place, Reservation, TodoItem, Trip } from '../types';
+
+vi.mock('./platform', () => ({ isNativeIos: vi.fn(() => true) }));
+vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn((feature: string) => feature === 'watch') }));
+vi.mock('./reportFailure', () => ({ reportNativeFailure: vi.fn() }));
+vi.mock('./trekShell', () => ({
+ TrekShell: {
+ setWatchSnapshot: vi.fn(async () => {}),
+ takeWatchActions: vi.fn(async () => ({ actions: [] as unknown[] })),
+ },
+}));
+
+import { hasNativeFeature } from './capabilities';
+import { reportNativeFailure } from './reportFailure';
+import { TrekShell } from './trekShell';
+import {
+ applyWatchActions,
+ buildWatchSnapshot,
+ fitWatchSnapshot,
+ parseWatchActions,
+ publishWatch,
+ takeWatchActions,
+ watchBooking,
+ watchDays,
+ watchPacking,
+ watchTodos,
+ type WatchSnapshot,
+} from './watch';
+import { upcomingReservations } from './widgetExtras';
+
+const trip = { id: 7, title: 'Autumn in Kyoto', start_date: '2026-11-17', end_date: '2026-11-25' } as unknown as Trip;
+
+const day = (id: number, n: number, date: string | null, stops: Record<string, unknown>[]) =>
+ ({
+ id,
+ trip_id: 7,
+ day_number: n,
+ date,
+ assignments: stops.map((place, i) => ({ id: id * 10 + i, order_index: i, place })),
+ }) as unknown as Day;
+
+const reservation = (fields: Partial<Reservation> & { id: number; title: string; type: string }): Reservation =>
+ ({ trip_id: 7, status: 'confirmed', ...fields }) as Reservation;
+
+const flight = reservation({
+ id: 1,
+ title: 'LH 716',
+ type: 'flight',
+ reservation_time: '2026-11-17T13:05',
+ reservation_end_time: '2026-11-18T08:50',
+ confirmation_number: ' K7Q2XD ',
+ metadata: JSON.stringify({ airline: 'Lufthansa', flight_number: 'LH 716', seat: '42A' }),
+ endpoints: [
+ {
+ role: 'to',
+ sequence: 1,
+ name: 'Tokyo Haneda',
+ code: 'HND',
+ lat: 35.5494,
+ lng: 139.7798,
+ timezone: null,
+ local_time: null,
+ local_date: null,
+ },
+ {
+ role: 'from',
+ sequence: 0,
+ name: 'Frankfurt',
+ code: 'FRA',
+ lat: 50.0379,
+ lng: 8.5622,
+ timezone: 'Europe/Berlin',
+ local_time: null,
+ local_date: null,
+ },
+ ],
+});
+
+const hotel = reservation({
+ id: 2,
+ title: 'Hotel Kanra Kyoto',
+ type: 'hotel',
+ day_id: 2,
+ end_day_id: 3,
+ accommodation_place_id: 50,
+ accommodation_name: 'Hotel Kanra Kyoto',
+ metadata: JSON.stringify({ check_in_time: '15:00', check_out_time: '11:00' }),
+});
+
+const places = [{ id: 50, lat: 34.99, lng: 135.76, address: 'Kyoto' }] as unknown as Place[];
+
+const days = [
+ day(1, 1, '2026-11-17', []),
+ day(2, 2, '2026-11-18', [
+ {
+ name: 'Fushimi Inari',
+ place_time: '08:30',
+ end_time: '10:30',
+ lat: 34.967146,
+ lng: 135.772673,
+ address: '68 Fukakusa',
+ category: { color: '#D6273B', icon: 'Landmark' },
+ },
+ { name: 'Nishiki Market', place_time: null, lat: null, lng: null },
+ ]),
+ day(3, 3, '2026-11-19', []),
+];
+
+describe('watchDays', () => {
+ it('lists the days in order with their stops, coordinates and the timed bookings of their date', () => {
+ const bookings = [
+ watchBooking(flight, { day: '2026-11-17', time: '13:05' }, { dayDates: new Map(), places: new Map() }),
+ ];
+ const out = watchDays([days[2], days[0], days[1]], bookings);
+ expect(out.map((d) => d.number)).toEqual([1, 2, 3]);
+ expect(out[0].stops).toEqual([
+ {
+ name: 'LH 716',
+ minutes: 785,
+ symbol: 'airplane',
+ booking: 'flight',
+ address: 'Frankfurt',
+ lat: 50.0379,
+ lng: 8.5622,
+ },
+ ]);
+ expect(out[1].stops[0]).toEqual({
+ name: 'Fushimi Inari',
+ minutes: 510,
+ endMinutes: 630,
+ symbol: 'building.columns.fill',
+ color: '#D6273B',
+ address: '68 Fukakusa',
+ lat: 34.96715,
+ lng: 135.77267,
+ });
+ expect(out[1].stops[1]).toEqual({ name: 'Nishiki Market' });
+ });
+
+ it('prefers the stop time set on the day over the place time', () => {
+ const custom = day(4, 1, '2026-11-20', []);
+ custom.assignments = [
+ { id: 1, order_index: 0, assignment_time: '09:15', place: { name: 'Gion', place_time: '18:00' } },
+ ] as unknown as Day['assignments'];
+ expect(watchDays([custom], [])[0].stops[0].minutes).toBe(555);
+ });
+});
+
+describe('watchBooking', () => {
+ it('carries the reference, seat, carrier, both airports and the departure zone', () => {
+ const b = watchBooking(flight, { day: '2026-11-17', time: '13:05' }, { dayDates: new Map(), places: new Map() });
+ expect(b).toMatchObject({
+ id: 1,
+ kind: 'flight',
+ confirmed: true,
+ date: '2026-11-17',
+ time: '13:05',
+ endDate: '2026-11-18',
+ endTime: '08:50',
+ zone: 'Europe/Berlin',
+ code: 'K7Q2XD',
+ carrier: 'Lufthansa LH 716',
+ seat: '42A',
+ from: { name: 'Frankfurt', code: 'FRA' },
+ to: { name: 'Tokyo Haneda', code: 'HND' },
+ });
+ });
+
+ it('gives a stay its check-in, check-out, dates from its days and the hotel as the place to go', () => {
+ const dayDates = new Map([
+ [2, '2026-11-18'],
+ [3, '2026-11-19'],
+ ]);
+ const b = watchBooking(hotel, { day: '2026-11-18', time: null }, { dayDates, places: new Map([[50, places[0]]]) });
+ expect(b).toMatchObject({
+ kind: 'hotel',
+ time: '15:00',
+ endDate: '2026-11-19',
+ endTime: '11:00',
+ checkIn: '15:00',
+ checkOut: '11:00',
+ location: 'Hotel Kanra Kyoto',
+ lat: 34.99,
+ lng: 135.76,
+ });
+ });
+});
+
+describe('upcomingReservations', () => {
+ it('keeps a stay that is running when asked to', () => {
+ const dayDates = new Map([
+ [2, '2026-11-18'],
+ [3, '2026-11-19'],
+ ]);
+ expect(upcomingReservations([hotel], { dayDates, today: '2026-11-19' })).toEqual([]);
+ expect(upcomingReservations([hotel], { dayDates, today: '2026-11-19', running: true })).toHaveLength(1);
+ });
+});
+
+describe('the lists', () => {
+ it('puts the packing still to do first and counts what is packed', () => {
+ const items = [
+ { id: 1, name: 'Passport', checked: 1, category: 'Documents', sort_order: 0 },
+ { id: 2, name: 'Rain jacket', checked: 0, category: 'Clothes', sort_order: 1 },
+ ] as PackingItem[];
+ expect(watchPacking(items)).toEqual({
+ items: [
+ { id: 2, name: 'Rain jacket', done: false, group: 'Clothes' },
+ { id: 1, name: 'Passport', done: true, group: 'Documents' },
+ ],
+ packed: 1,
+ total: 2,
+ });
+ expect(watchPacking([])).toBeUndefined();
+ });
+
+ it('orders the to-dos by done, due date, then priority', () => {
+ const todo = (id: number, fields: Partial<TodoItem>) =>
+ ({
+ id,
+ name: `T${id}`,
+ checked: 0,
+ due_date: null,
+ priority: 0,
+ sort_order: id,
+ category: null,
+ ...fields,
+ }) as TodoItem;
+ const out = watchTodos([
+ todo(1, { checked: 1 }),
+ todo(2, {}),
+ todo(3, { due_date: '2026-11-15', priority: 1 }),
+ todo(4, { priority: 3 }),
+ todo(5, { due_date: '2026-11-10' }),
+ ]);
+ expect(out?.items.map((i) => i.id)).toEqual([5, 3, 4, 2, 1]);
+ expect(out?.items[1]).toEqual({ id: 3, name: 'T3', done: false, due: '2026-11-15', priority: 1 });
+ expect(out?.open).toBe(4);
+ });
+});
+
+describe('buildWatchSnapshot', () => {
+ const src = {
+ trip,
+ days,
+ places,
+ reservations: [
+ flight,
+ hotel,
+ reservation({ id: 3, title: 'Old', type: 'tour', reservation_time: '2026-11-01T10:00' }),
+ ],
+ packing: [],
+ todos: [],
+ today: '2026-11-07',
+ hour12: false,
+ place: 'Kyoto, Japan',
+ applied: ['a1'],
+ now: new Date('2026-11-07T10:00:00Z'),
+ };
+
+ it('carries the trip, its days, the bookings ahead and the applied ticks', () => {
+ const snapshot = buildWatchSnapshot(src);
+ expect(snapshot.v).toBe(1);
+ expect(snapshot.generatedAt).toBe('2026-11-07T10:00:00.000Z');
+ expect(snapshot.trip).toEqual({
+ id: 7,
+ title: 'Autumn in Kyoto',
+ start: '2026-11-17',
+ end: '2026-11-25',
+ place: 'Kyoto, Japan',
+ });
+ expect(snapshot.bookings.map((b) => b.id)).toEqual([1, 2]);
+ expect(snapshot.days).toHaveLength(3);
+ expect(snapshot.applied).toEqual(['a1']);
+ expect(snapshot).not.toHaveProperty('packing');
+ });
+
+ it('is an empty snapshot without a trip', () => {
+ expect(buildWatchSnapshot({ ...src, trip: null })).toMatchObject({ trip: null, days: [], bookings: [] });
+ });
+});
+
+describe('fitWatchSnapshot', () => {
+ const big = (): WatchSnapshot => ({
+ v: 1,
+ generatedAt: '',
+ hour12: false,
+ trip: { id: 1, title: 'T', start: '', end: '', cover: 'x'.repeat(20_000) },
+ days: [],
+ bookings: [],
+ packing: {
+ items: Array.from({ length: 400 }, (_, i) => ({
+ id: i,
+ name: `Item number ${i} with a long name`,
+ done: i % 2 === 0,
+ })),
+ packed: 200,
+ total: 400,
+ },
+ applied: [],
+ });
+
+ it('leaves a small snapshot alone', () => {
+ const small = { ...big(), packing: undefined, trip: null };
+ expect(fitWatchSnapshot(small)).toBe(small);
+ });
+
+ it('drops the cover, then the done items, then halves the lists until it fits', () => {
+ const fitted = fitWatchSnapshot(big(), 6_000);
+ expect(fitted.trip?.cover).toBeUndefined();
+ expect(fitted.packing?.items.every((i) => !i.done)).toBe(true);
+ expect(JSON.stringify(fitted).length).toBeLessThanOrEqual(6_000);
+ expect(fitted.packing?.total).toBe(400);
+ });
+});
+
+describe('the watch actions', () => {
+ it('keeps only well-formed ticks', () => {
+ const good = { id: 'u1', tripId: 7, list: 'packing', itemId: 3, done: true };
+ expect(
+ parseWatchActions([good, { ...good, list: 'budget' }, { ...good, itemId: '3' }, null, 'x', { ...good, id: '' }])
+ ).toEqual([good]);
+ expect(parseWatchActions({})).toEqual([]);
+ });
+
+ it('applies them in order through the toggles and answers their ids, failed ones included', async () => {
+ const calls: string[] = [];
+ const toggles = {
+ packing: vi.fn(async (trip: number, id: number, done: boolean) => {
+ calls.push(`p${trip}:${id}:${done}`);
+ }),
+ todo: vi.fn(async () => {
+ calls.push('t');
+ throw new Error('offline');
+ }),
+ };
+ const ids = await applyWatchActions(
+ [
+ { id: 'a', tripId: 7, list: 'packing', itemId: 1, done: true },
+ { id: 'b', tripId: 7, list: 'todo', itemId: 2, done: false },
+ ],
+ toggles
+ );
+ expect(calls).toEqual(['p7:1:true', 't']);
+ expect(ids).toEqual(['a', 'b']);
+ expect(reportNativeFailure).toHaveBeenCalled();
+ });
+
+ it('takes them from the app, and nothing on a binary without the watch', async () => {
+ vi.mocked(TrekShell.takeWatchActions).mockResolvedValueOnce({
+ actions: [{ id: 'z', tripId: 1, list: 'todo', itemId: 9, done: true }, { bad: 1 }],
+ });
+ expect(await takeWatchActions()).toEqual([{ id: 'z', tripId: 1, list: 'todo', itemId: 9, done: true }]);
+ vi.mocked(hasNativeFeature).mockReturnValueOnce(false);
+ expect(await takeWatchActions()).toEqual([]);
+ });
+});
+
+describe('publishWatch', () => {
+ it('hands the fitted snapshot to the app', async () => {
+ const snapshot = buildWatchSnapshot({
+ trip: null,
+ days: [],
+ places: [],
+ reservations: [],
+ packing: [],
+ todos: [],
+ today: '2026-11-07',
+ hour12: true,
+ now: new Date('2026-11-07T10:00:00Z'),
+ });
+ await publishWatch(snapshot);
+ expect(TrekShell.setWatchSnapshot).toHaveBeenCalledWith({ json: JSON.stringify(snapshot) });
+ });
+});
diff --git a/client/src/native/watch.ts b/client/src/native/watch.ts
new file mode 100644
index 000000000..fc5d97dca
--- /dev/null
+++ b/client/src/native/watch.ts
@@ -0,0 +1,470 @@
+import type { Day, PackingItem, Place, Reservation, TodoItem, Trip } from '../types';
+import { parseReservationMetadata } from '../utils/flightLegs';
+import { splitReservationDateTime } from '../utils/formatters';
+import { hasNativeFeature } from './capabilities';
+import { isNativeIos } from './platform';
+import { reportNativeFailure } from './reportFailure';
+import { TrekShell } from './trekShell';
+import { bookingKind, stopLook, upcomingReservations } from './widgetExtras';
+import { RESERVATION_SYMBOLS, mergeByTime, minutesOf, type WidgetWeather } from './widgets';
+
+/**
+ * What the Apple Watch app shows (client/ios/App/TREKWatch), built from the
+ * trips this device keeps offline, like the widgets' snapshot, and handed to
+ * the app (TrekShell.setWatchSnapshot), which passes it on through
+ * WatchConnectivity. The watch has no session of its own, so this carries the
+ * whole trip it needs: every day with its stops and their coordinates, the
+ * bookings with their reference, seat and platform, the packing list and the
+ * to-dos with their ids. It carries data only; the watch says everything in its
+ * own languages and formats the times itself.
+ *
+ * What the watch ticks off comes back as WatchActions (parseWatchActions) and
+ * goes through the trip store's toggles, i.e. the repos and the mutation queue,
+ * exactly as a tap in the app would. The Swift side of the shape is
+ * client/ios/App/TREKWatchKit/WatchSnapshot.swift.
+ */
+
+interface WatchStop {
+ name: string;
+ /** Minutes after midnight, and the end when the stop has one. */
+ minutes?: number;
+ endMinutes?: number;
+ symbol?: string;
+ color?: string;
+ address?: string;
+ lat?: number;
+ lng?: number;
+ /** Set for a booking on the day's timeline: its kind (flight, hotel, ...). */
+ booking?: string;
+ note?: string;
+}
+
+interface WatchDay {
+ /** yyyy-MM-dd; missing on a day without a date. */
+ date?: string;
+ /** 1-based position in the trip. */
+ number: number;
+ title?: string;
+ stops: WatchStop[];
+}
+
+interface WatchPoint {
+ name: string;
+ code?: string;
+ lat?: number;
+ lng?: number;
+}
+
+interface WatchBooking {
+ id: number;
+ title: string;
+ /** flight, train, bus, car, cruise, hotel, restaurant, event, tour, other */
+ kind: string;
+ confirmed: boolean;
+ /** yyyy-MM-dd and HH:mm (24 hours) of the start, and of the end. */
+ date?: string;
+ time?: string;
+ endDate?: string;
+ endTime?: string;
+ /** The IANA zone the times are local to, when the booking names one (a departure airport). */
+ zone?: string;
+ from?: WatchPoint;
+ to?: WatchPoint;
+ /** The booking reference. */
+ code?: string;
+ /** "Lufthansa LH 716", "ICE 597". */
+ carrier?: string;
+ seat?: string;
+ platform?: string;
+ /** Where it is: the hotel, the restaurant's address. */
+ location?: string;
+ lat?: number;
+ lng?: number;
+ /** A stay's check-in and check-out times, HH:mm. */
+ checkIn?: string;
+ checkOut?: string;
+}
+
+interface WatchItem {
+ id: number;
+ name: string;
+ done: boolean;
+ /** The packing category or to-do category. */
+ group?: string;
+ /** yyyy-MM-dd */
+ due?: string;
+ /** 0 none ... 3 high. */
+ priority?: number;
+}
+
+export interface WatchSnapshot {
+ v: 1;
+ /** When the phone built it, ISO 8601. */
+ generatedAt: string;
+ /** The user's clock in TREK's settings. */
+ hour12: boolean;
+ trip: {
+ id: number;
+ title: string;
+ start: string;
+ end: string;
+ place?: string;
+ /** The cover as a base64 JPEG; the app scales it down for the watch. */
+ cover?: string;
+ } | null;
+ days: WatchDay[];
+ bookings: WatchBooking[];
+ weather?: WidgetWeather;
+ packing?: { items: WatchItem[]; packed: number; total: number };
+ todos?: { items: WatchItem[]; open: number; total: number };
+ /** The ids of the watch's own actions this phone has applied, newest last. */
+ applied: string[];
+}
+
+/** A tick from the watch: one packing item or to-do set done or not. */
+interface WatchAction {
+ id: string;
+ tripId: number;
+ list: 'packing' | 'todo';
+ itemId: number;
+ done: boolean;
+}
+
+const MAX_DAYS = 45;
+const MAX_STOPS = 24;
+const MAX_BOOKINGS = 12;
+const MAX_NAME = 80;
+
+const text = (value: string | null | undefined, max = MAX_NAME): string | undefined => {
+ const trimmed = value?.trim();
+ return trimmed ? trimmed.slice(0, max) : undefined;
+};
+
+const coordinate = (value: number | null | undefined): number | undefined =>
+ typeof value === 'number' && Number.isFinite(value) ? Math.round(value * 1e5) / 1e5 : undefined;
+
+/** Leaves out what is undefined, so the JSON the watch gets stays small. */
+function compact<T extends object>(value: T): T {
+ return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined)) as T;
+}
+
+function placeStop(a: NonNullable<Day['assignments']>[number]): WatchStop | null {
+ const place = a.place;
+ if (!place?.name) return null;
+ const start = minutesOf(a.assignment_time ?? place.place_time);
+ const end = minutesOf(a.assignment_end_time ?? place.end_time);
+ const look = stopLook(place.category);
+ return compact({
+ name: place.name.slice(0, MAX_NAME),
+ minutes: start ?? undefined,
+ endMinutes: start != null && end != null && end > start ? end : undefined,
+ symbol: look.symbol ?? undefined,
+ color: look.color ?? undefined,
+ address: text(place.address, 120),
+ lat: coordinate(place.lat),
+ lng: coordinate(place.lng),
+ note: text(a.notes, 140),
+ });
+}
+
+/** The trip's days in order, each with its stops and the timed bookings of its date merged in by time. */
+export function watchDays(days: Day[], bookings: WatchBooking[]): WatchDay[] {
+ return [...days]
+ .sort((a, b) => (a.day_number ?? 0) - (b.day_number ?? 0))
+ .slice(0, MAX_DAYS)
+ .map((day, index) => {
+ const date = day.date ? day.date.slice(0, 10) : undefined;
+ const stops = [...(day.assignments ?? [])]
+ .sort((a, b) => (a.order_index ?? 0) - (b.order_index ?? 0))
+ .map(placeStop)
+ .filter((s): s is WatchStop => s !== null);
+ const booked = date
+ ? bookings
+ .filter((b) => b.date === date && b.time)
+ .map((b) =>
+ compact<WatchStop>({
+ name: b.title,
+ minutes: minutesOf(b.time) ?? undefined,
+ symbol: RESERVATION_SYMBOLS[b.kind] ?? 'bookmark.fill',
+ booking: b.kind,
+ address: b.from?.name ?? b.location,
+ lat: b.from?.lat ?? b.lat,
+ lng: b.from?.lng ?? b.lng,
+ })
+ )
+ : [];
+ return compact({
+ date,
+ number: index + 1,
+ title: text(day.title),
+ stops: mergeByTime(stops, booked).slice(0, MAX_STOPS),
+ });
+ });
+}
+
+function point(e: NonNullable<Reservation['endpoints']>[number] | undefined): WatchPoint | undefined {
+ if (!e) return undefined;
+ return compact({
+ name: e.name.slice(0, MAX_NAME),
+ code: text(e.code, 8),
+ lat: coordinate(e.lat),
+ lng: coordinate(e.lng),
+ });
+}
+
+/** "Lufthansa LH 716" from the flight's airline and number, "ICE 597" from a train's. */
+function carrierOf(meta: Record<string, unknown>): string | undefined {
+ const str = (key: string) => (typeof meta[key] === 'string' ? (meta[key] as string).trim() : '');
+ const number = str('flight_number') || str('train_number');
+ const joined = [str('airline'), number].filter(Boolean).join(' ');
+ return text(joined, 40);
+}
+
+type PlaceLookup = Map<number, Pick<Place, 'lat' | 'lng' | 'address'>>;
+
+const metaText = (meta: Record<string, unknown>, key: string, max = 20) =>
+ typeof meta[key] === 'string' ? text(meta[key] as string, max) : undefined;
+
+/** Where a booking is: its hotel or place with coordinates, else what its location field says. */
+function whereOf(r: Reservation, places: PlaceLookup): Pick<WatchBooking, 'location' | 'lat' | 'lng'> {
+ const placeId = r.accommodation_place_id ?? r.place_id;
+ const place = placeId == null ? undefined : places.get(placeId);
+ const named = r.accommodation_name || r.location || r.place_name;
+ return { location: text(named || place?.address), lat: coordinate(place?.lat), lng: coordinate(place?.lng) };
+}
+
+/** When a booking starts and ends; a stay without times of its own takes its check-in and check-out. */
+function timesOf(
+ r: Reservation,
+ start: { day: string | null; time: string | null },
+ meta: Record<string, unknown>,
+ dayDates: Map<number, string>
+): Pick<WatchBooking, 'date' | 'time' | 'endDate' | 'endTime'> {
+ const end = splitReservationDateTime(r.reservation_end_time);
+ const endDay = r.end_day_id == null ? undefined : dayDates.get(r.end_day_id);
+ return {
+ date: start.day ?? undefined,
+ time: start.time ?? metaText(meta, 'check_in_time'),
+ endDate: end.date ?? endDay,
+ endTime: end.time ?? metaText(meta, 'check_out_time'),
+ };
+}
+
+/** A booking with what the watch shows of it: the reference, seat, platform, both ends and where to go. */
+export function watchBooking(
+ r: Reservation,
+ start: { day: string | null; time: string | null },
+ { dayDates, places }: { dayDates: Map<number, string>; places: PlaceLookup }
+): WatchBooking {
+ const meta = parseReservationMetadata(r);
+ const legs = [...(r.endpoints ?? [])].sort((a, b) => a.sequence - b.sequence);
+ const from = legs.find((e) => e.role === 'from');
+ const to = [...legs].reverse().find((e) => e.role === 'to');
+ return compact({
+ id: r.id,
+ title: r.title.slice(0, MAX_NAME),
+ kind: bookingKind(r.type),
+ confirmed: r.status === 'confirmed',
+ ...timesOf(r, start, meta, dayDates),
+ zone: text(from?.timezone || metaText(meta, 'departure_timezone', 40), 40),
+ from: point(from),
+ to: point(to),
+ code: text(r.confirmation_number, 40),
+ carrier: carrierOf(meta),
+ seat: metaText(meta, 'seat'),
+ platform: metaText(meta, 'platform'),
+ ...whereOf(r, places),
+ checkIn: metaText(meta, 'check_in_time'),
+ checkOut: metaText(meta, 'check_out_time'),
+ });
+}
+
+/** The packing list, items still to pack first, each group in the list's order. */
+export function watchPacking(items: PackingItem[]): WatchSnapshot['packing'] {
+ if (items.length === 0) return undefined;
+ const sorted = [...items].sort((a, b) => Number(!!a.checked) - Number(!!b.checked) || a.sort_order - b.sort_order);
+ return {
+ items: sorted.map((i) =>
+ compact({ id: i.id, name: i.name.slice(0, MAX_NAME), done: !!i.checked, group: text(i.category, 40) })
+ ),
+ packed: items.filter((i) => i.checked).length,
+ total: items.length,
+ };
+}
+
+/** The to-dos, open ones first by due date (undated last) and priority, then the done ones. */
+export function watchTodos(items: TodoItem[]): WatchSnapshot['todos'] {
+ if (items.length === 0) return undefined;
+ const rank = (i: TodoItem) => [i.checked ? 1 : 0, i.due_date ? 0 : 1] as const;
+ const sorted = [...items].sort((a, b) => {
+ const [doneA, undatedA] = rank(a);
+ const [doneB, undatedB] = rank(b);
+ if (doneA !== doneB) return doneA - doneB;
+ if (undatedA !== undatedB) return undatedA - undatedB;
+ if (a.due_date && b.due_date && a.due_date !== b.due_date) return a.due_date.localeCompare(b.due_date);
+ return (b.priority ?? 0) - (a.priority ?? 0) || (a.sort_order ?? 0) - (b.sort_order ?? 0);
+ });
+ return {
+ items: sorted.map((i) =>
+ compact({
+ id: i.id,
+ name: i.name.slice(0, MAX_NAME),
+ done: !!i.checked,
+ group: text(i.category, 40),
+ due: i.due_date ? i.due_date.slice(0, 10) : undefined,
+ priority: i.priority ? Math.max(0, Math.min(3, i.priority)) : undefined,
+ })
+ ),
+ open: items.filter((i) => !i.checked).length,
+ total: items.length,
+ };
+}
+
+interface WatchSources {
+ trip: Trip | null;
+ days: Day[];
+ places: Place[];
+ reservations: Reservation[];
+ packing: PackingItem[];
+ todos: TodoItem[];
+ today: string;
+ hour12: boolean;
+ place?: string | null;
+ cover?: string | null;
+ weather?: WidgetWeather | null;
+ applied?: string[];
+ now?: Date;
+}
+
+export function buildWatchSnapshot(src: WatchSources): WatchSnapshot {
+ const { trip } = src;
+ const base = {
+ v: 1 as const,
+ generatedAt: (src.now ?? new Date()).toISOString(),
+ hour12: src.hour12,
+ applied: src.applied ?? [],
+ };
+ if (!trip) return { ...base, trip: null, days: [], bookings: [] };
+ const dayDates = new Map(src.days.map((d) => [d.id, (d.date ?? '').slice(0, 10)]));
+ const places = new Map(src.places.map((p) => [p.id, p]));
+ const dated = upcomingReservations(src.reservations, { dayDates, today: src.today, running: true });
+ const bookings = dated.map(({ r, day, time }) => watchBooking(r, { day, time }, { dayDates, places }));
+ // The days get every booking of their date; the list only the ones ahead.
+ const all = upcomingReservations(src.reservations, { dayDates, today: '0000-00-00' }).map(({ r, day, time }) =>
+ watchBooking(r, { day, time }, { dayDates, places })
+ );
+ return compact({
+ ...base,
+ trip: compact({
+ id: trip.id,
+ title: trip.title,
+ start: trip.start_date ?? '',
+ end: trip.end_date ?? '',
+ place: text(src.place),
+ cover: src.cover ?? undefined,
+ }),
+ days: watchDays(src.days, all),
+ bookings: bookings.slice(0, MAX_BOOKINGS),
+ weather: src.weather ?? undefined,
+ packing: watchPacking(src.packing),
+ todos: watchTodos(src.todos),
+ });
+}
+
+const bytes = (value: unknown) => new TextEncoder().encode(JSON.stringify(value)).length;
+
+/**
+ * The snapshot cut down to `max` bytes of JSON, for WatchConnectivity's
+ * payload limit: first the cover goes (the app adds a small one back itself
+ * when it fits), then the done to-dos and packed items, then the lists are
+ * halved, then the days far from today.
+ */
+export function fitWatchSnapshot(snapshot: WatchSnapshot, max = 48_000): WatchSnapshot {
+ let fitted = snapshot;
+ const steps: ((s: WatchSnapshot) => WatchSnapshot)[] = [
+ (s) => (s.trip?.cover ? { ...s, trip: { ...s.trip, cover: undefined } } : s),
+ (s) => ({
+ ...s,
+ packing: s.packing && { ...s.packing, items: s.packing.items.filter((i) => !i.done) },
+ todos: s.todos && { ...s.todos, items: s.todos.items.filter((i) => !i.done) },
+ }),
+ ...[0, 1, 2, 3].map(() => (s: WatchSnapshot) => ({
+ ...s,
+ packing: s.packing && { ...s.packing, items: s.packing.items.slice(0, Math.ceil(s.packing.items.length / 2)) },
+ todos: s.todos && { ...s.todos, items: s.todos.items.slice(0, Math.ceil(s.todos.items.length / 2)) },
+ })),
+ (s) => ({
+ ...s,
+ days: s.days.map((d) => ({ ...d, stops: d.stops.map((stop) => ({ ...stop, note: undefined })) })),
+ }),
+ (s) => ({ ...s, days: s.days.slice(0, 14) }),
+ ];
+ for (const step of steps) {
+ if (bytes(fitted) <= max) break;
+ fitted = step(fitted);
+ }
+ return fitted;
+}
+
+export function watchActive(): boolean {
+ return isNativeIos() && hasNativeFeature('watch');
+}
+
+export async function publishWatch(snapshot: WatchSnapshot): Promise<void> {
+ if (!watchActive()) return;
+ await TrekShell.setWatchSnapshot({ json: JSON.stringify(fitWatchSnapshot(snapshot)) }).catch(reportNativeFailure);
+}
+
+/** The actions the watch queued, as the app hands them over; anything malformed is dropped. */
+export function parseWatchActions(raw: unknown): WatchAction[] {
+ if (!Array.isArray(raw)) return [];
+ return raw.flatMap((entry): WatchAction[] => {
+ if (typeof entry !== 'object' || entry === null) return [];
+ const { id, tripId, list, itemId, done } = entry as Record<string, unknown>;
+ const valid =
+ typeof id === 'string' &&
+ id.length > 0 &&
+ id.length <= 64 &&
+ Number.isInteger(tripId) &&
+ (list === 'packing' || list === 'todo') &&
+ Number.isInteger(itemId) &&
+ typeof done === 'boolean';
+ return valid ? [{ id, tripId: tripId as number, list, itemId: itemId as number, done }] : [];
+ });
+}
+
+interface WatchToggles {
+ packing: (tripId: number, id: number, done: boolean) => Promise<void>;
+ todo: (tripId: number, id: number, done: boolean) => Promise<void>;
+}
+
+/**
+ * Applies the watch's ticks in the order they were made, through the given
+ * toggles (the trip store's, which write through the repos and the mutation
+ * queue). Answers the ids it applied; a tick whose write failed is applied too,
+ * as the toggle has already rolled it back and told the user.
+ */
+export async function applyWatchActions(actions: WatchAction[], toggles: WatchToggles): Promise<string[]> {
+ const applied: string[] = [];
+ for (const action of actions) {
+ try {
+ await toggles[action.list](action.tripId, action.itemId, action.done);
+ } catch (err: unknown) {
+ reportNativeFailure(err);
+ }
+ applied.push(action.id);
+ }
+ return applied;
+}
+
+/** Takes the ticks the watch sent while the UI was not running, and with them the ones just arriving. */
+export async function takeWatchActions(): Promise<WatchAction[]> {
+ if (!watchActive()) return [];
+ try {
+ const { actions } = await TrekShell.takeWatchActions();
+ return parseWatchActions(actions);
+ } catch (err: unknown) {
+ reportNativeFailure(err);
+ return [];
+ }
+}
diff --git a/client/src/native/widgetExtras.ts b/client/src/native/widgetExtras.ts
index 6eb0c2cb6..ef1765548 100644
--- a/client/src/native/widgetExtras.ts
+++ b/client/src/native/widgetExtras.ts
@@ -137,10 +137,49 @@ function bookingDetail(r: Reservation): string | null {
/** Transport bookings open on the trip's transports tab, the rest on its bookings tab. */
const TRANSPORT_KINDS = new Set(['flight', 'train', 'bus', 'car', 'cruise']);
+/** A booking with the day it falls on and its start time, as the widgets order them. */
+interface DatedReservation {
+ r: Reservation;
+ /** yyyy-MM-dd: its own date, else the date of the day it is placed on. */
+ day: string | null;
+ /** HH:mm, 24 hours. */
+ time: string | null;
+}
+
/**
* The trip's bookings from today on, soonest first: those without a date at
- * the end, cancelled ones and drafts an import still waits on left out.
+ * the end, cancelled ones and drafts an import still waits on left out. With
+ * `running`, a booking that started before today but ends today or later (the
+ * hotel the trip sleeps in) stays in.
*/
+export function upcomingReservations(
+ reservations: Reservation[],
+ { dayDates, today, running = false }: { dayDates: Map<number, string>; today: string; running?: boolean }
+): DatedReservation[] {
+ const dayOf = (date: string | null, dayId: number | null | undefined) =>
+ date ?? (dayId != null ? (dayDates.get(dayId) ?? null) : null);
+ return reservations
+ .filter((r) => r.status !== 'cancelled' && (r.ingest_state ?? 'live') === 'live')
+ .map((r) => {
+ const { date, time } = splitReservationDateTime(r.reservation_time);
+ const day = dayOf(date, r.day_id);
+ const end = running ? dayOf(splitReservationDateTime(r.reservation_end_time).date, r.end_day_id) : null;
+ return { r, day, time, end };
+ })
+ .filter(({ day, end }) => day == null || day >= today || (end != null && end >= today))
+ .sort((a, b) => {
+ if (a.day !== b.day) return a.day == null ? 1 : b.day == null ? -1 : a.day.localeCompare(b.day);
+ return (a.time ?? '99:99').localeCompare(b.time ?? '99:99');
+ })
+ .map(({ r, day, time }) => ({ r, day, time }));
+}
+
+/** The kind a booking type is drawn as. */
+export function bookingKind(type: string): string {
+ return KINDS[type] ?? 'other';
+}
+
+/** The trip's bookings from today on, soonest first, as the widgets show them. */
export function bookingsAhead(
reservations: Reservation[],
{
@@ -158,21 +197,10 @@ export function bookingsAhead(
limit?: number;
}
): WidgetBooking[] {
- return reservations
- .filter((r) => r.status !== 'cancelled' && (r.ingest_state ?? 'live') === 'live')
- .map((r) => {
- const { date, time } = splitReservationDateTime(r.reservation_time);
- const day = date ?? (r.day_id != null ? (dayDates.get(r.day_id) ?? null) : null);
- return { r, day, time };
- })
- .filter(({ day }) => day == null || day >= today)
- .sort((a, b) => {
- if (a.day !== b.day) return a.day == null ? 1 : b.day == null ? -1 : a.day.localeCompare(b.day);
- return (a.time ?? '99:99').localeCompare(b.time ?? '99:99');
- })
+ return upcomingReservations(reservations, { dayDates, today })
.slice(0, limit)
.map(({ r, day, time }) => {
- const kind = KINDS[r.type] ?? 'other';
+ const kind = bookingKind(r.type);
return {
title: r.title,
kind,
diff --git a/client/src/native/widgets.ts b/client/src/native/widgets.ts
index bdb8f250c..e08878b7b 100644
--- a/client/src/native/widgets.ts
+++ b/client/src/native/widgets.ts
@@ -130,7 +130,7 @@ export function widgetsActive(): boolean {
return isNativeApp() && hasNativeFeature('widgets');
}
-function minutesOf(time: string | null | undefined): number | null {
+export function minutesOf(time: string | null | undefined): number | null {
const m = /^(\d{1,2}):(\d{2})/.exec(time ?? '');
return m ? Number(m[1]) * 60 + Number(m[2]) : null;
}
@@ -156,7 +156,7 @@ export function widgetTripChoices(trips: Trip[], today: string, limit = 6): Trip
}
/** The symbols of the booking kinds a day's timeline shows next to its stops. */
-const RESERVATION_SYMBOLS: Record<string, string> = {
+export const RESERVATION_SYMBOLS: Record<string, string> = {
flight: 'airplane',
train: 'tram.fill',
bus: 'bus.fill',
@@ -170,7 +170,7 @@ const RESERVATION_SYMBOLS: Record<string, string> = {
};
/** Puts each timed booking before the first stop that comes later; untimed stops keep their place. */
-function mergeByTime(stops: WidgetStop[], booked: WidgetStop[]): WidgetStop[] {
+export function mergeByTime<T extends { minutes?: number | null }>(stops: T[], booked: T[]): T[] {
const out = [...stops];
for (const b of [...booked].sort((x, y) => (x.minutes ?? 0) - (y.minutes ?? 0))) {
const at = out.findIndex((s) => s.minutes != null && s.minutes > (b.minutes ?? 0));