feat(native): booking passes go straight into Apple Wallet

Opening a .pkpass in the iOS app brought up the generic share sheet. It now
shows Wallet's own sheet with the pass and "Add", and a pass that is already in
Wallet opens there instead of being offered twice (TrekShell.addToWallet,
feature wallet). A broken pass or a device without Wallet falls back to the
share sheet as before.

Passes carry an "Apple Wallet" badge in the trip's files and a wallet icon
where they hang on a booking, so it is clear what a tap does.
This commit is contained in:
Maurice
2026-11-07 10:08:05 +01:00
parent 7b8bd4b166
commit 794da3be72
8 changed files with 185 additions and 14 deletions
+55 -1
View File
@@ -10,6 +10,7 @@ import WidgetKit
import ActivityKit
#endif
import LocalAuthentication
import PassKit
import UIKit
import WebKit
@@ -44,6 +45,7 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
CAPPluginMethod(name: "storePurchase", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "storeFinish", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "storeRestore", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "addToWallet", returnType: CAPPluginReturnPromise),
]
/// What this binary offers the server's UI, raised with every native feature
@@ -51,7 +53,7 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
/// and a server can require a minimum (minNativeShellApi in /api/health/features).
static let shellApi = 2
/// The native features by name, so the UI can turn each on by itself.
static let features: [String] = ["capabilities", "edgeBack", "tileCache", "biometricLock", "geolocation", "sharedFiles", "nativePush", "widgets", "liveActivity", "widgetTrips", "storeKit", "shareSheet"]
static let features: [String] = ["capabilities", "edgeBack", "tileCache", "biometricLock", "geolocation", "sharedFiles", "nativePush", "widgets", "liveActivity", "widgetTrips", "storeKit", "shareSheet", "wallet"]
// MARK: - Shared booking documents
@@ -381,6 +383,58 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
/// Positions and errors for the UI, shaped like the Geolocation API's, with the
/// When-In-Use permission asked the first time.
// MARK: - Apple Wallet
extension TrekShellPlugin {
/// Feature wallet: a booking's Wallet pass, straight into Apple Wallet. A pass
/// already there opens in Wallet instead of being offered twice. Resolves with
/// `result` added, opened or cancelled; rejects INVALID for bytes that are no
/// pass and UNAVAILABLE where Wallet cannot take one.
@objc func addToWallet(_ call: CAPPluginCall) {
guard let base64 = call.getString("data"), let data = Data(base64Encoded: base64),
let pass = try? PKPass(data: data) else {
call.reject("not a Wallet pass", "INVALID")
return
}
DispatchQueue.main.async { [weak self] in
let library = PKPassLibrary()
if library.containsPass(pass), let url = pass.passURL {
UIApplication.shared.open(url)
call.resolve(["result": "opened"])
return
}
guard PKAddPassesViewController.canAddPasses(),
let sheet = PKAddPassesViewController(pass: pass),
let presenter = self?.bridge?.viewController else {
call.reject("Wallet is not available", "UNAVAILABLE")
return
}
let delegate = TrekWalletSheet { [weak sheet] in
sheet?.dismiss(animated: true)
call.resolve(["result": library.containsPass(pass) ? "added" : "cancelled"])
}
sheet.delegate = delegate
TrekWalletSheet.current = delegate
presenter.present(sheet, animated: true)
}
}
}
/// Answers the Wallet sheet closing; held while it is up, since the sheet only keeps a weak delegate.
final class TrekWalletSheet: NSObject, PKAddPassesViewControllerDelegate {
static var current: TrekWalletSheet?
private let done: () -> Void
init(done: @escaping () -> Void) {
self.done = done
}
func addPassesViewControllerDidFinish(_ controller: PKAddPassesViewController) {
done()
TrekWalletSheet.current = nil
}
}
// MARK: - In-app purchase
extension TrekShellPlugin {
@@ -1,6 +1,7 @@
import { useRef, useState } from 'react'
import { ExternalLink, FileText, Link2, Paperclip, X } from 'lucide-react'
import { ExternalLink, FileText, Link2, Paperclip, Wallet, X } from 'lucide-react'
import { openFile } from '../../../../utils/fileDownload'
import { isWalletPass } from '../../../../components/Files/FileManager.helpers'
import type { TripFile } from '../../../../types'
import type { TripPlanner } from '../MTripShell'
@@ -95,7 +96,9 @@ export default function PlFileAttach({ planner, files, onAdd, onRemove, hideHint
<div className="mt-2 flex flex-col gap-1">
{attached.map(file => (
<button key={file.id} type="button" onClick={() => { void openFile(file.url, file.original_name) }} className={ITEM_CLS}>
<FileText size={11} strokeWidth={2} className="flex-none text-m-faint" />
{isWalletPass(file.mime_type, file.original_name)
? <Wallet size={11} strokeWidth={2} className="flex-none text-m-ink" />
: <FileText size={11} strokeWidth={2} className="flex-none text-m-faint" />}
<span className="min-w-0 flex-1 truncate font-geist text-[0.6875rem] font-medium text-m-ink">{file.original_name}</span>
<ExternalLink size={11} strokeWidth={2} className="flex-none text-m-faint" />
</button>
@@ -1,10 +1,10 @@
import { useEffect, useRef, useState, type ChangeEvent, type ClipboardEvent } from 'react'
import { Link, Loader2, MoreVertical, Star } from 'lucide-react'
import { Link, Loader2, MoreVertical, Star, Wallet } from 'lucide-react'
import MDancingTrek from '../../../components/MDancingTrek'
import { useTranslation, translateApiError } from '../../../../i18n'
import { fileRepo } from '../../../../repo/fileRepo'
import { openFile } from '../../../../utils/fileDownload'
import { isMedia, formatSize } from '../../../../components/Files/FileManager.helpers'
import { isMedia, isWalletPass, formatSize } from '../../../../components/Files/FileManager.helpers'
import type { TripFile } from '../../../../types'
import { TabScroller } from './tabChrome'
import type { MTabScreenProps } from './tabModel'
@@ -237,6 +237,9 @@ export default function MFilesTab({ planner, shell }: MTabScreenProps) {
)
}
/** The product's name, the same in every language. */
const APPLE_WALLET = 'Apple Wallet'
function FileRow({ file, planner, onOpen, onStar, onMenu }: {
file: TripFile
planner: MTabScreenProps['planner']
@@ -266,6 +269,13 @@ function FileRow({ file, planner, onOpen, onStar, onMenu }: {
<div className="truncate text-[0.8125rem] font-bold text-m-ink">{file.original_name}</div>
<div className="mt-1 flex flex-wrap items-center gap-1">
{isWalletPass(file.mime_type, file.original_name) && (
// A tap hands the pass to Apple Wallet (native/wallet.ts), or downloads it into Wallet on the web.
<span className="flex items-center gap-[3px] whitespace-nowrap rounded-full bg-m-act px-[7px] py-[2px] font-geist text-[length:calc(8.5px*var(--fs-scale-caption,1))] font-bold text-m-actfg">
<Wallet size={9} strokeWidth={2.4} aria-hidden="true" />
{APPLE_WALLET}
</span>
)}
{!!file.file_size && (
<span className="whitespace-nowrap rounded-full bg-[color:var(--m-ic)] px-[7px] py-[2px] font-geist text-[0.53125rem] font-bold text-m-muted">
{formatSize(file.file_size)}
+9
View File
@@ -0,0 +1,9 @@
/** A Blob as plain base64 (no data: prefix), the way the native bridge takes bytes. */
export function toBase64(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result).slice(String(reader.result).indexOf(',') + 1));
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(blob);
});
}
+4 -9
View File
@@ -1,14 +1,7 @@
import { Directory, Filesystem } from '@capacitor/filesystem';
import { Share } from '@capacitor/share';
function toBase64(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result).slice(String(reader.result).indexOf(',') + 1));
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(blob);
});
}
import { toBase64 } from './blobBase64';
import { addToWallet, isWalletPassName } from './wallet';
/** Readable, but safe as a single path segment inside the cache directory. */
export function cacheFileName(filename: string): string {
@@ -34,6 +27,8 @@ export function fileNameFromUrl(url: string): string {
* saving it to Files, opening it in another app or sending it on.
*/
export async function shareFile(blob: Blob, filename: string): Promise<void> {
// A Wallet pass goes to Apple Wallet's own sheet, not to the generic share sheet.
if (isWalletPassName(filename) && (await addToWallet(blob))) return;
const { uri } = await Filesystem.writeFile({
path: cacheFileName(filename),
data: await toBase64(blob),
+2
View File
@@ -81,6 +81,8 @@ export interface TrekShellPlugin {
}): Promise<{ kind: 'bought' | 'cancelled' | 'pending' | 'failed'; jws?: string; transactionId?: string }>;
/** iOS, feature storeKit: marks a purchase delivered once its instance exists. */
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 }>;
addListener(
+64
View File
@@ -0,0 +1,64 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const env = vi.hoisted(() => ({ ios: true, wallet: true }));
const shell = vi.hoisted(() => ({ addToWallet: 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('./trekShell', () => ({ TrekShell: shell }));
vi.mock('./reportFailure', () => ({ reportNativeFailure: report }));
import { addToWallet, canAddToWallet, isWalletPassName } from './wallet';
const pass = new Blob(['PK\u0003\u0004pass'], { type: 'application/vnd.apple.pkpass' });
beforeEach(() => {
env.ios = true;
env.wallet = true;
shell.addToWallet.mockReset();
report.mockReset();
});
describe('Apple Wallet', () => {
it('knows a pass by its name', () => {
expect(isWalletPassName('Boarding Pass.pkpass')).toBe(true);
expect(isWalletPassName('TICKET.PKPASS ')).toBe(true);
expect(isWalletPassName('passes.pkpasses')).toBe(false);
expect(isWalletPassName('booking.pdf')).toBe(false);
});
it('is offered only on iOS with the wallet feature', () => {
expect(canAddToWallet()).toBe(true);
env.wallet = false;
expect(canAddToWallet()).toBe(false);
env.wallet = true;
env.ios = false;
expect(canAddToWallet()).toBe(false);
});
it('hands the pass to Wallet as base64', async () => {
shell.addToWallet.mockResolvedValue({ result: 'added' });
expect(await addToWallet(pass)).toBe(true);
const { data } = shell.addToWallet.mock.calls[0][0] as { data: string };
expect(atob(data)).toBe('PK\u0003\u0004pass');
});
it('falls back quietly for a broken pass or no Wallet, and reports anything else', async () => {
shell.addToWallet.mockRejectedValue({ code: 'INVALID' });
expect(await addToWallet(pass)).toBe(false);
shell.addToWallet.mockRejectedValue({ code: 'UNAVAILABLE' });
expect(await addToWallet(pass)).toBe(false);
expect(report).not.toHaveBeenCalled();
shell.addToWallet.mockRejectedValue(new Error('bridge gone'));
expect(await addToWallet(pass)).toBe(false);
expect(report).toHaveBeenCalledTimes(1);
});
it('does not touch the bridge where it cannot add a pass', async () => {
env.ios = false;
expect(await addToWallet(pass)).toBe(false);
expect(shell.addToWallet).not.toHaveBeenCalled();
});
});
+34
View File
@@ -0,0 +1,34 @@
import { toBase64 } from './blobBase64';
import { hasNativeFeature } from './capabilities';
import { isNativeIos } from './platform';
import { reportNativeFailure } from './reportFailure';
import { TrekShell } from './trekShell';
/** A file that is a single Apple Wallet pass, by its name (the MIME type is often missing). */
export function isWalletPassName(filename: string): boolean {
return /\.pkpass$/i.test(filename.trim());
}
/** Whether this app can hand a pass to Apple Wallet itself (iOS, feature wallet). */
export function canAddToWallet(): boolean {
return isNativeIos() && hasNativeFeature('wallet');
}
/**
* Hands a booking's Wallet pass to Apple Wallet: the system sheet with the pass
* and "Add", or the pass opened in Wallet when it is already there. True when
* Wallet took it over (including the user closing the sheet); false when the app
* cannot, so the caller falls back to the share sheet.
*/
export async function addToWallet(blob: Blob): Promise<boolean> {
if (!canAddToWallet()) return false;
try {
await TrekShell.addToWallet({ data: await toBase64(blob) });
return true;
} catch (err) {
// INVALID (not really a pass) and UNAVAILABLE fall back to the share sheet quietly.
const code = (err as { code?: unknown })?.code;
if (code !== 'INVALID' && code !== 'UNAVAILABLE') reportNativeFailure(err);
return false;
}
}