feat(mobile): add a place shared from Google Maps or Amap to a trip

A place shared from a maps app to TREK could only be kept among a trip's
links or read as a booking. A map link is now first offered as a place: after
the trip is picked, its new place sheet opens with the link in the search,
which looks it up at once through the existing resolver, so name, address
and position are filled in and only need saving. Other links are offered as
before.

Addresses discussion #2582.
This commit is contained in:
Maurice
2026-11-27 23:21:13 +01:00
parent 20d10d765d
commit 57fb2cf47b
35 changed files with 234 additions and 27 deletions
@@ -22,7 +22,7 @@ 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, link: null });
useSharedImportStore.setState({ file: null, tripId: null, link: null, placeLink: null });
useAddonStore.setState({ addons: [{ id: 'collab', enabled: true }] as never, loaded: true });
useTripAddonsStore.setState({ trips: {} });
// Every trip follows the instance switch unless a test says otherwise; answered at once, so no read outlives its test.
@@ -217,6 +217,35 @@ describe('NativeImportSheet', () => {
expect(saveSharedLink).toHaveBeenCalledTimes(1);
});
it('offers a shared map link as a place first, and hands it to the trip picked (#2582)', async () => {
const maps = {
url: 'https://www.google.com/maps/place/Time+Out+Market',
title: 'Time Out Market',
presetTripId: null,
};
render(<NativeImportSheet />);
act(() => useSharedImportStore.getState().setFile(page(), maps));
const choices = await screen.findAllByRole('button', {
name: /Add it as a place|Save to the trip's links|Read a booking/,
});
expect(choices[0]).toHaveAccessibleName(/Add it as a place/);
fireEvent.click(choices[0]);
expect(screen.getByText('Add the place to which trip?')).toBeInTheDocument();
fireEvent.click(await screen.findByRole('button', { name: /Japan/ }));
expect(useSharedImportStore.getState().placeLink).toEqual({ tripId: 2, url: maps.url });
expect(useSharedImportStore.getState().file).toBeNull();
expect(navigate).toHaveBeenCalledWith('/trips/2');
expect(saveSharedLink).not.toHaveBeenCalled();
});
it('offers no place for a link that is not a map', async () => {
render(<NativeImportSheet />);
act(() => useSharedImportStore.getState().setFile(page(), link()));
await screen.findByText('What should TREK do with this link?');
expect(screen.queryByRole('button', { name: /Add it as a place/ })).not.toBeInTheDocument();
});
it('stays closed with nothing shared', () => {
render(<NativeImportSheet />);
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
@@ -7,11 +7,14 @@
* (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.
* Collaboration counts per trip: a link goes only to a trip that has it on.
* A map link (Google Maps, Amap) can also become a place of the
* trip (#2582): the trip's new place sheet opens and looks the link up.
*/
import { ChevronRight, FileText, Link2, ScanText } from 'lucide-react';
import { ChevronRight, FileText, Link2, MapPin, ScanText } from 'lucide-react';
import React, { useEffect, useEffectEvent, useRef, useState } from 'react';
import { useLocation, useNavigate } from 'react-router';
import { useShallow } from 'zustand/react/shallow';
import { isMapUrl } from '../../components/Planner/PlaceFormModal.helpers';
import { useToast } from '../../components/shared/Toast';
import { useTranslation } from '../../i18n';
import { saveSharedLink, useSharedImportStore, type SharedLink } from '../../native/sharedFiles';
@@ -31,11 +34,15 @@ interface TripRow {
end_date?: string | null;
}
type LinkChoice = 'link' | 'booking';
type LinkChoice = 'link' | 'booking' | 'place';
/** 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[] {
/**
* What to offer for a shared link: a place first when it points at a map, the links
* when Collaboration is on, the import when there is a page to read.
*/
function linkChoicesOf(file: File, collabOn: boolean, url: string): LinkChoice[] {
const choices: LinkChoice[] = [];
if (isMapUrl(url)) choices.push('place');
if (collabOn) choices.push('link');
if (file.type !== 'text/uri-list') choices.push('booking');
return choices;
@@ -54,19 +61,22 @@ interface StageInput {
/** Where the sheet stands for the shared item: what it asks, and what a tap on a trip does. */
function stageOf({ file, link, collabOn, picked, presetFailed, settled }: StageInput) {
if (!file || !link) return { choice: 'booking' as LinkChoice | null, asking: false, nowhere: false, showTrips: true };
if (!settled) return { choice: null, asking: false, nowhere: false, showTrips: false };
const choices = linkChoicesOf(file, collabOn);
const none: LinkChoice[] = [];
if (!file || !link)
return { choice: 'booking' as LinkChoice | null, asking: false, nowhere: false, choices: none, showTrips: true };
if (!settled) return { choice: null, asking: false, nowhere: false, choices: none, showTrips: false };
const choices = linkChoicesOf(file, collabOn, link.url);
const choice = picked ?? (choices.length === 1 ? choices[0] : null);
const asking = choice == null && choices.length > 1;
const nowhere = choices.length === 0;
// While the share sheet's trip takes the link there is nothing to choose.
const presetTakes = link.presetTripId != null && choice === 'link' && !presetFailed;
return { choice, asking, nowhere, showTrips: !asking && !nowhere && !presetTakes };
return { choice, asking, nowhere, choices, showTrips: !asking && !nowhere && !presetTakes };
}
function sheetTitle(t: (key: string) => string, asking: boolean, choice: LinkChoice | null): string {
if (asking) return t('native.share.linkTitle');
if (choice === 'place') return t('native.share.placeTrip');
return choice === 'link' ? t('native.share.linkTrip') : t('native.share.title');
}
@@ -151,6 +161,7 @@ export default function NativeImportSheet(): React.ReactElement | null {
const tripId = useSharedImportStore((s) => s.tripId);
const link = useSharedImportStore((s) => s.link);
const chooseTrip = useSharedImportStore((s) => s.chooseTrip);
const choosePlaceTrip = useSharedImportStore((s) => s.choosePlaceTrip);
const setFile = useSharedImportStore((s) => s.setFile);
const instanceCollab = useAddonStore((s) => s.isEnabled('collab'));
const open = !!file && tripId == null;
@@ -164,7 +175,7 @@ export default function NativeImportSheet(): React.ReactElement | null {
// The save in flight, kept off the state: it guards a second tap, it is not shown.
const savingRef = useRef<File | null>(null);
const picked = pick && pick.file === file ? pick.choice : null;
const { choice, asking, nowhere, showTrips } = stageOf({
const { choice, asking, nowhere, choices, showTrips } = stageOf({
file,
link,
collabOn,
@@ -198,17 +209,28 @@ export default function NativeImportSheet(): React.ReactElement | null {
);
};
// The trip's new place sheet takes the map link from here (MTripShell, MPlaceEditSheet).
const addPlace = (id: number) => {
choosePlaceTrip(id);
void navigate(`/trips/${id}`);
};
// The trip the share sheet picked, used as soon as it is clear what the link is for.
const preset = link?.presetTripId ?? null;
const applyPreset = useEffectEvent((id: number, use: LinkChoice) => {
if (use === 'booking') chooseTrip(id);
else if (use === 'place') addPlace(id);
else if (failedFile !== file) saveLink(id);
});
useEffect(() => {
if (preset != null && choice != null && file) applyPreset(preset, choice);
}, [preset, choice, file]);
const pickTrip = (id: number) => (choice === 'link' ? saveLink(id) : chooseTrip(id));
const pickTrip = (id: number) => {
if (choice === 'link') saveLink(id);
else if (choice === 'place') addPlace(id);
else chooseTrip(id);
};
return (
<MSheet open={open} onClose={() => setFile(null)} variant="bottom" ariaLabel={t('native.share.title')}>
@@ -222,7 +244,7 @@ export default function NativeImportSheet(): React.ReactElement | null {
closeLabel={t('common.close')}
/>
</div>
{asking && file && <LinkQuestion onPick={(use) => setPick({ file, choice: use })} />}
{asking && file && <LinkQuestion choices={choices} onPick={(use) => setPick({ file, choice: use })} />}
{nowhere && (
<p className="px-1 text-[length:calc(12px*var(--fs-scale-body,1))] text-m-muted">
{t('native.share.linkUnsupported')}
@@ -234,22 +256,40 @@ export default function NativeImportSheet(): React.ReactElement | null {
);
}
function LinkQuestion({ onPick }: { onPick: (choice: LinkChoice) => void }): React.ReactElement {
function LinkQuestion({
choices,
onPick,
}: {
choices: LinkChoice[];
onPick: (choice: LinkChoice) => void;
}): React.ReactElement {
const { t } = useTranslation();
return (
<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={() => onPick('link')}
/>
<ChoiceRow
icon={<ScanText size={17} strokeWidth={2} />}
label={t('native.share.readBooking')}
hint={t('native.share.readBookingHint')}
onClick={() => onPick('booking')}
/>
{choices.includes('place') && (
<ChoiceRow
icon={<MapPin size={17} strokeWidth={2} />}
label={t('native.share.addPlace')}
hint={t('native.share.addPlaceHint')}
onClick={() => onPick('place')}
/>
)}
{choices.includes('link') && (
<ChoiceRow
icon={<Link2 size={17} strokeWidth={2} />}
label={t('native.share.saveLink')}
hint={t('native.share.saveLinkHint')}
onClick={() => onPick('link')}
/>
)}
{choices.includes('booking') && (
<ChoiceRow
icon={<ScanText size={17} strokeWidth={2} />}
label={t('native.share.readBooking')}
hint={t('native.share.readBookingHint')}
onClick={() => onPick('booking')}
/>
)}
</div>
);
}
@@ -324,6 +324,17 @@ export default function MTripShell({
setBookingImportKind('bookings')
setShowBookingImport(true)
}, [sharedTripId, tripId, setBookingImportKind, setShowBookingImport])
// A map link shared to TREK and this trip picked for it (#2582): the new place
// sheet opens, and its search looks the link up (MPlaceEditSheet).
const sharedPlaceTripId = useSharedImportStore(s => s.placeLink?.tripId ?? null)
const { setEditingPlace, setEditingAssignmentId, setPrefillCoords, setShowPlaceForm } = planner
useEffect(() => {
if (sharedPlaceTripId == null || sharedPlaceTripId !== Number(tripId)) return
setEditingPlace(null)
setEditingAssignmentId(null)
setPrefillCoords(null)
setShowPlaceForm(true)
}, [sharedPlaceTripId, tripId, setEditingPlace, setEditingAssignmentId, setPrefillCoords, setShowPlaceForm])
// The day strip says when it runs on past an edge (a long trip, a narrow pane).
const dayFade = useEdgeFade(dayRail)
const dayPill = useActivePill(dayRail, '[aria-current="true"]', `${railDayId}:${days.map(d => d.id).join(',')}:${language}`)
@@ -34,6 +34,7 @@ import { usePlaceImageField } from '../../../../components/Planner/usePlaceImage
import { useTranslation } from '../../../../i18n'
import { useAuthStore } from '../../../../store/authStore'
import { useSettingsStore } from '../../../../store/settingsStore'
import { useSharedImportStore } from '../../../../native/sharedFiles'
import type { Assignment, AssignmentsMap, Place } from '../../../../types'
import type { TripPlanner } from '../MTripShell'
import { useLocationBias } from '../../../../hooks/useLocationBias'
@@ -103,6 +104,9 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
const tagField = usePlaceTags({ tripId: planner.tripId, place: sheetPlace, tags: form.tags, setForm, t, toast })
const placesEnrichEnabled = useAuthStore(s => s.placesEnrichEnabled)
// A map link shared to TREK for this trip (#2582): a new place starts from it.
const sharedPlaceUrl = useSharedImportStore(s => (s.placeLink?.tripId === planner.tripId ? s.placeLink.url : null))
const clearSharedPlace = useSharedImportStore(s => s.clearPlaceLink)
const { language, locale } = useTranslation()
const timeFormat = useSettingsStore(s => s.settings.time_format) || '24h'
@@ -266,6 +270,8 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
onPick={applyPick}
onSuggestionName={name => setForm(prev => ({ ...prev, name }))}
onResolvingChange={setResolvingPick}
initialQuery={!sheetPlace && sharedPlaceUrl ? sharedPlaceUrl : undefined}
onInitialQueryRun={clearSharedPlace}
/>
{placesEnrichEnabled && (
@@ -1,4 +1,5 @@
import { Loader2, RotateCcw, Search } from 'lucide-react'
import { useEffect, useEffectEvent } from 'react'
import { offersGoogleRetry } from '../../../../utils/placeSource'
import { usePlaceSearch, type MapsPlace } from '../../../../components/Planner/usePlaceSearch'
import { FIELD_CLS } from './PlSheetChrome'
@@ -48,6 +49,10 @@ interface PlPlaceSearchProps {
onSuggestionName: (name: string) => void
/** True while a suggestion's details are being resolved (name spinner). */
onResolvingChange?: (resolving: boolean) => void
/** A query the field starts with and runs once, such as a shared map link (#2582). */
initialQuery?: string
/** The starting query was sent, so whoever held it can let it go. */
onInitialQueryRun?: () => void
}
function placeToPick(place: MapsPlace): PlSearchPick {
@@ -73,7 +78,7 @@ function placeToPick(place: MapsPlace): PlSearchPick {
* detection — the mobile counterpart of PlaceFormModal's search block, on the
* same search logic (usePlaceSearch).
*/
export default function PlPlaceSearch({ planner, locationBias, onPick, onSuggestionName, onResolvingChange }: PlPlaceSearchProps) {
export default function PlPlaceSearch({ planner, locationBias, onPick, onSuggestionName, onResolvingChange, initialQuery, onInitialQueryRun }: PlPlaceSearchProps) {
const { t, toast } = planner
const {
query, setQuery, results, suggestions, setSuggestions, acSource, searchSource, searching, googleAnswers,
@@ -94,8 +99,19 @@ export default function PlPlaceSearch({ planner, locationBias, onPick, onSuggest
}),
onCoordinates: (lat, lng) => onPick({ lat, lng }),
onResolvingChange,
initialQuery,
})
// A map link shared to the app (#2582) is looked up as soon as the sheet opens,
// as if it had been pasted and searched.
const runInitial = useEffectEvent(() => {
void handleSearch()
onInitialQueryRun?.()
})
useEffect(() => {
if (initialQuery) runInitial()
}, [initialQuery])
return (
<div className="relative">
<div className="flex items-center gap-2">