mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 17:41:51 +00:00
feat(native): pick the trip a widget shows in Edit Widget
Widgets followed the dashboard's trip only, which is the one under way, so a packing list or to-dos for a trip still being planned could not sit on the home screen. The trip, today, bookings, to-dos, packing and group widgets now take a trip in Edit Widget (an AppIntent with the trips running or ahead, Automatic by default, which keeps following the dashboard); the world map needs none. - The app writes a snapshot per trip running or ahead (at most six, the dashboard's order) and the list to pick from, under their own keys (feature widgetTrips, so an older binary never mistakes one for the dashboard's); bags, chat and polls are kept ten minutes, covers per trip - The widget extension targets iOS 17, which configurable widgets need; the apps are not released, so no installed widget goes away - The choices and their texts in the 28 languages of the gallery
This commit is contained in:
@@ -60,7 +60,8 @@ export interface TrekShellPlugin {
|
||||
/** Feature nativePush: the notification the app was opened from, before the UI ran. */
|
||||
takeOpenedPush(): Promise<{ url: string | null }>;
|
||||
/** Feature widgets: what the home-screen widget shows (native/widgets.ts), as JSON. */
|
||||
setWidgetSnapshot(options: { json: string }): Promise<void>;
|
||||
/** Feature widgetTrips adds `key`: "trip.<id>" for one trip's snapshot, "trips" for the list a widget picks from. */
|
||||
setWidgetSnapshot(options: { json: string; key?: string }): Promise<void>;
|
||||
/** Feature liveActivity: starts the travel day's Live Activity, or updates the running one. */
|
||||
syncTripDay(options: {
|
||||
tripTitle: string;
|
||||
|
||||
@@ -42,25 +42,33 @@ export async function widgetWeather(
|
||||
return value;
|
||||
}
|
||||
|
||||
const COVER_KEY = 'trek.widgetCover';
|
||||
const COVER_KEY = 'trek.widgetCovers';
|
||||
/** Covers kept, one per trip a widget can show (widgetTripChoices). */
|
||||
const COVER_KEEP = 6;
|
||||
const COVER_MAX_PX = 720;
|
||||
const COVER_MAX_BYTES = 15 * 1024 * 1024;
|
||||
/** Kept under this so the keychain item the widget reads stays small. */
|
||||
const COVER_MAX_BASE64 = 160_000;
|
||||
|
||||
function storedCover(url: string): string | null {
|
||||
function storedCovers(): { url: string; data: string }[] {
|
||||
try {
|
||||
const raw = localStorage.getItem(COVER_KEY);
|
||||
const parsed = raw ? (JSON.parse(raw) as { url?: string; data?: string }) : null;
|
||||
return parsed?.url === url && parsed.data ? parsed.data : null;
|
||||
const parsed: unknown = raw ? JSON.parse(raw) : [];
|
||||
return Array.isArray(parsed) ? (parsed as { url: string; data: string }[]) : [];
|
||||
} catch {
|
||||
return null;
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function storedCover(url: string): string | null {
|
||||
return storedCovers().find((c) => c.url === url)?.data ?? null;
|
||||
}
|
||||
|
||||
/** Newest first, the oldest dropped past COVER_KEEP. */
|
||||
function storeCover(url: string, data: string): void {
|
||||
try {
|
||||
localStorage.setItem(COVER_KEY, JSON.stringify({ url, data }));
|
||||
const rest = storedCovers().filter((c) => c.url !== url);
|
||||
localStorage.setItem(COVER_KEY, JSON.stringify([{ url, data }, ...rest].slice(0, COVER_KEEP)));
|
||||
} catch {
|
||||
// Storage full: the cover is fetched again next time, nothing else depends on it.
|
||||
}
|
||||
|
||||
@@ -42,6 +42,21 @@ export interface WidgetCollab {
|
||||
|
||||
const HEX = /^#[0-9a-f]{6}$/i;
|
||||
|
||||
/**
|
||||
* Server answers kept for a while: the widgets sync every quarter hour for up
|
||||
* to six trips, and bags, chat and polls do not change that fast.
|
||||
*/
|
||||
const NETWORK_TTL_MS = 10 * 60 * 1000;
|
||||
const networkCache = new Map<string, { at: number; value: unknown }>();
|
||||
|
||||
async function cached<T>(key: string, read: () => Promise<T>): Promise<T> {
|
||||
const hit = networkCache.get(key);
|
||||
if (hit && Date.now() - hit.at < NETWORK_TTL_MS) return hit.value as T;
|
||||
const value = await read();
|
||||
networkCache.set(key, { at: Date.now(), value });
|
||||
return value;
|
||||
}
|
||||
|
||||
function initials(name: string): string {
|
||||
const parts = name
|
||||
.trim()
|
||||
@@ -66,7 +81,7 @@ export async function packingDetail(
|
||||
total_weight_grams?: number;
|
||||
}[] = [];
|
||||
try {
|
||||
const res = (await packingApi.listBags(tripId)) as { bags?: typeof bags };
|
||||
const res = await cached(`bags:${tripId}`, () => packingApi.listBags(tripId) as Promise<{ bags?: typeof bags }>);
|
||||
bags = res.bags ?? [];
|
||||
} catch {
|
||||
// Offline or no bags: the widget shows the items without them.
|
||||
@@ -173,8 +188,8 @@ export async function collabSummary(
|
||||
let polls: Poll[] = [];
|
||||
try {
|
||||
const [m, p] = await Promise.all([
|
||||
collabApi.getMessages(tripId) as Promise<{ messages?: Message[] }>,
|
||||
collabApi.getPolls(tripId) as Promise<{ polls?: Poll[] }>,
|
||||
cached(`messages:${tripId}`, () => collabApi.getMessages(tripId) as Promise<{ messages?: Message[] }>),
|
||||
cached(`polls:${tripId}`, () => collabApi.getPolls(tripId) as Promise<{ polls?: Poll[] }>),
|
||||
]);
|
||||
messages = m.messages ?? [];
|
||||
polls = p.polls ?? [];
|
||||
|
||||
@@ -13,7 +13,15 @@ vi.mock('./trekShell', () => ({
|
||||
}));
|
||||
|
||||
import { TrekShell } from './trekShell';
|
||||
import { buildSnapshot, pickTrip, publishWidgets, todayOf, tripDayState, withBookings } from './widgets';
|
||||
import {
|
||||
buildSnapshot,
|
||||
pickTrip,
|
||||
publishWidgets,
|
||||
todayOf,
|
||||
tripDayState,
|
||||
widgetTripChoices,
|
||||
withBookings,
|
||||
} from './widgets';
|
||||
|
||||
const trip = (id: number, start: string | null, end: string | null, archived = 0) =>
|
||||
({ id, title: `Trip ${id}`, start_date: start, end_date: end, is_archived: archived }) as unknown as Trip;
|
||||
@@ -220,3 +228,28 @@ describe('the richer snapshot', () => {
|
||||
expect(snapshot).not.toHaveProperty('packing');
|
||||
});
|
||||
});
|
||||
|
||||
describe('widgets set to a trip', () => {
|
||||
it('offers the trips running or ahead, in the dashboard order, at most six', () => {
|
||||
const trips = [
|
||||
trip(1, '2026-01-01', '2026-01-05'),
|
||||
trip(2, '2026-12-01', '2026-12-05'),
|
||||
trip(3, '2026-11-04', '2026-11-12'),
|
||||
trip(4, '2026-11-20', '2026-11-22', 1),
|
||||
trip(5, null, null),
|
||||
...[6, 7, 8, 9, 10, 11].map((id) => trip(id, `2027-0${id - 5}-01`, `2027-0${id - 5}-03`)),
|
||||
];
|
||||
expect(widgetTripChoices(trips, '2026-11-06').map((t) => t.id)).toEqual([3, 2, 6, 7, 8, 9]);
|
||||
});
|
||||
|
||||
it('writes each trip under its own key and the list to pick from', async () => {
|
||||
vi.mocked(TrekShell.setWidgetSnapshot).mockClear();
|
||||
const snapshot = buildSnapshot(trip(2, '2026-12-01', '2026-12-05'), null, labels);
|
||||
await publishWidgets(snapshot, null, [
|
||||
{ id: 2, title: 'Trip 2', start: '2026-12-01', end: '2026-12-05', snapshot },
|
||||
]);
|
||||
const calls = vi.mocked(TrekShell.setWidgetSnapshot).mock.calls.map(([options]) => options);
|
||||
expect(calls.map((c) => c.key)).toEqual([undefined, 'trip.2', 'trips']);
|
||||
expect(JSON.parse(calls[2].json)).toEqual([{ id: 2, title: 'Trip 2', start: '2026-12-01', end: '2026-12-05' }]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -144,6 +144,16 @@ export function pickTrip(trips: Trip[], today: string): Trip | null {
|
||||
return heroTrip(sortTripsByRelevance(active, today), today);
|
||||
}
|
||||
|
||||
/**
|
||||
* The trips a widget can be set to in Edit Widget: the ones running or coming
|
||||
* up, in the dashboard's order (so the hero's trip comes first), at most `limit`,
|
||||
* each of which gets a snapshot of its own.
|
||||
*/
|
||||
export function widgetTripChoices(trips: Trip[], today: string, limit = 6): Trip[] {
|
||||
const ahead = trips.filter((t) => !t.is_archived && t.start_date && (t.end_date ?? t.start_date) >= today);
|
||||
return sortTripsByRelevance(ahead, today).slice(0, limit);
|
||||
}
|
||||
|
||||
/** The symbols of the booking kinds a day's timeline shows next to its stops. */
|
||||
const RESERVATION_SYMBOLS: Record<string, string> = {
|
||||
flight: 'airplane',
|
||||
@@ -294,12 +304,32 @@ export function tripDayState(day: TripDay, nowMinutes: number, allDone: string)
|
||||
};
|
||||
}
|
||||
|
||||
/** A trip a widget can be set to in Edit Widget, and its snapshot. */
|
||||
export interface TripWidgetSnapshot {
|
||||
id: number;
|
||||
title: string;
|
||||
start: string;
|
||||
end: string;
|
||||
snapshot: WidgetSnapshot;
|
||||
}
|
||||
|
||||
export async function publishWidgets(
|
||||
snapshot: WidgetSnapshot,
|
||||
liveDay: ReturnType<typeof tripDayState> | null
|
||||
liveDay: ReturnType<typeof tripDayState> | null,
|
||||
trips: TripWidgetSnapshot[] = []
|
||||
): Promise<void> {
|
||||
if (!widgetsActive()) return;
|
||||
await TrekShell.setWidgetSnapshot({ json: JSON.stringify(snapshot) }).catch(reportNativeFailure);
|
||||
// An app binary without widgetTrips would take every one of these for the dashboard's snapshot.
|
||||
if (hasNativeFeature('widgetTrips')) {
|
||||
for (const trip of trips) {
|
||||
await TrekShell.setWidgetSnapshot({ json: JSON.stringify(trip.snapshot), key: `trip.${trip.id}` }).catch(
|
||||
reportNativeFailure
|
||||
);
|
||||
}
|
||||
const index = trips.map(({ id, title, start, end }) => ({ id, title, start, end }));
|
||||
await TrekShell.setWidgetSnapshot({ json: JSON.stringify(index), key: 'trips' }).catch(reportNativeFailure);
|
||||
}
|
||||
if (!hasNativeFeature('liveActivity')) return;
|
||||
if (liveDay && liveDay.total > 0) await TrekShell.syncTripDay(liveDay).catch(reportNativeFailure);
|
||||
else await TrekShell.endTripDay().catch(reportNativeFailure);
|
||||
|
||||
Reference in New Issue
Block a user