feat(native): the Android app's widgets, location, tile store, Play Billing and Google Wallet

The UI now turns these on by feature on Android as well as iOS:

- widgets, widgetTrips and the travel day (liveActivity) write the same
  snapshot to the Android app's Glance widgets; the travel day also sends
  the next stop's minutes and the stops' colours for the Live Update.
- geolocation answers navigator.geolocation from the app's location stream.
- tileCache: Android keeps Mapbox's resources in its WebView client, so the
  map is offline-capable there too, without the iOS trek-tile:// rewrite.
- playBilling: the purchase client buys through Google Play on Android,
  with the purchase token as the receipt the control plane verifies.
- googleWallet: a booking's button adds it to Google Wallet on Android,
  through the save link the server asks the TREK services for.
This commit is contained in:
Maurice
2026-11-07 14:11:59 +01:00
parent d41a4f0827
commit 3beb5c4223
41 changed files with 404 additions and 60 deletions
+8 -4
View File
@@ -1,10 +1,10 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { hasNativeFeature } from './capabilities';
import { _resetNativeGeolocation, installNativeGeolocation } from './geolocation';
import { isNativeIos } from './platform';
import { isNativeApp } from './platform';
import { TrekShell, type NativeLocationPayload } from './trekShell';
vi.mock('./platform', () => ({ isNativeIos: vi.fn() }));
vi.mock('./platform', () => ({ isNativeApp: vi.fn() }));
vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn() }));
vi.mock('./trekShell', () => ({
TrekShell: { startLocation: vi.fn(), stopLocation: vi.fn(), addListener: vi.fn() },
@@ -16,7 +16,7 @@ const original = navigator.geolocation;
beforeEach(() => {
_resetNativeGeolocation();
Object.defineProperty(navigator, 'geolocation', { configurable: true, value: original });
vi.mocked(isNativeIos).mockReturnValue(true);
vi.mocked(isNativeApp).mockReturnValue(true);
vi.mocked(hasNativeFeature).mockReturnValue(true);
vi.mocked(TrekShell.startLocation).mockReset().mockResolvedValue();
vi.mocked(TrekShell.stopLocation).mockReset().mockResolvedValue();
@@ -71,9 +71,13 @@ describe('native geolocation', () => {
expect(failed.mock.calls[0][0]).toMatchObject({ code: 1, PERMISSION_DENIED: 1 });
});
it('leaves the browser API alone outside an iOS binary with the feature', () => {
it('leaves the browser API alone outside an app binary with the feature', () => {
vi.mocked(hasNativeFeature).mockReturnValue(false);
expect(installNativeGeolocation()).toBe(false);
expect(navigator.geolocation).toBe(original);
vi.mocked(hasNativeFeature).mockReturnValue(true);
vi.mocked(isNativeApp).mockReturnValue(false);
expect(installNativeGeolocation()).toBe(false);
expect(navigator.geolocation).toBe(original);
});
});
+5 -4
View File
@@ -1,11 +1,12 @@
import { hasNativeFeature } from './capabilities';
import { isNativeIos } from './platform';
import { isNativeApp } from './platform';
import { reportNativeFailure } from './reportFailure';
import { TrekShell, type NativeLocationPayload } from './trekShell';
/**
* navigator.geolocation, answered by the iOS app's CoreLocation where the binary
* has the geolocation feature.
* navigator.geolocation, answered by the app's own location stream where the
* binary has the geolocation feature: CoreLocation on iOS, the system's fused
* provider on Android.
*
* WKWebView asks for the location per server origin, under the server's name,
* and asks again across launches. The app asks once, as the app. Installing the
@@ -85,7 +86,7 @@ function add(success: Success, failure: Failure, options: PositionOptions | unde
/** Puts the app's location under navigator.geolocation. Once, inside a binary that has it. */
export function installNativeGeolocation(): boolean {
if (!isNativeIos() || !hasNativeFeature('geolocation') || typeof navigator === 'undefined') return false;
if (!isNativeApp() || !hasNativeFeature('geolocation') || typeof navigator === 'undefined') return false;
const shim: Geolocation = {
getCurrentPosition: (success, failure, options) => {
add(success, failure, options, true);
+55 -2
View File
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const platform = vi.hoisted(() => ({ ios: true }));
const platform = vi.hoisted(() => ({ ios: true, android: false }));
const shell = vi.hoisted(() => ({
getCapabilities: vi.fn(),
storeProducts: vi.fn(),
@@ -9,7 +9,7 @@ const shell = vi.hoisted(() => ({
storeRestore: vi.fn(),
}));
vi.mock('./platform', () => ({ isNativeIos: () => platform.ios }));
vi.mock('./platform', () => ({ isNativeIos: () => platform.ios, isNativeAndroid: () => platform.android }));
vi.mock('./trekShell', () => ({ TrekShell: shell }));
import { fakeIapClient, nativeIapClient, productIdFor } from './iap';
@@ -22,6 +22,7 @@ function jwsFor(productId: string): string {
beforeEach(() => {
platform.ios = true;
platform.android = false;
for (const fn of Object.values(shell)) fn.mockReset();
});
@@ -123,3 +124,55 @@ describe('native client', () => {
expect(await nativeIapClient.restore()).toBeNull();
});
});
describe('native client on Android (Google Play Billing)', () => {
beforeEach(() => {
platform.ios = false;
platform.android = true;
});
it('is available with the playBilling feature, not with storeKit', async () => {
shell.getCapabilities.mockResolvedValue({ features: ['playBilling'] });
expect(await nativeIapClient.isAvailable()).toBe(true);
shell.getCapabilities.mockResolvedValue({ features: ['storeKit'] });
expect(await nativeIapClient.isAvailable()).toBe(false);
});
it('a bought subscription yields the purchase token as a Google receipt', async () => {
shell.storePurchase.mockResolvedValue({
kind: 'bought',
purchaseToken: 'token-1',
transactionId: 'token-1',
productId: 'cloud.plus.yearly',
});
const outcome = await nativeIapClient.purchase('cloud.plus.yearly');
expect(outcome).toEqual({
kind: 'bought',
purchase: { platform: 'google', productId: 'cloud.plus.yearly', receipt: 'token-1', transactionId: 'token-1' },
});
shell.storePurchase.mockResolvedValue({ kind: 'pending' });
expect(await nativeIapClient.purchase('cloud.plus.yearly')).toEqual({ kind: 'pending' });
shell.storePurchase.mockResolvedValue({ kind: 'bought' });
expect(await nativeIapClient.purchase('cloud.plus.yearly')).toEqual({ kind: 'failed' });
});
it('a restore finds the subscription on the Google account, and acknowledges through finish', async () => {
shell.storeRestore.mockResolvedValue({
purchaseToken: 'token-2',
transactionId: 'token-2',
productId: 'cloud.start.monthly',
});
const purchase = await nativeIapClient.restore();
expect(purchase).toEqual({
platform: 'google',
productId: 'cloud.start.monthly',
receipt: 'token-2',
transactionId: 'token-2',
});
shell.storeRestore.mockResolvedValue({});
expect(await nativeIapClient.restore()).toBeNull();
shell.storeFinish.mockResolvedValue(undefined);
await nativeIapClient.finish(purchase!);
expect(shell.storeFinish).toHaveBeenCalledWith({ transactionId: 'token-2' });
});
});
+33 -14
View File
@@ -1,4 +1,4 @@
import { isNativeIos } from './platform';
import { isNativeAndroid, isNativeIos } from './platform';
import { TrekShell } from './trekShell';
/**
@@ -6,10 +6,11 @@ import { TrekShell } from './trekShell';
* screens drive a plan to a receipt through this, and never touch StoreKit
* directly. Two implementations stand behind it: a fake one for development and
* preview, so the whole subscription flow can be walked without a store, and the
* native one that runs StoreKit 2 through TrekShell (feature storeKit). Where
* neither can take a payment (Android until Play Billing is wired, a binary from
* before storeKit) the client reports itself unavailable and the shell offers no
* purchase at all: the store rules leave no room for sending buyers to the web.
* native one that runs StoreKit 2 on iOS (feature storeKit) and Google Play
* Billing on Android (feature playBilling) through TrekShell. Where neither can
* take a payment (a binary from before them, the web) the client reports itself
* unavailable and the shell offers no purchase at all: the store rules leave no
* room for sending buyers to the web.
*/
type IapPlatform = 'apple' | 'google';
@@ -18,7 +19,7 @@ type IapPlatform = 'apple' | 'google';
export interface Purchase {
platform: IapPlatform;
productId: string;
/** Apple: the signed transaction (JWS) the control plane verifies. */
/** Apple: the signed transaction (JWS); Google: the purchase token. The control plane verifies either with its store. */
receipt: string;
/** The store's id for this transaction, handed back to {@link IapClient.finish}. */
transactionId: string;
@@ -92,17 +93,26 @@ export const fakeIapClient: IapClient = {
},
};
/** The store this app buys through: the App Store on iOS, Google Play on Android. */
function nativeStore(): { platform: IapPlatform; feature: string } | null {
if (isNativeIos()) return { platform: 'apple', feature: 'storeKit' };
if (isNativeAndroid()) return { platform: 'google', feature: 'playBilling' };
return null;
}
/**
* StoreKit 2 through TrekShell. Available on iOS when the binary has the
* storeKit feature; everywhere else (Android, the web, an older binary) it
* reports itself unavailable and every call comes to nothing.
* StoreKit 2 (iOS) or Google Play Billing (Android) through TrekShell, the same
* methods on both. Available when the binary has the platform's feature;
* everywhere else (the web, an older binary) it reports itself unavailable and
* every call comes to nothing.
*/
export const nativeIapClient: IapClient = {
async isAvailable() {
if (!isNativeIos()) return false;
const store = nativeStore();
if (!store) return false;
try {
const caps = await TrekShell.getCapabilities();
return caps.features.includes('storeKit');
return caps.features.includes(store.feature);
} catch {
return false;
}
@@ -125,10 +135,16 @@ export const nativeIapClient: IapClient = {
async purchase(productId) {
try {
const result = await TrekShell.storePurchase({ productId });
if (result.kind === 'bought' && result.jws && result.transactionId) {
const receipt = result.jws ?? result.purchaseToken;
if (result.kind === 'bought' && receipt && result.transactionId) {
return {
kind: 'bought',
purchase: { platform: 'apple', productId, receipt: result.jws, transactionId: result.transactionId },
purchase: {
platform: nativeStore()?.platform ?? 'apple',
productId: result.productId ?? productId,
receipt,
transactionId: result.transactionId,
},
};
}
if (result.kind === 'cancelled' || result.kind === 'pending') return { kind: result.kind };
@@ -146,7 +162,10 @@ export const nativeIapClient: IapClient = {
},
async restore() {
try {
const { jws, transactionId } = await TrekShell.storeRestore({ prefix: PRODUCT_PREFIX });
const { jws, purchaseToken, productId, transactionId } = await TrekShell.storeRestore({ prefix: PRODUCT_PREFIX });
if (purchaseToken && transactionId) {
return { platform: 'google', productId: productId ?? '', receipt: purchaseToken, transactionId };
}
if (!jws || !transactionId) return null;
return { platform: 'apple', productId: productIdOf(jws), receipt: jws, transactionId };
} catch {
+4
View File
@@ -9,6 +9,10 @@ export function isNativeIos(): boolean {
return isNativeApp() && Capacitor.getPlatform() === 'ios';
}
export function isNativeAndroid(): boolean {
return isNativeApp() && Capacitor.getPlatform() === 'android';
}
/** The server the app is connected to: the WebView sits on its origin. */
export function nativeServerHost(): string | null {
return isNativeApp() ? window.location.host : null;
+16 -3
View File
@@ -1,26 +1,39 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { hasNativeFeature } from './capabilities';
import { isNativeIos } from './platform';
import { isNativeApp, isNativeIos } from './platform';
import { mapboxTileCacheRequest, nativeRasterTemplate, tileCacheActive, toTileCacheUrl } from './tileCache';
vi.mock('./platform', () => ({ isNativeIos: vi.fn() }));
vi.mock('./platform', () => ({ isNativeIos: vi.fn(), isNativeApp: vi.fn() }));
vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn() }));
beforeEach(() => {
vi.mocked(isNativeIos).mockReturnValue(true);
vi.mocked(isNativeApp).mockReturnValue(true);
vi.mocked(hasNativeFeature).mockReturnValue(true);
});
describe('tileCache', () => {
it('is on only in an iOS binary that has the store', () => {
it('is on only in an app binary that has the store', () => {
expect(tileCacheActive()).toBe(true);
vi.mocked(hasNativeFeature).mockReturnValue(false);
expect(tileCacheActive()).toBe(false);
vi.mocked(hasNativeFeature).mockReturnValue(true);
vi.mocked(isNativeIos).mockReturnValue(false);
vi.mocked(isNativeApp).mockReturnValue(false);
expect(tileCacheActive()).toBe(false);
});
it('on Android keeps the store but leaves every URL as it is: the WebView client takes the requests', () => {
vi.mocked(isNativeIos).mockReturnValue(false);
expect(tileCacheActive()).toBe(true);
expect(nativeRasterTemplate('https://{s}.tiles.example.com/{z}/{x}/{y}.png')).toBe(
'https://{s}.tiles.example.com/{z}/{x}/{y}.png'
);
expect(mapboxTileCacheRequest('https://a.tiles.mapbox.com/v4/x/1/2/3.vector.pbf', 'Tile').url).toBe(
'https://a.tiles.mapbox.com/v4/x/1/2/3.vector.pbf'
);
});
it('swaps only the scheme, so the store knows where the tile lives', () => {
expect(toTileCacheUrl('https://a.tile.example.com/1/2/3.png?k=v')).toBe(
'trek-tile://a.tile.example.com/1/2/3.png?k=v'
+13 -3
View File
@@ -1,5 +1,5 @@
import { hasNativeFeature } from './capabilities';
import { isNativeIos } from './platform';
import { isNativeApp, isNativeIos } from './platform';
/**
* The iOS app's own tile store (TrekTileSchemeHandler.swift), reached through
@@ -18,7 +18,17 @@ import { isNativeIos } from './platform';
*/
const TILE_CACHE_SCHEME = 'trek-tile';
/**
* Whether the app keeps the Mapbox map's resources itself, so a Mapbox map works
* offline where it was viewed. On Android the app's WebView client takes those
* requests as they are (tiles/TrekTileStore.kt), so only iOS rewrites URLs.
*/
export function tileCacheActive(): boolean {
return isNativeApp() && hasNativeFeature('tileCache');
}
/** Whether URLs go through the trek-tile:// scheme: the iOS store only. */
function tileSchemeActive(): boolean {
return isNativeIos() && hasNativeFeature('tileCache');
}
@@ -29,7 +39,7 @@ export function toTileCacheUrl(url: string): string {
/** A raster tile template for Leaflet, through the store where the app has one. */
export function nativeRasterTemplate(template: string): string {
return tileCacheActive() ? toTileCacheUrl(template) : template;
return tileSchemeActive() ? toTileCacheUrl(template) : template;
}
const MAPBOX_HOST = /^https:\/\/(?:api\.mapbox\.com|[a-z0-9-]+\.tiles\.mapbox\.com)\//i;
@@ -51,7 +61,7 @@ const CACHED_RESOURCES = new Set([
* Mapbox's servers go through the store, events and sessions never do.
*/
export function mapboxTileCacheRequest(url: string, resourceType?: string): { url: string } {
if (!MAPBOX_HOST.test(url)) return { url };
if (!tileSchemeActive() || !MAPBOX_HOST.test(url)) return { url };
if (resourceType && !CACHED_RESOURCES.has(resourceType)) return { url };
return { url: toTileCacheUrl(url) };
}
+49 -11
View File
@@ -32,9 +32,9 @@ export interface TrekShellPlugin {
openOfflineCopy(): Promise<{ opened: boolean }>;
/** What this binary offers the UI (native/capabilities.ts). Missing before shell API 2. */
getCapabilities(): Promise<NativeCapabilities>;
/** iOS, feature tileCache: what the map tile store takes on disk, and its limit. */
/** Feature tileCache: what the map tile store takes on disk, and its limit (iOS: every map; Android: Mapbox's). */
getTileCacheUsage(): Promise<{ bytes: number; limit: number }>;
/** iOS, feature tileCache: empties the map tile store. */
/** Feature tileCache: empties the map tile store. */
clearTileCache(): Promise<void>;
/** Feature biometricLock: which biometry the device offers for the app lock. */
biometryInfo(): Promise<{ available: boolean; type: string }>;
@@ -42,7 +42,7 @@ export interface TrekShellPlugin {
authenticateBiometric(options: { reason: string }): Promise<{ ok: true }>;
/** Feature biometricLock: a blurred cover in the app switcher while the lock is on. */
setPrivacyCover(options: { enabled: boolean }): Promise<void>;
/** iOS, feature geolocation: starts the native location stream (the "location" event). */
/** Feature geolocation: starts the native location stream (the "location" event). */
startLocation(options: { highAccuracy: boolean }): Promise<void>;
stopLocation(): Promise<void>;
addListener(
@@ -71,22 +71,43 @@ export interface TrekShellPlugin {
nextTime?: string;
done: number;
total: number;
/** Android: minutes after midnight of the next stop, for the countdown in the Live Update. */
nextMinutes?: number;
/** Android: each stop's colour (#rrggbb) for the Live Update's segments. */
colors?: (string | null)[];
}): Promise<{ running: boolean }>;
endTripDay(): Promise<void>;
/** iOS, feature storeKit: the App Store's price strings for the products it knows. */
/** Feature storeKit (iOS) or playBilling (Android): the store's price strings for the products it knows. */
storeProducts(options: {
ids: string[];
}): Promise<{ products: { id: string; displayPrice: string }[]; sandbox?: boolean }>;
/** iOS, feature storeKit: the purchase sheet; `jws` is the signed transaction, set when bought. */
storePurchase(options: {
productId: string;
}): Promise<{ kind: 'bought' | 'cancelled' | 'pending' | 'failed'; jws?: string; transactionId?: string }>;
/** iOS, feature storeKit: marks a purchase delivered once its instance exists. */
/**
* The purchase sheet. Set when bought: on iOS `jws`, the signed transaction; on
* Android `purchaseToken`, which the control plane verifies with Google Play.
*/
storePurchase(options: { productId: string }): Promise<{
kind: 'bought' | 'cancelled' | 'pending' | 'failed';
jws?: string;
purchaseToken?: string;
productId?: string;
transactionId?: string;
}>;
/** Marks a purchase delivered once its instance exists (Android: acknowledges it with Google Play). */
storeFinish(options: { transactionId: string }): Promise<void>;
/** iOS, feature wallet: adds a .pkpass (base64) to Apple Wallet, or opens it there when it is already in. */
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 }>;
/** The newest active subscription under `prefix` on this Apple ID or Google account, if any. */
storeRestore(options: {
prefix: string;
}): Promise<{ jws?: string; purchaseToken?: string; productId?: string; transactionId?: string }>;
/** Android, feature googleWallet: opens a Google Wallet save link (https://pay.google.com/gp/v/save/...). */
addToGoogleWallet(options: { url: string }): Promise<{ result: 'opened' }>;
/** Android, feature windowLayout: the window's size classes and a foldable's posture and hinge. */
getWindowLayout(): Promise<NativeWindowLayout>;
addListener(
event: 'windowLayout',
listener: (payload: NativeWindowLayout) => void
): Promise<{ remove: () => Promise<void> }>;
addListener(
event: 'pushOpened',
listener: (payload: { url: string }) => void
@@ -103,6 +124,23 @@ export interface SharedFilePayload {
tripId?: number;
}
/**
* The window as the Android app sees it (feature windowLayout): its size in CSS
* pixels, Android's size classes, and a foldable's posture with the hinge's
* place in the window. `posture` is none on a device without a fold.
*/
interface NativeWindowLayout {
width: number;
height: number;
widthClass: 'compact' | 'medium' | 'expanded';
heightClass: 'compact' | 'medium' | 'expanded';
posture: 'none' | 'flat' | 'halfOpened';
orientation?: 'vertical' | 'horizontal';
separating?: boolean;
occluding?: boolean;
hinge?: { left: number; top: number; right: number; bottom: number };
}
/** A position, or an error shaped like GeolocationPositionError (1 denied, 2 unavailable). */
export type NativeLocationPayload =
| {
+81 -5
View File
@@ -1,22 +1,36 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const env = vi.hoisted(() => ({ ios: true, wallet: true }));
const shell = vi.hoisted(() => ({ addToWallet: vi.fn() }));
const env = vi.hoisted(() => ({ ios: true, android: false, wallet: true, googleWallet: false }));
const shell = vi.hoisted(() => ({ addToWallet: vi.fn(), addToGoogleWallet: vi.fn() }));
const report = vi.hoisted(() => vi.fn());
vi.mock('./platform', () => ({ isNativeIos: () => env.ios }));
vi.mock('./capabilities', () => ({ hasNativeFeature: (name: string) => name === 'wallet' && env.wallet }));
vi.mock('./platform', () => ({ isNativeIos: () => env.ios, isNativeAndroid: () => env.android }));
vi.mock('./capabilities', () => ({
hasNativeFeature: (name: string) =>
(name === 'wallet' && env.wallet) || (name === 'googleWallet' && env.googleWallet),
}));
vi.mock('./trekShell', () => ({ TrekShell: shell }));
vi.mock('./reportFailure', () => ({ reportNativeFailure: report }));
import { addReservationToWallet, addToWallet, canAddToWallet, isWalletPassName } from './wallet';
import {
addReservationToGoogleWallet,
addReservationToWallet,
addToWallet,
bookingWallet,
canAddToGoogleWallet,
canAddToWallet,
isWalletPassName,
} from './wallet';
const pass = new Blob(['PK\u0003\u0004pass'], { type: 'application/vnd.apple.pkpass' });
beforeEach(() => {
env.ios = true;
env.android = false;
env.wallet = true;
env.googleWallet = false;
shell.addToWallet.mockReset();
shell.addToGoogleWallet.mockReset();
report.mockReset();
});
@@ -96,3 +110,65 @@ describe('a booking into Wallet', () => {
fetchSpy.mockRestore();
});
});
describe('Google Wallet', () => {
beforeEach(() => {
env.ios = false;
env.android = true;
env.wallet = false;
env.googleWallet = true;
});
it('is offered only on Android with the googleWallet feature, and names its wallet', () => {
expect(canAddToGoogleWallet()).toBe(true);
expect(bookingWallet()).toBe('google');
env.googleWallet = false;
expect(canAddToGoogleWallet()).toBe(false);
expect(bookingWallet()).toBeNull();
env.ios = true;
env.android = false;
env.wallet = true;
expect(bookingWallet()).toBe('apple');
});
it('asks this server for the save link in the user language and opens it in the app', async () => {
const saveUrl = 'https://pay.google.com/gp/v/save/jwt';
const fetchMock = vi.fn(async () => new Response(JSON.stringify({ saveUrl }), { status: 200 }));
vi.stubGlobal('fetch', fetchMock);
shell.addToGoogleWallet.mockResolvedValue({ result: 'opened' });
expect(await addReservationToGoogleWallet(42, 7, 'de')).toBe('added');
expect(fetchMock).toHaveBeenCalledWith('/api/trips/42/reservations/7/wallet-pass/google?lang=de', {
credentials: 'include',
});
expect(shell.addToGoogleWallet).toHaveBeenCalledWith({ url: saveUrl });
vi.unstubAllGlobals();
});
it('an undated booking, a refusal or a link the app will not open is a clear outcome', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => new Response('', { status: 422 }))
);
expect(await addReservationToGoogleWallet(42, 7, 'en')).toBe('undated');
vi.stubGlobal(
'fetch',
vi.fn(async () => new Response('', { status: 404 }))
);
expect(await addReservationToGoogleWallet(42, 7, 'en')).toBe('failed');
vi.stubGlobal(
'fetch',
vi.fn(async () => new Response(JSON.stringify({ saveUrl: 'x' }), { status: 200 }))
);
shell.addToGoogleWallet.mockRejectedValue({ code: 'INVALID' });
expect(await addReservationToGoogleWallet(42, 7, 'en')).toBe('failed');
expect(report).not.toHaveBeenCalled();
vi.stubGlobal(
'fetch',
vi.fn(async () => {
throw new Error('offline');
})
);
expect(await addReservationToGoogleWallet(42, 7, 'en')).toBe('failed');
vi.unstubAllGlobals();
});
});
+48 -1
View File
@@ -1,6 +1,6 @@
import { toBase64 } from './blobBase64';
import { hasNativeFeature } from './capabilities';
import { isNativeIos } from './platform';
import { isNativeAndroid, isNativeIos } from './platform';
import { reportNativeFailure } from './reportFailure';
import { TrekShell } from './trekShell';
@@ -59,3 +59,50 @@ export async function addReservationToWallet(
if (!response.ok) return 'failed';
return (await addToWallet(await response.blob())) ? 'added' : 'failed';
}
/** Whether this app can hand a booking to Google Wallet (Android, feature googleWallet). */
export function canAddToGoogleWallet(): boolean {
return isNativeAndroid() && hasNativeFeature('googleWallet');
}
/** The wallet a booking's button adds to here, if any: Apple Wallet on iOS, Google Wallet on Android. */
export function bookingWallet(): 'apple' | 'google' | null {
if (canAddToWallet()) return 'apple';
if (canAddToGoogleWallet()) return 'google';
return null;
}
/**
* A booking as a Google Wallet pass: this server asks the TREK services for a
* save link (GET .../reservations/:id/wallet-pass/google), and the app opens it,
* where Google Wallet shows the pass with its own Save button. `undated`: the
* booking has no date yet.
*/
export async function addReservationToGoogleWallet(
tripId: number,
reservationId: number,
language: string
): Promise<ReservationWalletOutcome> {
if (!canAddToGoogleWallet()) return 'failed';
let response: Response;
try {
response = await fetch(
`/api/trips/${tripId}/reservations/${reservationId}/wallet-pass/google?lang=${encodeURIComponent(language)}`,
{ credentials: 'include' }
);
} catch {
return 'failed';
}
if (response.status === 422) return 'undated';
if (!response.ok) return 'failed';
try {
const { saveUrl } = (await response.json()) as { saveUrl?: unknown };
if (typeof saveUrl !== 'string') return 'failed';
await TrekShell.addToGoogleWallet({ url: saveUrl });
return 'added';
} catch (err) {
const code = (err as { code?: unknown })?.code;
if (code !== 'INVALID' && code !== 'UNAVAILABLE') reportNativeFailure(err);
return 'failed';
}
}
+28 -1
View File
@@ -1,7 +1,7 @@
import { describe, expect, it, vi } from 'vitest';
import type { Day, Trip } from '../types';
vi.mock('./platform', () => ({ isNativeIos: vi.fn(() => true) }));
vi.mock('./platform', () => ({ isNativeIos: vi.fn(() => true), isNativeApp: vi.fn(() => true) }));
vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn(() => true) }));
vi.mock('./reportFailure', () => ({ reportNativeFailure: vi.fn() }));
vi.mock('./trekShell', () => ({
@@ -122,6 +122,33 @@ describe('todayOf and tripDayState', () => {
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 });
});
it('gives the Android Live Update the next stop in minutes and one colour per timed stop', () => {
const state = tripDayState(
{
tripTitle: 'T',
path: '/trips/1',
dayLabel: 'D',
stops: [
{ name: 'Museum', time: '10:00', minutes: 600, color: '#D6273B' },
{ name: 'Walk', time: null, minutes: null },
{ name: 'Dinner', time: '19:30', minutes: 1170, color: null },
],
},
12 * 60,
'done'
);
expect(state).toMatchObject({
nextName: 'Dinner',
nextMinutes: 1170,
colors: ['#D6273B', null],
done: 1,
total: 2,
});
expect(
tripDayState({ tripTitle: 'T', path: '/', dayLabel: 'D', stops: [] }, 0, 'done').nextMinutes
).toBeUndefined();
});
});
describe('publishWidgets', () => {
+23 -4
View File
@@ -2,7 +2,7 @@ import type { Day, Reservation, Trip } from '../types';
import { splitReservationDateTime } from '../utils/formatters';
import { heroTrip, sortTripsByRelevance } from '../utils/heroTrip';
import { hasNativeFeature } from './capabilities';
import { isNativeIos } from './platform';
import { isNativeApp } from './platform';
import { reportNativeFailure } from './reportFailure';
import { TrekShell } from './trekShell';
import { stopLook, type WidgetBooking, type WidgetPacking, type WidgetTodos } from './widgetExtras';
@@ -125,8 +125,9 @@ export interface TripDay {
total?: number;
}
/** iOS (WidgetKit) and Android (Glance) read the same snapshot. */
export function widgetsActive(): boolean {
return isNativeIos() && hasNativeFeature('widgets');
return isNativeApp() && hasNativeFeature('widgets');
}
function minutesOf(time: string | null | undefined): number | null {
@@ -287,8 +288,23 @@ export function buildSnapshot(
return snapshot;
}
/** What the Live Activity (iOS) and the Live Update (Android) show of the travel day. */
interface TripDayState {
tripTitle: string;
path: string;
dayLabel: string;
nextName: string;
nextTime?: string;
/** Android: minutes after midnight of the next stop, for the countdown. */
nextMinutes?: number;
/** Android: the colour of each timed stop, for the progress segments. */
colors?: (string | null)[];
done: number;
total: number;
}
/** 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) {
export function tripDayState(day: TripDay, nowMinutes: number, allDone: string): TripDayState {
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;
@@ -299,6 +315,9 @@ export function tripDayState(day: TripDay, nowMinutes: number, allDone: string)
dayLabel: day.dayLabel,
nextName: next?.name ?? allDone,
nextTime: next?.time ?? undefined,
// Android's Live Update counts down to the next stop and colours a segment per stop.
nextMinutes: next?.minutes ?? undefined,
colors: day.stops.filter((s) => s.minutes != null).map((s) => s.color ?? null),
done,
total: timed.length,
};
@@ -315,7 +334,7 @@ export interface TripWidgetSnapshot {
export async function publishWidgets(
snapshot: WidgetSnapshot,
liveDay: ReturnType<typeof tripDayState> | null,
liveDay: TripDayState | null,
trips: TripWidgetSnapshot[] = []
): Promise<void> {
if (!widgetsActive()) return;