mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-22 03:50:30 +00:00
feat(native): a link shared to TREK can go to the trip's links
A page or a link shared from another app now carries its address. The app asks whether to keep it among the trip's links (Collab, Links) or to read a booking from it. A link whose page the phone cannot read is no longer refused: it is handed over as the link alone, which can be kept. With Collab off a page is read as a booking, as before.
This commit is contained in:
@@ -1,10 +1,15 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import { useSharedImportStore } from '../../native/sharedFiles';
|
||||
import { act, fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import { saveSharedLink, useSharedImportStore } from '../../native/sharedFiles';
|
||||
import { tripRepo } from '../../repo/tripRepo';
|
||||
import { useAddonStore } from '../../store/addonStore';
|
||||
import NativeImportSheet from './NativeImportSheet';
|
||||
|
||||
const navigate = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../../native/sharedFiles', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../native/sharedFiles')>()),
|
||||
saveSharedLink: vi.fn(),
|
||||
}));
|
||||
vi.mock('react-router', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('react-router')>()),
|
||||
useNavigate: () => navigate,
|
||||
@@ -14,7 +19,9 @@ beforeEach(() => {
|
||||
// A second spyOn returns the first spy with its calls; start every test clean.
|
||||
vi.restoreAllMocks();
|
||||
navigate.mockReset();
|
||||
useSharedImportStore.setState({ file: null, tripId: null });
|
||||
useSharedImportStore.setState({ file: null, tripId: null, link: null });
|
||||
useAddonStore.setState({ addons: [{ id: 'collab', enabled: true }] as never, loaded: true });
|
||||
vi.mocked(saveSharedLink).mockReset().mockResolvedValue();
|
||||
vi.spyOn(tripRepo, 'list').mockResolvedValue({
|
||||
trips: [
|
||||
{ id: 1, title: 'Past trip', start_date: '2020-01-01', end_date: '2020-01-05' },
|
||||
@@ -24,6 +31,14 @@ beforeEach(() => {
|
||||
} as unknown as Awaited<ReturnType<typeof tripRepo.list>>);
|
||||
});
|
||||
|
||||
const page = () => new File(['<html></html>'], 'hotel.html', { type: 'text/html' });
|
||||
const bareLink = () => new File(['https://hotel.example/stay'], 'link.url', { type: 'text/uri-list' });
|
||||
const link = (presetTripId: number | null = null) => ({
|
||||
url: 'https://hotel.example/stay',
|
||||
title: 'Hotel Kanra',
|
||||
presetTripId,
|
||||
});
|
||||
|
||||
describe('NativeImportSheet', () => {
|
||||
it('asks which trip a shared document goes to, upcoming trips first, and opens it there', async () => {
|
||||
render(<NativeImportSheet />);
|
||||
@@ -49,6 +64,58 @@ describe('NativeImportSheet', () => {
|
||||
expect(navigate).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('asks what a shared page is for, and keeps it among the links of the trip picked', async () => {
|
||||
render(<NativeImportSheet />);
|
||||
act(() => useSharedImportStore.getState().setFile(page(), link()));
|
||||
expect(screen.getByText('native.share.linkTitle')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /Japan/ })).not.toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /native\.share\.saveLink/ }));
|
||||
expect(screen.getByText('native.share.linkTrip')).toBeInTheDocument();
|
||||
fireEvent.click(await screen.findByRole('button', { name: /Japan/ }));
|
||||
await waitFor(() => expect(navigate).toHaveBeenCalledWith('/trips/2?tab=collab'));
|
||||
expect(saveSharedLink).toHaveBeenCalledWith(2, link());
|
||||
expect(useSharedImportStore.getState().file).toBeNull();
|
||||
});
|
||||
|
||||
it('reads a booking from the page when that is asked for', async () => {
|
||||
render(<NativeImportSheet />);
|
||||
act(() => useSharedImportStore.getState().setFile(page(), link()));
|
||||
fireEvent.click(screen.getByRole('button', { name: /native\.share\.readBooking/ }));
|
||||
fireEvent.click(await screen.findByRole('button', { name: /Japan/ }));
|
||||
expect(useSharedImportStore.getState().tripId).toBe(2);
|
||||
expect(navigate).toHaveBeenCalledWith('/trips/2');
|
||||
expect(saveSharedLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps a bare link in the trip the share sheet picked, with nothing to ask', async () => {
|
||||
render(<NativeImportSheet />);
|
||||
act(() => useSharedImportStore.getState().setFile(bareLink(), link(2)));
|
||||
await waitFor(() => expect(saveSharedLink).toHaveBeenCalledWith(2, link(2)));
|
||||
await waitFor(() => expect(navigate).toHaveBeenCalledWith('/trips/2?tab=collab'));
|
||||
});
|
||||
|
||||
it('with Collab off, a page is read as a booking and a bare link is explained', async () => {
|
||||
useAddonStore.setState({ addons: [], loaded: true });
|
||||
render(<NativeImportSheet />);
|
||||
act(() => useSharedImportStore.getState().setFile(page(), link()));
|
||||
expect(screen.queryByText('native.share.linkTitle')).not.toBeInTheDocument();
|
||||
expect(await screen.findAllByRole('button', { name: /Japan|Past trip/ })).toHaveLength(2);
|
||||
|
||||
act(() => useSharedImportStore.getState().setFile(bareLink(), link()));
|
||||
expect(screen.getByText('native.share.linkUnsupported')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /Japan/ })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('says so when the link cannot be saved, and offers the trips again', async () => {
|
||||
vi.mocked(saveSharedLink).mockRejectedValue(new Error('offline'));
|
||||
render(<NativeImportSheet />);
|
||||
act(() => useSharedImportStore.getState().setFile(bareLink(), link(2)));
|
||||
expect(await screen.findByRole('button', { name: /Japan/ })).toBeEnabled();
|
||||
expect(navigate).not.toHaveBeenCalled();
|
||||
expect(useSharedImportStore.getState().file).not.toBeNull();
|
||||
});
|
||||
|
||||
it('stays closed with nothing shared', () => {
|
||||
render(<NativeImportSheet />);
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
/**
|
||||
* 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.
|
||||
* NativeImportSheet: something 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.
|
||||
*
|
||||
* A web page or a link is asked about first: kept among the trip's links
|
||||
* (Collaboration, Links), or read as a booking. A bare link, whose page the phone
|
||||
* could not read, can only be kept; with Collaboration off, a page can only be read.
|
||||
*/
|
||||
import { ChevronRight, FileText } from 'lucide-react';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { ChevronRight, FileText, Link2, ScanText } from 'lucide-react';
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { useLocation, useNavigate } from 'react-router';
|
||||
import { useToast } from '../../components/shared/Toast';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useSharedImportStore } from '../../native/sharedFiles';
|
||||
import { saveSharedLink, useSharedImportStore } from '../../native/sharedFiles';
|
||||
import { tripRepo } from '../../repo/tripRepo';
|
||||
import { useAddonStore } from '../../store/addonStore';
|
||||
import { offlineOr } from '../../utils/needsConnection';
|
||||
import { TileHeader } from '../screens/trip/sheets/MTripSheetUi';
|
||||
import MSheet from './MSheet';
|
||||
|
||||
@@ -19,15 +26,42 @@ interface TripRow {
|
||||
end_date?: string | null;
|
||||
}
|
||||
|
||||
type LinkChoice = 'link' | 'booking';
|
||||
|
||||
/** What to offer for a shared link: the links when Collaboration is on, the import when there is a page to read. */
|
||||
function linkChoicesOf(file: File, collabOn: boolean): LinkChoice[] {
|
||||
const choices: LinkChoice[] = [];
|
||||
if (collabOn) choices.push('link');
|
||||
if (file.type !== 'text/uri-list') choices.push('booking');
|
||||
return choices;
|
||||
}
|
||||
|
||||
export default function NativeImportSheet(): React.ReactElement | null {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const navigate = useNavigate();
|
||||
const { pathname } = useLocation();
|
||||
const file = useSharedImportStore((s) => s.file);
|
||||
const tripId = useSharedImportStore((s) => s.tripId);
|
||||
const link = useSharedImportStore((s) => s.link);
|
||||
const chooseTrip = useSharedImportStore((s) => s.chooseTrip);
|
||||
const setFile = useSharedImportStore((s) => s.setFile);
|
||||
const collabOn = useAddonStore((s) => s.isEnabled('collab'));
|
||||
const [trips, setTrips] = useState<TripRow[]>([]);
|
||||
const [picked, setPicked] = useState<LinkChoice | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
// Each shared item is asked about afresh.
|
||||
useEffect(() => {
|
||||
setPicked(null);
|
||||
setSaving(false);
|
||||
}, [file]);
|
||||
|
||||
const choices = file && link ? linkChoicesOf(file, collabOn) : [];
|
||||
// With one way to go there is nothing to ask.
|
||||
const choice: LinkChoice | null = !link ? 'booking' : (picked ?? (choices.length === 1 ? choices[0] : null));
|
||||
const asking = !!link && choice == null && choices.length > 1;
|
||||
const nowhere = !!link && choices.length === 0;
|
||||
|
||||
const open = !!file && tripId == null;
|
||||
|
||||
@@ -54,41 +88,129 @@ export default function NativeImportSheet(): React.ReactElement | null {
|
||||
void navigate(`/trips/${tripId}`);
|
||||
}, [file, tripId, pathname, navigate]);
|
||||
|
||||
const pick = (id: number) => chooseTrip(id);
|
||||
const saveLink = async (id: number) => {
|
||||
if (!link || saving) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
await saveSharedLink(id, link);
|
||||
toast.success(t('native.share.linkSaved'));
|
||||
setFile(null);
|
||||
void navigate(`/trips/${id}?tab=collab`);
|
||||
} catch {
|
||||
toast.error(offlineOr(t, t('common.error')));
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
// The trip the share sheet picked, used as soon as it is clear what the link is for.
|
||||
// saveLink is a fresh function on every render, so the effect reaches it through a
|
||||
// ref and runs on the trip and the choice alone.
|
||||
const preset = link?.presetTripId ?? null;
|
||||
const saveLinkRef = useRef(saveLink);
|
||||
saveLinkRef.current = saveLink;
|
||||
useEffect(() => {
|
||||
if (preset == null || choice == null || !file) return;
|
||||
if (choice === 'booking') chooseTrip(preset);
|
||||
else void saveLinkRef.current(preset);
|
||||
}, [preset, choice, file, chooseTrip]);
|
||||
|
||||
const pick = (id: number) => (choice === 'link' ? void saveLink(id) : chooseTrip(id));
|
||||
// While the picked trip takes the link, there is nothing to choose; should it fail, the trips come back.
|
||||
const showTrips = !asking && !nowhere && !(preset != null && choice === 'link' && saving);
|
||||
|
||||
return (
|
||||
<MSheet open={open} onClose={() => setFile(null)} variant="bottom" ariaLabel={t('native.share.title')}>
|
||||
<div className="px-[18px] pb-4 pt-4">
|
||||
<div className="mb-3">
|
||||
<TileHeader
|
||||
icon={<FileText size={19} strokeWidth={1.8} />}
|
||||
title={t('native.share.title')}
|
||||
sub={file?.name}
|
||||
icon={link ? <Link2 size={19} strokeWidth={1.8} /> : <FileText size={19} strokeWidth={1.8} />}
|
||||
title={t(
|
||||
asking ? 'native.share.linkTitle' : choice === 'link' ? 'native.share.linkTrip' : 'native.share.title'
|
||||
)}
|
||||
sub={link ? link.title : file?.name}
|
||||
onClose={() => setFile(null)}
|
||||
closeLabel={t('common.close')}
|
||||
/>
|
||||
</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-[length:calc(14px*var(--fs-scale-body,1))] 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-[length:calc(12px*var(--fs-scale-body,1))] text-m-muted">
|
||||
{t('native.share.noTrips')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{asking && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<ChoiceRow
|
||||
icon={<Link2 size={17} strokeWidth={2} />}
|
||||
label={t('native.share.saveLink')}
|
||||
hint={t('native.share.saveLinkHint')}
|
||||
onClick={() => setPicked('link')}
|
||||
/>
|
||||
<ChoiceRow
|
||||
icon={<ScanText size={17} strokeWidth={2} />}
|
||||
label={t('native.share.readBooking')}
|
||||
hint={t('native.share.readBookingHint')}
|
||||
onClick={() => setPicked('booking')}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{nowhere && (
|
||||
<p className="px-1 text-[length:calc(12px*var(--fs-scale-body,1))] text-m-muted">
|
||||
{t('native.share.linkUnsupported')}
|
||||
</p>
|
||||
)}
|
||||
{showTrips && (
|
||||
<div className="flex max-h-[50vh] flex-col gap-2 overflow-y-auto">
|
||||
{trips.map((trip) => (
|
||||
<button
|
||||
key={trip.id}
|
||||
type="button"
|
||||
disabled={saving}
|
||||
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] disabled:opacity-50"
|
||||
>
|
||||
<span className="min-w-0 flex-1 truncate text-[length:calc(14px*var(--fs-scale-body,1))] 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-[length:calc(12px*var(--fs-scale-body,1))] text-m-muted">
|
||||
{t('native.share.noTrips')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</MSheet>
|
||||
);
|
||||
}
|
||||
|
||||
function ChoiceRow({
|
||||
icon,
|
||||
label,
|
||||
hint,
|
||||
onClick,
|
||||
}: {
|
||||
icon: React.ReactNode;
|
||||
label: string;
|
||||
hint: string;
|
||||
onClick: () => void;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
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="flex h-9 w-9 flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] text-m-ink"
|
||||
aria-hidden="true"
|
||||
>
|
||||
{icon}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-[length:calc(14px*var(--fs-scale-body,1))] font-bold text-m-ink">
|
||||
{label}
|
||||
</span>
|
||||
<span className="block truncate text-[length:calc(12px*var(--fs-scale-body,1))] text-m-muted">{hint}</span>
|
||||
</span>
|
||||
<ChevronRight size={16} className="flex-none text-m-faint" aria-hidden="true" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { hasNativeFeature } from './capabilities';
|
||||
import { startSharedFiles, toFile, useSharedImportStore } from './sharedFiles';
|
||||
import { linkOf, startSharedFiles, toFile, useSharedImportStore } from './sharedFiles';
|
||||
import { TrekShell } from './trekShell';
|
||||
|
||||
vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn(), loadNativeCapabilities: vi.fn(async () => ({})) }));
|
||||
@@ -12,7 +12,7 @@ vi.mock('./trekShell', () => ({
|
||||
const PDF = { name: 'booking.pdf', mimeType: 'application/pdf', data: btoa('%PDF-1.4 hello') };
|
||||
|
||||
beforeEach(() => {
|
||||
useSharedImportStore.setState({ file: null, tripId: null });
|
||||
useSharedImportStore.setState({ file: null, tripId: null, link: null });
|
||||
vi.mocked(hasNativeFeature).mockReturnValue(true);
|
||||
vi.mocked(TrekShell.takeSharedFile).mockReset().mockResolvedValue({ file: null });
|
||||
});
|
||||
@@ -50,6 +50,36 @@ describe('shared booking documents', () => {
|
||||
expect(useSharedImportStore.getState().file?.name).toBe('booking.pdf');
|
||||
});
|
||||
|
||||
it('keeps the address of a shared page, and holds the picked trip back until the link is decided on', async () => {
|
||||
const page = { name: 'hotel.html', mimeType: 'text/html', data: btoa('<html></html>') };
|
||||
vi.mocked(TrekShell.takeSharedFile).mockResolvedValue({
|
||||
file: { ...page, tripId: 12, url: 'https://hotel.example/stay', title: 'Hotel Kanra' },
|
||||
});
|
||||
await startSharedFiles();
|
||||
expect(useSharedImportStore.getState()).toMatchObject({
|
||||
tripId: null,
|
||||
link: { url: 'https://hotel.example/stay', title: 'Hotel Kanra', presetTripId: 12 },
|
||||
});
|
||||
});
|
||||
|
||||
it('takes http(s) links only, titled by the host when the page has none', () => {
|
||||
const base = { name: 'link.url', mimeType: 'text/uri-list', data: '' };
|
||||
expect(linkOf({ ...base, url: 'https://maps.app.goo.gl/x' })).toEqual({
|
||||
url: 'https://maps.app.goo.gl/x',
|
||||
title: 'maps.app.goo.gl',
|
||||
presetTripId: null,
|
||||
});
|
||||
expect(linkOf({ ...base, url: 'javascript:alert(1)' })).toBeNull();
|
||||
expect(linkOf({ ...base, url: 'not a url' })).toBeNull();
|
||||
expect(linkOf(base)).toBeNull();
|
||||
});
|
||||
|
||||
it('forgets the link along with the file', () => {
|
||||
useSharedImportStore.getState().setFile(toFile(PDF), { url: 'https://a.example/', title: 'A', presetTripId: null });
|
||||
useSharedImportStore.getState().setFile(null, { url: 'https://a.example/', title: 'A', presetTripId: null });
|
||||
expect(useSharedImportStore.getState().link).toBeNull();
|
||||
});
|
||||
|
||||
it('does nothing in a binary without the feature', async () => {
|
||||
vi.mocked(hasNativeFeature).mockReturnValue(false);
|
||||
vi.mocked(TrekShell.addListener).mockClear();
|
||||
|
||||
@@ -1,20 +1,33 @@
|
||||
import { create } from 'zustand';
|
||||
import { collabApi } from '../api/client';
|
||||
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).
|
||||
* What was shared to TREK: a booking document ("Open in TREK" on a PDF, a
|
||||
* calendar entry, a Wallet pass or a mail), or a web page or link. The native
|
||||
* side hands it over as base64 (TrekShell.takeSharedFile and the sharedFile
|
||||
* event); here it becomes a File waiting for a trip: NativeImportSheet asks
|
||||
* which one, and the trip's booking import opens with the file already chosen
|
||||
* (BookingImportModal). A page or a link also carries its address, and the
|
||||
* sheet asks first whether it goes to the trip's links or is read as a booking.
|
||||
*/
|
||||
|
||||
/** A shared page or link, which can be kept among a trip's links. */
|
||||
export interface SharedLink {
|
||||
url: string;
|
||||
title: string;
|
||||
/** The trip the share sheet picked for it, held back until it is clear what to do with the link. */
|
||||
presetTripId: number | null;
|
||||
}
|
||||
|
||||
interface SharedImportState {
|
||||
file: File | null;
|
||||
/** The trip the user picked for it; the planner of that trip takes it from here. */
|
||||
/** The trip whose booking import takes the file; the planner of that trip takes it from here. */
|
||||
tripId: number | null;
|
||||
setFile: (file: File | null) => void;
|
||||
link: SharedLink | null;
|
||||
setFile: (file: File | null, link?: SharedLink | null) => void;
|
||||
chooseTrip: (tripId: number) => void;
|
||||
/** The booking import took the file: the queue is empty again. */
|
||||
take: () => File | null;
|
||||
@@ -23,11 +36,12 @@ interface SharedImportState {
|
||||
export const useSharedImportStore = create<SharedImportState>((set, get) => ({
|
||||
file: null,
|
||||
tripId: null,
|
||||
setFile: (file) => set({ file, tripId: null }),
|
||||
link: null,
|
||||
setFile: (file, link = null) => set({ file, tripId: null, link: file ? link : null }),
|
||||
chooseTrip: (tripId) => set({ tripId }),
|
||||
take: () => {
|
||||
const { file } = get();
|
||||
set({ file: null, tripId: null });
|
||||
set({ file: null, tripId: null, link: null });
|
||||
return file;
|
||||
},
|
||||
}));
|
||||
@@ -39,6 +53,34 @@ export function toFile(payload: SharedFilePayload): File {
|
||||
return new File([bytes], payload.name || 'booking', { type: payload.mimeType || 'application/octet-stream' });
|
||||
}
|
||||
|
||||
/** The link a payload carries: an http(s) address only, titled by the page or its host. */
|
||||
export function linkOf(payload: SharedFilePayload): SharedLink | null {
|
||||
const raw = payload.url?.trim();
|
||||
if (!raw) return null;
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (url.protocol !== 'https:' && url.protocol !== 'http:') return null;
|
||||
const title = payload.title?.trim() || url.host;
|
||||
return {
|
||||
url: url.href,
|
||||
title: title.slice(0, 200),
|
||||
presetTripId: typeof payload.tripId === 'number' ? payload.tripId : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps a shared link among the trip's links (Collaboration, Links), titled as
|
||||
* the page is. Online only, like adding a link in the app: the caller says so
|
||||
* when it fails. The trip's other members get it live over the WebSocket.
|
||||
*/
|
||||
export async function saveSharedLink(tripId: number, link: SharedLink): Promise<void> {
|
||||
await collabApi.createLink(tripId, { title: link.title, url: link.url });
|
||||
}
|
||||
|
||||
/** Picks up a document shared before the UI ran, and listens for the next ones. */
|
||||
export async function startSharedFiles(): Promise<void> {
|
||||
await loadNativeCapabilities();
|
||||
@@ -46,9 +88,11 @@ export async function startSharedFiles(): Promise<void> {
|
||||
const accept = (payload: SharedFilePayload | null) => {
|
||||
if (!payload?.data) return;
|
||||
const store = useSharedImportStore.getState();
|
||||
store.setFile(toFile(payload));
|
||||
// The share sheet asked for the trip already; NativeImportSheet opens it.
|
||||
if (typeof payload.tripId === 'number') store.chooseTrip(payload.tripId);
|
||||
const link = linkOf(payload);
|
||||
store.setFile(toFile(payload), link);
|
||||
// The share sheet asked for the trip already; NativeImportSheet opens it. A link
|
||||
// keeps that trip in hand instead, until the sheet knows what to do with it.
|
||||
if (!link && typeof payload.tripId === 'number') store.chooseTrip(payload.tripId);
|
||||
};
|
||||
void TrekShell.addListener('sharedFile', accept);
|
||||
try {
|
||||
|
||||
@@ -163,6 +163,10 @@ export interface SharedFilePayload {
|
||||
data: string;
|
||||
/** Set when the share sheet already asked which trip it belongs to (feature shareSheet). */
|
||||
tripId?: number;
|
||||
/** The http(s) address of a shared page or link, which can go to the trip's links instead. */
|
||||
url?: string;
|
||||
/** The page's title, for that link. */
|
||||
title?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user