mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-21 03:26:07 +00:00
feat(native): home-screen widget and travel-day Live Activity on iOS
A WidgetKit extension (TREKWidgets) with two parts: the next trip on the home screen, with a countdown before it starts and today's day and next stops while it runs, and a Live Activity for the travel day on the lock screen and in the Dynamic Island showing the next timed stop and the day's progress. The web app builds both from the trips stored offline on the device (native/widgets.ts) and hands them over through TrekShell (setWidgetSnapshot, syncTripDay, endTripDay). The texts are already translated, so the widget needs no localisation of its own. The snapshot lives in the keychain group the app shares with its extensions, so no App Group is needed. Taps open com.liketrek.trek://navigate/<path>. NativeWidgetsSync refreshes on start, on returning to the foreground and every quarter hour. Both parts are gated behind the widgets / liveActivity capabilities, so older binaries and the PWA are unaffected.
This commit is contained in:
@@ -24,7 +24,7 @@ vi.mock('./capabilities', () => ({
|
||||
}));
|
||||
vi.mock('./geolocation', () => ({ installNativeGeolocation: vi.fn() }));
|
||||
vi.mock('./sharedFiles', () => ({ startSharedFiles: vi.fn(async () => {}) }));
|
||||
vi.mock('./push', () => ({ startNativePush: vi.fn(async () => {}) }));
|
||||
vi.mock('./push', () => ({ startNativePush: vi.fn(async () => {}), openPushTarget: vi.fn() }));
|
||||
vi.mock('../mobile/overlayStack', () => ({ closeTopOverlay: vi.fn(() => false) }));
|
||||
|
||||
function backButtonHandler(): (event: { canGoBack: boolean }) => void {
|
||||
|
||||
@@ -8,10 +8,10 @@ import { checkAppUpdate, loadNativeCapabilities } from './capabilities';
|
||||
import { installNativeGeolocation } from './geolocation';
|
||||
import { keepOfflineShellFresh } from './offlineShell';
|
||||
import { isNativeApp, isNativeIos } from './platform';
|
||||
import { startNativePush } from './push';
|
||||
import { openPushTarget, startNativePush } from './push';
|
||||
import { reportNativeFailure } from './reportFailure';
|
||||
import { startSharedFiles } from './sharedFiles';
|
||||
import { isUnimplemented } from './trekShell';
|
||||
import { APP_URL_SCHEME, isUnimplemented } from './trekShell';
|
||||
|
||||
/** Long enough that the warm-up never competes with the first screen's requests. */
|
||||
const OFFLINE_SHELL_DELAY_MS = 15_000;
|
||||
@@ -34,6 +34,12 @@ export function startNativeApp(): void {
|
||||
// Taps on TREK notifications open the place they point at.
|
||||
void loadNativeCapabilities().then(() => startNativePush());
|
||||
|
||||
// A widget or Live Activity tap opens com.liketrek.trek://navigate/<path>.
|
||||
void App.addListener('appUrlOpen', ({ url }) => {
|
||||
const prefix = `${APP_URL_SCHEME}://navigate`;
|
||||
if (url.startsWith(prefix)) openPushTarget(url.slice(prefix.length) || '/');
|
||||
});
|
||||
|
||||
// A tap on the status bar scrolls the list under it back to the top, as in
|
||||
// every iOS app (the status-bar plugin fires statusTap on iOS).
|
||||
window.addEventListener('statusTap', scrollToTop);
|
||||
|
||||
@@ -59,6 +59,19 @@ export interface TrekShellPlugin {
|
||||
registerPush(): Promise<{ endpoint: string; keys: { p256dh: string; auth: string } }>;
|
||||
/** 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 liveActivity: starts the travel day's Live Activity, or updates the running one. */
|
||||
syncTripDay(options: {
|
||||
tripTitle: string;
|
||||
path: string;
|
||||
dayLabel: string;
|
||||
nextName: string;
|
||||
nextTime?: string;
|
||||
done: number;
|
||||
total: number;
|
||||
}): Promise<{ running: boolean }>;
|
||||
endTripDay(): Promise<void>;
|
||||
addListener(
|
||||
event: 'pushOpened',
|
||||
listener: (payload: { url: string }) => void
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { Day, Trip } from '../types';
|
||||
|
||||
vi.mock('./platform', () => ({ isNativeIos: vi.fn(() => true) }));
|
||||
vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn(() => true) }));
|
||||
vi.mock('./reportFailure', () => ({ reportNativeFailure: vi.fn() }));
|
||||
vi.mock('./trekShell', () => ({
|
||||
TrekShell: {
|
||||
setWidgetSnapshot: vi.fn(async () => {}),
|
||||
syncTripDay: vi.fn(async () => ({ running: true })),
|
||||
endTripDay: vi.fn(async () => {}),
|
||||
},
|
||||
}));
|
||||
|
||||
import { TrekShell } from './trekShell';
|
||||
import { buildSnapshot, pickTrip, publishWidgets, todayOf, tripDayState } 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;
|
||||
|
||||
const day = (id: number, n: number, date: string, places: { name: string; time?: string }[]) =>
|
||||
({
|
||||
id,
|
||||
trip_id: 1,
|
||||
day_number: n,
|
||||
date,
|
||||
assignments: places.map((p, i) => ({
|
||||
id: id * 10 + i,
|
||||
order_index: i,
|
||||
place: { name: p.name, place_time: p.time ?? null },
|
||||
})),
|
||||
}) as unknown as Day;
|
||||
|
||||
const labels = {
|
||||
nextTrip: 'Next',
|
||||
today: 'Today',
|
||||
noTrip: 'None',
|
||||
inDays: 'in {n} days',
|
||||
tomorrow: 'Tomorrow',
|
||||
nothingPlanned: '-',
|
||||
};
|
||||
|
||||
describe('pickTrip', () => {
|
||||
it('prefers the running trip, then the next upcoming one', () => {
|
||||
const trips = [
|
||||
trip(1, '2026-12-01', '2026-12-05'),
|
||||
trip(2, '2026-11-20', '2026-11-25'),
|
||||
trip(3, '2026-11-01', '2026-11-10'),
|
||||
];
|
||||
expect(pickTrip(trips, '2026-11-06')?.id).toBe(3);
|
||||
expect(pickTrip(trips, '2026-11-12')?.id).toBe(2);
|
||||
});
|
||||
|
||||
it('skips undated, archived and finished trips', () => {
|
||||
expect(
|
||||
pickTrip(
|
||||
[trip(1, null, null), trip(2, '2026-12-01', '2026-12-02', 1), trip(3, '2026-01-01', '2026-01-02')],
|
||||
'2026-11-06'
|
||||
)
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('todayOf and tripDayState', () => {
|
||||
const days = [
|
||||
day(2, 2, '2026-11-07', []),
|
||||
day(1, 1, '2026-11-06', [{ name: 'Museum', time: '09:00' }, { name: 'Walk' }, { name: 'Dinner', time: '19:30' }]),
|
||||
];
|
||||
|
||||
it('finds today in day order and keeps the plan order', () => {
|
||||
const today = todayOf(
|
||||
trip(1, '2026-11-06', '2026-11-07'),
|
||||
days,
|
||||
'2026-11-06',
|
||||
(n, m) => `${n}/${m}`,
|
||||
(t) => `T${t}`
|
||||
);
|
||||
expect(today?.dayLabel).toBe('1/2');
|
||||
expect(today?.stops.map((s) => s.name)).toEqual(['Museum', 'Walk', 'Dinner']);
|
||||
expect(today?.stops[0]).toMatchObject({ time: 'T09:00', minutes: 540 });
|
||||
});
|
||||
|
||||
it('is null on a day outside the trip', () => {
|
||||
expect(
|
||||
todayOf(
|
||||
trip(1, '2026-11-06', '2026-11-07'),
|
||||
days,
|
||||
'2026-11-09',
|
||||
() => '',
|
||||
(t) => t
|
||||
)
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('names the next timed stop and counts the ones behind', () => {
|
||||
const today = todayOf(
|
||||
trip(1, '2026-11-06', '2026-11-07'),
|
||||
days,
|
||||
'2026-11-06',
|
||||
() => 'D',
|
||||
(t) => t
|
||||
)!;
|
||||
expect(tripDayState(today, 8 * 60, 'done')).toMatchObject({ nextName: 'Museum', done: 0, total: 2 });
|
||||
expect(tripDayState(today, 12 * 60, 'done')).toMatchObject({ nextName: 'Dinner', nextTime: '19:30', done: 1 });
|
||||
expect(tripDayState(today, 22 * 60, 'done')).toMatchObject({ nextName: 'done', done: 2, nextTime: undefined });
|
||||
});
|
||||
});
|
||||
|
||||
describe('publishWidgets', () => {
|
||||
it('writes the snapshot without the internal minutes and ends the activity on a day without times', async () => {
|
||||
const snapshot = buildSnapshot(
|
||||
trip(1, '2026-11-06', '2026-11-07'),
|
||||
{ tripTitle: 'Trip 1', path: '/trips/1', dayLabel: 'D', stops: [{ name: 'Walk', time: null, minutes: null }] },
|
||||
labels
|
||||
);
|
||||
expect(snapshot.today?.stops[0]).toEqual({ name: 'Walk', time: null });
|
||||
await publishWidgets(snapshot, {
|
||||
tripTitle: 'Trip 1',
|
||||
path: '/trips/1',
|
||||
dayLabel: 'D',
|
||||
nextName: 'x',
|
||||
done: 0,
|
||||
total: 0,
|
||||
});
|
||||
expect(JSON.parse(vi.mocked(TrekShell.setWidgetSnapshot).mock.calls[0][0].json).trip.path).toBe('/trips/1');
|
||||
expect(TrekShell.endTripDay).toHaveBeenCalled();
|
||||
expect(TrekShell.syncTripDay).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import type { Day, Trip } from '../types';
|
||||
import { hasNativeFeature } from './capabilities';
|
||||
import { isNativeIos } from './platform';
|
||||
import { reportNativeFailure } from './reportFailure';
|
||||
import { TrekShell } from './trekShell';
|
||||
|
||||
/**
|
||||
* What the home-screen widget and the travel-day Live Activity show, built from
|
||||
* the trips this device keeps offline (db/offlineDb) and handed to the app
|
||||
* (TrekShell.setWidgetSnapshot, syncTripDay). The texts go along translated, so
|
||||
* the widget speaks the app's language without localising anything itself.
|
||||
*/
|
||||
export interface WidgetLabels {
|
||||
nextTrip: string;
|
||||
today: string;
|
||||
noTrip: string;
|
||||
/** Contains "{n}". */
|
||||
inDays: string;
|
||||
tomorrow: string;
|
||||
nothingPlanned: string;
|
||||
}
|
||||
|
||||
export interface WidgetStop {
|
||||
time: string | null;
|
||||
name: string;
|
||||
/** Minutes after midnight, for picking the next stop; not sent to the widget. */
|
||||
minutes: number | null;
|
||||
}
|
||||
|
||||
export interface WidgetSnapshot {
|
||||
trip: { title: string; start: string; end: string; path: string } | null;
|
||||
today: { dayLabel: string; stops: { time: string | null; name: string }[] } | null;
|
||||
labels: WidgetLabels;
|
||||
}
|
||||
|
||||
export interface TripDay {
|
||||
tripTitle: string;
|
||||
path: string;
|
||||
dayLabel: string;
|
||||
stops: WidgetStop[];
|
||||
}
|
||||
|
||||
export function widgetsActive(): boolean {
|
||||
return isNativeIos() && hasNativeFeature('widgets');
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* The running trip if there is one, else the next to start. Trips without dates
|
||||
* and trips already over are not candidates.
|
||||
*/
|
||||
export function pickTrip(trips: Trip[], today: string): Trip | null {
|
||||
const dated = trips.filter((t) => t.start_date && t.end_date && !t.is_archived);
|
||||
const running = dated.find((t) => t.start_date! <= today && t.end_date! >= today);
|
||||
if (running) return running;
|
||||
const upcoming = dated
|
||||
.filter((t) => t.start_date! > today)
|
||||
.sort((a, b) => a.start_date!.localeCompare(b.start_date!));
|
||||
return upcoming[0] ?? null;
|
||||
}
|
||||
|
||||
/** Today's day of the trip with its stops in plan order, if the trip runs today. */
|
||||
export function todayOf(
|
||||
trip: Trip,
|
||||
days: Day[],
|
||||
today: string,
|
||||
dayLabel: (index: number, total: number) => string,
|
||||
formatTime: (time: string) => string
|
||||
): TripDay | null {
|
||||
const ordered = days.filter((d) => d.trip_id === trip.id).sort((a, b) => (a.day_number ?? 0) - (b.day_number ?? 0));
|
||||
const index = ordered.findIndex((d) => (d.date ?? '').slice(0, 10) === today);
|
||||
if (index < 0) return null;
|
||||
const day = ordered[index];
|
||||
const stops = [...(day.assignments ?? [])]
|
||||
.sort((a, b) => (a.order_index ?? 0) - (b.order_index ?? 0))
|
||||
.filter((a) => a.place?.name)
|
||||
.map((a) => ({
|
||||
name: a.place!.name,
|
||||
time: a.place?.place_time ? formatTime(a.place.place_time.slice(0, 5)) : null,
|
||||
minutes: minutesOf(a.place?.place_time),
|
||||
}));
|
||||
return { tripTitle: trip.title, path: `/trips/${trip.id}`, dayLabel: dayLabel(index + 1, ordered.length), stops };
|
||||
}
|
||||
|
||||
export function buildSnapshot(trip: Trip | null, day: TripDay | null, labels: WidgetLabels): WidgetSnapshot {
|
||||
return {
|
||||
trip: trip ? { title: trip.title, start: trip.start_date!, end: trip.end_date!, path: `/trips/${trip.id}` } : null,
|
||||
today: day ? { dayLabel: day.dayLabel, stops: day.stops.map(({ time, name }) => ({ time, name })) } : null,
|
||||
labels,
|
||||
};
|
||||
}
|
||||
|
||||
/** The Live Activity's state: the first stop whose time is still ahead, else the last. */
|
||||
export function tripDayState(day: TripDay, nowMinutes: number, allDone: string) {
|
||||
const timed = day.stops.filter((s) => s.minutes != null);
|
||||
const nextIndex = day.stops.findIndex((s) => s.minutes != null && s.minutes >= nowMinutes);
|
||||
const done = nextIndex < 0 ? timed.length : day.stops.slice(0, nextIndex).filter((s) => s.minutes != null).length;
|
||||
const next = nextIndex >= 0 ? day.stops[nextIndex] : null;
|
||||
return {
|
||||
tripTitle: day.tripTitle,
|
||||
path: day.path,
|
||||
dayLabel: day.dayLabel,
|
||||
nextName: next?.name ?? allDone,
|
||||
nextTime: next?.time ?? undefined,
|
||||
done,
|
||||
total: timed.length,
|
||||
};
|
||||
}
|
||||
|
||||
export async function publishWidgets(
|
||||
snapshot: WidgetSnapshot,
|
||||
liveDay: ReturnType<typeof tripDayState> | null
|
||||
): Promise<void> {
|
||||
if (!widgetsActive()) return;
|
||||
await TrekShell.setWidgetSnapshot({ json: JSON.stringify(snapshot) }).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