mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
feat(native): share a booking document to TREK and import it into a trip
TREK now appears under "Open in" and in the share sheet for PDFs, calendar entries, Wallet passes and mails (iOS document types, Android VIEW and SEND filters). The native side reads the file (up to 15 MB) and hands it to the UI, which asks which trip it belongs to, upcoming trips first, then opens that trip's booking import with the file already chosen.
This commit is contained in:
@@ -34,6 +34,7 @@ import OfflineBanner from './components/Layout/OfflineBanner'
|
||||
import NewVersionNotice from './components/Layout/NewVersionNotice'
|
||||
import NativeUpdateNotice from './components/Layout/NativeUpdateNotice'
|
||||
import AppLockGate from './components/Layout/AppLockGate'
|
||||
import NativeImportSheet from './components/Layout/NativeImportSheet'
|
||||
import { SystemNoticeHost } from './components/SystemNotices/SystemNoticeHost.js'
|
||||
import HelpPanel from './components/Help/HelpPanel'
|
||||
// Notice action registrations (side-effect imports):
|
||||
@@ -446,6 +447,7 @@ export default function App() {
|
||||
<ErrorBoundary boundaryId="widget:new-version" fallback={null}><NewVersionNotice /></ErrorBoundary>
|
||||
<ErrorBoundary boundaryId="widget:native-update" fallback={null}><NativeUpdateNotice /></ErrorBoundary>
|
||||
<ErrorBoundary boundaryId="widget:app-lock" fallback={null}><AppLockGate /></ErrorBoundary>
|
||||
<ErrorBoundary boundaryId="widget:native-import" fallback={null}><NativeImportSheet /></ErrorBoundary>
|
||||
{/* One boundary for all route chunks, above <Routes> so it stays mounted
|
||||
across navigations. react-router runs location updates inside a transition,
|
||||
so a mounted boundary keeps the current page on screen instead of flashing
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import { tripsApi } from '../../api/client';
|
||||
import { useSharedImportStore } from '../../native/sharedFiles';
|
||||
import NativeImportSheet from './NativeImportSheet';
|
||||
|
||||
const navigate = vi.hoisted(() => vi.fn());
|
||||
vi.mock('react-router', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('react-router')>()),
|
||||
useNavigate: () => navigate,
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
navigate.mockReset();
|
||||
useSharedImportStore.setState({ file: null, tripId: null });
|
||||
vi.spyOn(tripsApi, 'list').mockResolvedValue({
|
||||
trips: [
|
||||
{ id: 1, title: 'Past trip', start_date: '2020-01-01', end_date: '2020-01-05' },
|
||||
{ id: 2, title: 'Japan', start_date: '2099-03-01', end_date: '2099-03-10' },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
describe('NativeImportSheet', () => {
|
||||
it('asks which trip a shared document goes to, upcoming trips first, and opens it there', async () => {
|
||||
render(<NativeImportSheet />);
|
||||
act(() => useSharedImportStore.getState().setFile(new File(['x'], 'booking.pdf', { type: 'application/pdf' })));
|
||||
|
||||
const rows = await screen.findAllByRole('button', { name: /Japan|Past trip/ });
|
||||
expect(rows.map((r) => r.textContent)).toEqual(['Japan', 'Past trip']);
|
||||
expect(screen.getByText('booking.pdf')).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(rows[0]);
|
||||
expect(useSharedImportStore.getState().tripId).toBe(2);
|
||||
expect(navigate).toHaveBeenCalledWith('/trips/2');
|
||||
});
|
||||
|
||||
it('stays closed with nothing shared', () => {
|
||||
render(<NativeImportSheet />);
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
expect(tripsApi.list).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* NativeImportSheet: a booking document was shared to TREK (native/sharedFiles.ts),
|
||||
* so this asks which trip it belongs to and opens that trip's booking import with
|
||||
* the file already chosen. Trips still ahead come first, the ones that ended after.
|
||||
*/
|
||||
import { ChevronRight, FileText } from 'lucide-react';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { tripsApi } from '../../api/client';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import MSheet from '../../mobile/components/MSheet';
|
||||
import { useSharedImportStore } from '../../native/sharedFiles';
|
||||
|
||||
interface TripRow {
|
||||
id: number;
|
||||
title: string;
|
||||
start_date?: string | null;
|
||||
end_date?: string | null;
|
||||
}
|
||||
|
||||
export default function NativeImportSheet(): React.ReactElement | null {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const file = useSharedImportStore((s) => s.file);
|
||||
const tripId = useSharedImportStore((s) => s.tripId);
|
||||
const chooseTrip = useSharedImportStore((s) => s.chooseTrip);
|
||||
const setFile = useSharedImportStore((s) => s.setFile);
|
||||
const [trips, setTrips] = useState<TripRow[]>([]);
|
||||
|
||||
const open = !!file && tripId == null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
tripsApi.list().then(
|
||||
(data: { trips?: TripRow[] }) => {
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const list = [...(data.trips ?? [])];
|
||||
const ahead = (trip: TripRow) => (trip.end_date ?? '9999') >= today;
|
||||
list.sort(
|
||||
(a, b) => Number(ahead(b)) - Number(ahead(a)) || (a.start_date ?? '').localeCompare(b.start_date ?? '')
|
||||
);
|
||||
setTrips(list);
|
||||
},
|
||||
() => setTrips([])
|
||||
);
|
||||
}, [open]);
|
||||
|
||||
const pick = (id: number) => {
|
||||
chooseTrip(id);
|
||||
navigate(`/trips/${id}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<MSheet open={open} onClose={() => setFile(null)} variant="bottom" ariaLabel={t('native.share.title')}>
|
||||
<div className="px-4 pb-4 pt-6">
|
||||
<div className="mb-1 px-1 text-[0.8125rem] font-bold text-m-ink">{t('native.share.title')}</div>
|
||||
{file && (
|
||||
<div className="mb-3 flex items-center gap-2 px-1 font-geist text-[0.6875rem] text-m-muted">
|
||||
<FileText size={13} aria-hidden="true" />
|
||||
<span className="truncate">{file.name}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex max-h-[50vh] flex-col gap-2 overflow-y-auto">
|
||||
{trips.map((trip) => (
|
||||
<button
|
||||
key={trip.id}
|
||||
type="button"
|
||||
onClick={() => pick(trip.id)}
|
||||
className="flex items-center gap-3 rounded-[16px] border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] px-4 py-3 text-start transition-transform active:scale-[.98]"
|
||||
>
|
||||
<span className="min-w-0 flex-1 truncate text-[0.875rem] font-bold text-m-ink">{trip.title}</span>
|
||||
<ChevronRight size={16} className="flex-none text-m-faint" aria-hidden="true" />
|
||||
</button>
|
||||
))}
|
||||
{trips.length === 0 && <p className="px-1 text-[0.75rem] text-m-muted">{t('native.share.noTrips')}</p>}
|
||||
</div>
|
||||
</div>
|
||||
</MSheet>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useSharedImportStore } from '../../native/sharedFiles'
|
||||
import { useState, useRef, useEffect } from 'react'
|
||||
import { Upload, X } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
@@ -35,6 +36,12 @@ export default function BookingImportModal({ isOpen, onClose, tripId, kind }: Bo
|
||||
const mouseDownTarget = useRef<EventTarget | null>(null)
|
||||
|
||||
const [files, setFiles] = useState<File[]>([])
|
||||
// A booking document shared to TREK lands here already chosen.
|
||||
useEffect(() => {
|
||||
if (!isOpen) return
|
||||
const shared = useSharedImportStore.getState().file
|
||||
if (shared) setFiles([useSharedImportStore.getState().take() ?? shared])
|
||||
}, [isOpen])
|
||||
const [isDragOver, setIsDragOver] = useState(false)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
@@ -9,6 +9,7 @@ import { pickDockTabs } from './dockTabs'
|
||||
import MBadge from '../../components/MBadge'
|
||||
import MIconBtn from '../../components/MIconBtn'
|
||||
import { useActivePill } from '../../components/useActivePill'
|
||||
import { useSharedImportStore } from '../../../native/sharedFiles'
|
||||
import MPlanTimeline from './plan/MPlanTimeline'
|
||||
import MMapArea from './map/MMapArea'
|
||||
import MPlacesBrowser from './places/MPlacesBrowser'
|
||||
@@ -291,6 +292,14 @@ export default function MTripShell({
|
||||
})
|
||||
}, [planner.selectedDayId, days, dayRail])
|
||||
// The active day's pill glides to the next chip rather than jumping there.
|
||||
// A booking document shared to TREK, and this trip picked for it: open the import.
|
||||
const sharedTripId = useSharedImportStore(s => s.tripId)
|
||||
useEffect(() => {
|
||||
if (sharedTripId == null || sharedTripId !== Number(tripId)) return
|
||||
planner.setBookingImportKind('bookings')
|
||||
planner.setShowBookingImport(true)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [sharedTripId, tripId])
|
||||
const dayPill = useActivePill(dayRail, '[aria-current="true"]', [planner.selectedDayId, days, dayRail, language])
|
||||
|
||||
const trTab = planner.activeTab
|
||||
|
||||
@@ -23,6 +23,7 @@ vi.mock('./capabilities', () => ({
|
||||
loadNativeCapabilities: vi.fn(async () => ({})),
|
||||
}));
|
||||
vi.mock('./geolocation', () => ({ installNativeGeolocation: vi.fn() }));
|
||||
vi.mock('./sharedFiles', () => ({ startSharedFiles: vi.fn(async () => {}) }));
|
||||
vi.mock('../mobile/overlayStack', () => ({ closeTopOverlay: vi.fn(() => false) }));
|
||||
|
||||
function backButtonHandler(): (event: { canGoBack: boolean }) => void {
|
||||
|
||||
@@ -9,6 +9,7 @@ import { installNativeGeolocation } from './geolocation';
|
||||
import { keepOfflineShellFresh } from './offlineShell';
|
||||
import { isNativeApp, isNativeIos } from './platform';
|
||||
import { reportNativeFailure } from './reportFailure';
|
||||
import { startSharedFiles } from './sharedFiles';
|
||||
import { isUnimplemented } from './trekShell';
|
||||
|
||||
/** Long enough that the warm-up never competes with the first screen's requests. */
|
||||
@@ -27,6 +28,8 @@ export function startNativeApp(): void {
|
||||
void checkAppUpdate(fetchServerFeatures);
|
||||
// The app's own location under navigator.geolocation, where the binary has it.
|
||||
void loadNativeCapabilities().then(() => installNativeGeolocation());
|
||||
// Booking documents shared to TREK, waiting for a trip to import into.
|
||||
void startSharedFiles();
|
||||
|
||||
// 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).
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { hasNativeFeature } from './capabilities';
|
||||
import { startSharedFiles, toFile, useSharedImportStore } from './sharedFiles';
|
||||
import { TrekShell } from './trekShell';
|
||||
|
||||
vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn(), loadNativeCapabilities: vi.fn(async () => ({})) }));
|
||||
vi.mock('./trekShell', () => ({
|
||||
TrekShell: { addListener: vi.fn(async () => ({ remove: async () => {} })), takeSharedFile: vi.fn() },
|
||||
isUnimplemented: () => false,
|
||||
}));
|
||||
|
||||
const PDF = { name: 'booking.pdf', mimeType: 'application/pdf', data: btoa('%PDF-1.4 hello') };
|
||||
|
||||
beforeEach(() => {
|
||||
useSharedImportStore.setState({ file: null, tripId: null });
|
||||
vi.mocked(hasNativeFeature).mockReturnValue(true);
|
||||
vi.mocked(TrekShell.takeSharedFile).mockReset().mockResolvedValue({ file: null });
|
||||
});
|
||||
|
||||
describe('shared booking documents', () => {
|
||||
it('turns the base64 the native side sends into a File', async () => {
|
||||
const file = toFile(PDF);
|
||||
expect(file.name).toBe('booking.pdf');
|
||||
expect(file.type).toBe('application/pdf');
|
||||
expect(await file.text()).toBe('%PDF-1.4 hello');
|
||||
});
|
||||
|
||||
it('picks up a document shared before the UI ran, and the next ones as they come', async () => {
|
||||
vi.mocked(TrekShell.takeSharedFile).mockResolvedValue({ file: PDF });
|
||||
await startSharedFiles();
|
||||
expect(useSharedImportStore.getState().file?.name).toBe('booking.pdf');
|
||||
|
||||
const listener = vi.mocked(TrekShell.addListener).mock.calls[0][1] as (p: typeof PDF) => void;
|
||||
listener({ ...PDF, name: 'train.ics', mimeType: 'text/calendar' });
|
||||
expect(useSharedImportStore.getState().file?.name).toBe('train.ics');
|
||||
});
|
||||
|
||||
it('hands the file over once a trip is picked, and empties the queue', () => {
|
||||
useSharedImportStore.getState().setFile(toFile(PDF));
|
||||
useSharedImportStore.getState().chooseTrip(7);
|
||||
expect(useSharedImportStore.getState().tripId).toBe(7);
|
||||
expect(useSharedImportStore.getState().take()?.name).toBe('booking.pdf');
|
||||
expect(useSharedImportStore.getState()).toMatchObject({ file: null, tripId: null });
|
||||
});
|
||||
|
||||
it('does nothing in a binary without the feature', async () => {
|
||||
vi.mocked(hasNativeFeature).mockReturnValue(false);
|
||||
vi.mocked(TrekShell.addListener).mockClear();
|
||||
await startSharedFiles();
|
||||
expect(TrekShell.addListener).not.toHaveBeenCalled();
|
||||
expect(TrekShell.takeSharedFile).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { create } from 'zustand';
|
||||
import { hasNativeFeature, loadNativeCapabilities } from './capabilities';
|
||||
import { reportNativeFailure } from './reportFailure';
|
||||
import { TrekShell, isUnimplemented, type SharedFilePayload } from './trekShell';
|
||||
|
||||
/**
|
||||
* Booking documents shared to TREK ("Open in TREK" on a PDF, a calendar entry,
|
||||
* a Wallet pass or a mail). The native side hands them over as base64
|
||||
* (TrekShell.takeSharedFile and the sharedFile event); here they become a File
|
||||
* waiting for a trip: NativeImportSheet asks which one, and the trip's booking
|
||||
* import opens with the file already chosen (BookingImportModal).
|
||||
*/
|
||||
interface SharedImportState {
|
||||
file: File | null;
|
||||
/** The trip the user picked for it; the planner of that trip takes it from here. */
|
||||
tripId: number | null;
|
||||
setFile: (file: File | null) => void;
|
||||
chooseTrip: (tripId: number) => void;
|
||||
/** The booking import took the file: the queue is empty again. */
|
||||
take: () => File | null;
|
||||
}
|
||||
|
||||
export const useSharedImportStore = create<SharedImportState>((set, get) => ({
|
||||
file: null,
|
||||
tripId: null,
|
||||
setFile: (file) => set({ file, tripId: null }),
|
||||
chooseTrip: (tripId) => set({ tripId }),
|
||||
take: () => {
|
||||
const { file } = get();
|
||||
set({ file: null, tripId: null });
|
||||
return file;
|
||||
},
|
||||
}));
|
||||
|
||||
export function toFile(payload: SharedFilePayload): File {
|
||||
const binary = atob(payload.data);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
||||
return new File([bytes], payload.name || 'booking', { type: payload.mimeType || 'application/octet-stream' });
|
||||
}
|
||||
|
||||
/** Picks up a document shared before the UI ran, and listens for the next ones. */
|
||||
export async function startSharedFiles(): Promise<void> {
|
||||
await loadNativeCapabilities();
|
||||
if (!hasNativeFeature('sharedFiles')) return;
|
||||
const accept = (payload: SharedFilePayload | null) => {
|
||||
if (payload?.data) useSharedImportStore.getState().setFile(toFile(payload));
|
||||
};
|
||||
void TrekShell.addListener('sharedFile', accept);
|
||||
try {
|
||||
accept((await TrekShell.takeSharedFile()).file);
|
||||
} catch (err) {
|
||||
if (!isUnimplemented(err)) reportNativeFailure(err);
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,20 @@ export interface TrekShellPlugin {
|
||||
event: 'location',
|
||||
listener: (payload: NativeLocationPayload) => void
|
||||
): Promise<{ remove: () => Promise<void> }>;
|
||||
addListener(
|
||||
event: 'sharedFile',
|
||||
listener: (payload: SharedFilePayload) => void
|
||||
): Promise<{ remove: () => Promise<void> }>;
|
||||
/** Feature sharedFiles: the booking document shared to TREK before the UI ran. */
|
||||
takeSharedFile(): Promise<{ file: SharedFilePayload | null }>;
|
||||
}
|
||||
|
||||
/** A document shared to TREK, as the native side reads it. */
|
||||
export interface SharedFilePayload {
|
||||
name: string;
|
||||
mimeType: string;
|
||||
/** base64 */
|
||||
data: string;
|
||||
}
|
||||
|
||||
/** A position, or an error shaped like GeolocationPositionError (1 denied, 2 unavailable). */
|
||||
|
||||
Reference in New Issue
Block a user