feat(tours): a city walk from a Google Maps walking route, its short link followed only to Google Maps (CW-06, CW-07)

"Add tour" in the planner now offers "Import walk from Google Maps". The
dialog takes the link of a route shared in Google Maps, either a
maps.app.goo.gl short link or the long google.com/maps/dir link, or the
share text of the Google Maps app with the one link in it. It shows the
stops in their order with their names, marks a stop the link gives no
position as such, says that the route comes from Google Maps with a link to
open it there, and that TREK plans the way between the stops itself and
does not take the line drawn in Google Maps over. Nothing is written until
"Load as walk": that opens a new, unsaved city walk in the planner with the
positioned stops and their names, routed on foot by TREK, and warns first
when it replaces unsaved work. A stop without a position is left out and
never looked up or guessed; with fewer than two positions nothing can be
loaded. While the walk is not saved, a calm notice in the planner says
where it came from, also after a reload of the draft. Cancelling or a
failure leaves every tour as it was.

Only a route the link marks unambiguously as on foot is read. A car, bike
or transit route, a link that does not say, or one that says two things is
refused with a reason the dialog gives in the reader's language. Each stop
takes its position from its own block of the link's data, so a line
dragged through extra points or a stop given as coordinates no longer
leaves the stops without positions or shifts them. The road trip and
places imports read links as before.

A short link is followed by a resolver of its own: every hop is checked
against the Google Maps short link shapes and the strict SSRF guard before
it is looked up or asked, so ALLOW_INTERNAL_NETWORK and
ALLOW_LINK_LOCAL_IPS do not open it. Each request goes to the vetted
addresses only, follows nothing by itself, reads no body and carries no
credentials; the chain has one deadline including name lookups, at most
three hops and a cap on the Location header, and the long link it ends on
must be Google Maps and is never fetched. The preview is POST
/api/trips/:tripId/tours/import/google-maps/preview for members who may
edit places, with a 502 when Google could not be reached, and the MCP tool
preview_google_maps_walk reads the same.
This commit is contained in:
Maurice
2026-10-20 04:21:14 +00:00
parent 2203ff3a2e
commit 4ca5728072
67 changed files with 3770 additions and 68 deletions
@@ -11,8 +11,20 @@ vi.mock('../library/useTourLibrary', () => ({
},
}));
vi.mock('../library/TourLibraryDialog', () => ({ TourLibraryDialog: () => <div data-testid="library-dialog" /> }));
const walk = vi.hoisted(() => ({ show: vi.fn(), options: null as unknown }));
vi.mock('../walk/useWalkImport', () => ({
useWalkImport: (options: unknown) => {
walk.options = options;
return { show: walk.show };
},
}));
vi.mock('../walk/WalkImportDialog', () => ({
WalkImportDialog: ({ hasUnsavedChanges }: { hasUnsavedChanges: boolean }) => (
<div data-testid="walk-dialog" data-unsaved={String(hasUnsavedChanges)} />
),
}));
// FE-TOUR-ADD-001 to FE-TOUR-ADD-005
// FE-TOUR-ADD-001 to FE-TOUR-ADD-006
function planner(mode: 'neutral' | 'new-draft' = 'new-draft', overrides: Record<string, unknown> = {}) {
return {
@@ -21,6 +33,7 @@ function planner(mode: 'neutral' | 'new-draft' = 'new-draft', overrides: Record<
hasUnsavedChanges: false,
openTour: vi.fn(),
startNewTour: vi.fn(),
startDerivedTour: vi.fn(),
...overrides,
} as unknown as Parameters<typeof TourAddMenu>[0]['planner'];
}
@@ -32,7 +45,7 @@ const open = () => fireEvent.click(screen.getByTestId('tour-rail-add'));
afterEach(() => vi.clearAllMocks());
describe('TourAddMenu (LIB-02)', () => {
it('FE-TOUR-ADD-001: one button opens the three ways to add a tour, in order', () => {
it('FE-TOUR-ADD-001: one button opens the four ways to add a tour, in order', () => {
render(<TourAddMenu planner={planner()} gpxImport={gpxImport()} onTakenOver={vi.fn()} disabled={false} />);
const button = screen.getByTestId('tour-rail-add');
expect(button).toHaveAccessibleName('Add tour');
@@ -42,6 +55,7 @@ describe('TourAddMenu (LIB-02)', () => {
expect(entries().map((entry) => entry.textContent)).toEqual([
'Plan new tour',
'Import GPX',
'Import walk from Google Maps',
'Take over a tour from another trip',
]);
});
@@ -65,7 +79,11 @@ describe('TourAddMenu (LIB-02)', () => {
it('FE-TOUR-ADD-003: with no tour open the map is already planning one, so that entry is left out', () => {
render(<TourAddMenu planner={planner('neutral')} gpxImport={gpxImport()} onTakenOver={vi.fn()} disabled={false} />);
open();
expect(entries().map((entry) => entry.textContent)).toEqual(['Import GPX', 'Take over a tour from another trip']);
expect(entries().map((entry) => entry.textContent)).toEqual([
'Import GPX',
'Import walk from Google Maps',
'Take over a tour from another trip',
]);
});
it('FE-TOUR-ADD-004: a tour taken over comes in, and opens unless the editor holds unsaved work', async () => {
@@ -84,13 +102,25 @@ describe('TourAddMenu (LIB-02)', () => {
expect(screen.getByTestId('library-dialog')).toBeInTheDocument();
});
it('FE-TOUR-ADD-005: waits while saving or importing, and is not there with nothing to offer', () => {
it('FE-TOUR-ADD-005: waits while saving or importing, and offers a walk from Google Maps with nothing else to offer', () => {
const { rerender } = render(<TourAddMenu planner={planner()} gpxImport={gpxImport(true)} disabled={false} />);
expect(screen.getByTestId('tour-rail-add')).toBeDisabled();
rerender(<TourAddMenu planner={planner()} gpxImport={gpxImport()} disabled />);
expect(screen.getByTestId('tour-rail-add')).toBeDisabled();
rerender(<TourAddMenu planner={planner('neutral')} disabled={false} />);
expect(screen.queryByTestId('tour-rail-add')).toBeNull();
open();
expect(entries().map((entry) => entry.textContent)).toEqual(['Import walk from Google Maps']);
expect(screen.queryByTestId('library-dialog')).toBeNull();
});
it('FE-TOUR-ADD-006: the walk entry opens its dialog, which knows about unsaved work in the planner (CW-07)', () => {
const p = planner('new-draft', { hasUnsavedChanges: true });
render(<TourAddMenu planner={p} gpxImport={gpxImport()} disabled={false} />);
expect((walk.options as { planner: unknown }).planner).toBe(p);
expect(screen.getByTestId('walk-dialog')).toHaveAttribute('data-unsaved', 'true');
open();
fireEvent.click(screen.getByText('Import walk from Google Maps'));
expect(walk.show).toHaveBeenCalledTimes(1);
expect(screen.queryByRole('group')).toBeNull();
});
});
@@ -1,5 +1,5 @@
import type { TourListItem } from '@trek/shared';
import { FileDown, Library, Loader2, PenLine, Plus } from 'lucide-react';
import { FileDown, Footprints, Library, Loader2, PenLine, Plus } from 'lucide-react';
import type { ReactNode } from 'react';
import { useTranslation } from '../../../i18n';
import { PopoverItem } from '../../Packing/PackingPopover';
@@ -9,6 +9,8 @@ import { usePopoverList } from '../../shared/usePopoverList';
import { TourLibraryDialog } from '../library/TourLibraryDialog';
import { useTourLibrary } from '../library/useTourLibrary';
import type { TourGpxImport } from '../useTourGpxImport';
import { WalkImportDialog } from '../walk/WalkImportDialog';
import { useWalkImport } from '../walk/useWalkImport';
import type { TourPlannerController } from './useTourPlanner';
interface AddEntry {
@@ -21,9 +23,12 @@ interface AddEntry {
/**
* LIB-02: the tours rail's one way to add a tour, as a menu: plan a new one
* (while another is open; with none open the map is already planning one),
* import GPX files, or take one over from another trip, whose dialog opens
* from here. A tour taken over comes into the trip and opens in the editor,
* unless the editor holds unsaved work.
* import GPX files, read a city walk from a Google Maps walking route (CW-07),
* or take one over from another trip. The walk and the take-over open their
* dialogs from here. A tour taken over comes into the trip and opens in the
* editor, unless the editor holds unsaved work; a walk read from Google Maps
* opens in the planner as a new draft, after a warning when that replaces
* unsaved work.
*/
export function TourAddMenu({
planner,
@@ -31,14 +36,17 @@ export function TourAddMenu({
onTakenOver,
disabled,
}: {
planner: Pick<TourPlannerController, 'tripId' | 'mode' | 'hasUnsavedChanges' | 'openTour' | 'startNewTour'>;
planner: Pick<
TourPlannerController,
'tripId' | 'mode' | 'hasUnsavedChanges' | 'openTour' | 'startNewTour' | 'startDerivedTour'
>;
gpxImport?: TourGpxImport;
/** Where a tour of another trip goes into this one; without it that entry is left out. */
onTakenOver?: (tour: TourListItem) => Promise<void>;
disabled: boolean;
}) {
const { t } = useTranslation();
const list = usePopoverList(0, { estimatedHeight: 140 });
const list = usePopoverList(0, { estimatedHeight: 176 });
const { open, toggle, close, triggerRef } = list;
const library = useTourLibrary({
tripId: Number(planner.tripId),
@@ -47,6 +55,7 @@ export function TourAddMenu({
if (!planner.hasUnsavedChanges) void planner.openTour(tour);
},
});
const walkImport = useWalkImport({ planner });
const importing = gpxImport?.importing ?? false;
const entries: AddEntry[] = [];
@@ -66,6 +75,12 @@ export function TourAddMenu({
run: gpxImport.pick,
});
}
entries.push({
key: 'walk',
icon: <Footprints size={14} strokeWidth={2} />,
label: t('tours.walkImport.menu'),
run: walkImport.show,
});
if (onTakenOver) {
entries.push({
key: 'library',
@@ -74,7 +89,6 @@ export function TourAddMenu({
run: library.show,
});
}
if (entries.length === 0) return null;
// Run inside the click that picked it: the file picker opens only from a user's own tap.
const pick = (entry: AddEntry) => {
@@ -106,6 +120,7 @@ export function TourAddMenu({
<PopoverItem key={entry.key} icon={entry.icon} label={entry.label} onClick={() => pick(entry)} />
))}
</PopoverListPanel>
<WalkImportDialog walkImport={walkImport} hasUnsavedChanges={planner.hasUnsavedChanges} />
{onTakenOver && <TourLibraryDialog library={library} />}
</>
);
@@ -901,6 +901,17 @@ describe('TourPlannerRail', () => {
expect(screen.getByLabelText('Unsaved draft restored')).toBeInTheDocument()
expect(screen.getByRole('heading', { name: 'Edit tour' })).toBeInTheDocument()
})
it('TOUR-PLANNER-RAIL-022: an unsaved walk read from Google Maps says so, and a saved one no longer does (CW-07)', () => {
const notice = 'From a Google Maps walking route. TREK planned the way between the stops itself.'
const { rerender } = render(<TourPlannerRail planner={planner({ draftSource: 'google_maps', hasUnsavedChanges: true, mode: { type: 'new-draft' } })} />)
expect(screen.getByText(notice)).toBeInTheDocument()
rerender(<TourPlannerRail planner={planner({ draftSource: 'google_maps', editingPlaceId: tour.place_id, mode: { type: 'edit-saved', placeId: tour.place_id } })} />)
expect(screen.queryByText(notice)).toBeNull()
rerender(<TourPlannerRail planner={planner({ hasUnsavedChanges: true, mode: { type: 'new-draft' } })} />)
expect(screen.queryByText(notice)).toBeNull()
})
})
describe('the paddle checklist in the rails (PAD-06)', () => {
@@ -41,6 +41,7 @@ import { type AssignTourToDay, useTourDayAssignment } from '../useTourDayAssignm
import WandererMark from '../wanderer/WandererMark'
import { TourGpxExportBarButton } from '../TourGpxExportButton'
import { TourRemoteChangeNotice, TourRevisionConflictDialog } from './TourRevisionNotice'
import { WalkImportDraftNotice } from '../walk/WalkImportDialog'
import TourListFilterMenu, { TourFilterEmpty } from '../TourListFilterMenu'
import { TourScopeSummary } from '../TourScopeSummary'
import { useTourListFilters } from '../useTourListFilters'
@@ -438,6 +439,7 @@ export function TourPlannerRail({ planner,
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-3 py-3.5">
<TourRemoteChangeNotice planner={planner} />
<WalkImportDraftNotice planner={planner} />
<TourNameField planner={planner} locked={locked} />
<TourTypeFields planner={planner} locked={locked} />
@@ -12,6 +12,9 @@ import {
import type { TourPlannerWaypoint } from './tourPlannerWaypoints';
import type { PaddleFieldValues } from './usePaddleFields';
/** CW-07: where a draft's points were read from outside the trip, said in the planner until it is saved. */
export type DraftSource = 'google_maps';
/**
* The tour planner's draft as it is kept in local storage between visits, and
* the check a stored draft has to pass before the planner takes it back: a
@@ -30,6 +33,8 @@ export interface DraftPayload {
editingPlaceId?: number | null;
/** The import a new tour is being planned from; carried until it is saved. */
derivedFromPlaceId?: number | null;
/** CW-07: a draft loaded from a Google Maps walk keeps saying so across a reload. */
draftSource?: DraftSource | null;
tourType?: PlannableTourType;
paddle?: PaddleFieldValues;
/** P2C-03: the revision of the tour the draft edits, as it was loaded. */
@@ -58,6 +63,10 @@ function optionalPlaceId(value: number | null | undefined): boolean {
return value == null || (Number.isInteger(value) && value > 0);
}
function optionalSource(value: unknown): boolean {
return value == null || value === 'google_maps';
}
function optionalDifficulty(value: number | null | undefined): boolean {
return value == null || (Number.isInteger(value) && value >= 1 && value <= 6);
}
@@ -97,6 +106,7 @@ export function validDraft(value: unknown): value is DraftPayload {
optionalMinutes(draft.breakAdditionalMinutes) &&
optionalPlaceId(draft.editingPlaceId) &&
optionalPlaceId(draft.derivedFromPlaceId) &&
optionalSource(draft.draftSource) &&
optionalPlaceId(draft.baseRevision) &&
validRouteChoices(draft) &&
Array.isArray(draft.waypoints) &&
@@ -14,7 +14,7 @@ import { useTourDraftStorage } from './useTourDraftStorage'
import { useTourRevisionGuard } from './useTourRevisionGuard'
import { useRouteShaping } from './useRouteShaping'
import { useTourMapView } from './useTourMapView'
import type { DraftPayload } from './tourPlannerDraft'
import type { DraftPayload, DraftSource } from './tourPlannerDraft'
import { paddleEstimateOf } from './paddlePlanOf'
import { adoptChangedPoints } from './paddleRouting'
import { NO_PADDLE_FIELDS, paddleFieldsOf, usePaddleFields, type PaddleFieldValues } from './usePaddleFields'
@@ -26,9 +26,10 @@ export interface DerivedTourDraft {
description?: string | null
website?: string | null
difficulty: TourMaxHikingDifficulty
points: Array<{ lat: number; lng: number }>
/** The import the points were taken from. */
sourcePlaceId: number
/** The control points in order; a city walk's stop keeps the name it came with (CW-07). */
points: Array<{ lat: number; lng: number; name?: string | null }>
/** The import the points were taken from; absent for a link read from outside the trip (CW-07). */
sourcePlaceId?: number
/**
* Plan the import over in place, keeping its id, days and notes (the server
* keeps the recorded track to go back to), rather than as a new tour beside it.
@@ -40,6 +41,8 @@ export interface DerivedTourDraft {
tourType?: PlannableTourType
paddle?: PaddleFieldValues
bikeProfile?: BikeProfile
/** CW-07: where the points came from, said in the planner until the draft is saved. */
source?: DraftSource
}
export type TourPlannerStatus =
@@ -133,6 +136,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
const [draftRestored, setDraftRestored] = useState(Boolean(restored))
const [editingPlaceId, setEditingPlaceId] = useState<number | null>(restored?.editingPlaceId ?? null)
const [derivedFromPlaceId, setDerivedFromPlaceId] = useState<number | null>(restored?.derivedFromPlaceId ?? null)
const [draftSource, setDraftSource] = useState<DraftSource | null>(restored?.draftSource ?? null)
const [openingTourId, setOpeningTourId] = useState<number | null>(null)
const [saveOutcome, setSaveOutcome] = useState<TourListItem | null>(null)
const [retryToken, setRetryToken] = useState(0)
@@ -540,6 +544,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
setEditingPlaceId(null)
editingPlaceIdRef.current = null
setDerivedFromPlaceId(null)
setDraftSource(null)
adoptRevision(null)
setOpeningTourId(null)
setSaveOutcome(null)
@@ -587,9 +592,12 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
returnToNeutral()
const type = draft.tourType ?? 'hike'
const points = normalizePlannerWaypoints(
draft.points.map(({ lat, lng }) => ({ id: randomId(), lat, lng, role: 'via' as const })),
draft.points.map(({ lat, lng, name }) => ({
id: randomId(), lat, lng, role: 'via' as const, ...(name ? { name } : {}),
})),
type === 'kayak',
)
setDraftSource(draft.source ?? null)
tourTypeRef.current = type
setTourTypeState(type)
if (draft.paddle) loadPaddle(draft.paddle)
@@ -605,12 +613,12 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
setMaxHikingDifficultyState(draft.difficulty)
difficultyRef.current = draft.difficulty
setSelectedWaypointId(points[0].id)
if (draft.inPlace) {
if (draft.inPlace && draft.sourcePlaceId !== undefined) {
setEditingPlaceId(draft.sourcePlaceId)
editingPlaceIdRef.current = draft.sourcePlaceId
adoptRevision(draft.revision)
} else {
setDerivedFromPlaceId(draft.sourcePlaceId)
setDerivedFromPlaceId(draft.sourcePlaceId ?? null)
}
setStatus('dirty')
setHasUnsavedChanges(true)
@@ -707,6 +715,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
setMapFocusKey(key => key + 1)
setSaveOutcome(null)
setReadOnlyGpxTour(null)
setDraftSource(null)
return true
} catch {
if (requestIsCurrent() && !saveInFlightRef.current) setError('open')
@@ -749,12 +758,12 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
useEffect(() => {
if (!hasUnsavedChanges) return
const draft: DraftPayload = { version: 10, name, description, website, plannedDurationMinutes, breakAdditionalMinutes, waypoints, maxHikingDifficulty, editingPlaceId,
derivedFromPlaceId, tourType, baseRevision: revision.base, hikingPreferences, bikeProfile,
derivedFromPlaceId, draftSource, tourType, baseRevision: revision.base, hikingPreferences, bikeProfile,
paddle: { boatType: paddle.boatType, waterContext: paddle.waterContext, speedKmh: paddle.speedKmh, portageSpeedKmh: paddle.portageSpeedKmh, lakeStyle: paddle.lakeStyle },
}
keepDraft(draft)
}, [breakAdditionalMinutes,
derivedFromPlaceId, description, editingPlaceId, hasUnsavedChanges, maxHikingDifficulty, name, plannedDurationMinutes, keepDraft, waypoints, website,
derivedFromPlaceId, draftSource, description, editingPlaceId, hasUnsavedChanges, maxHikingDifficulty, name, plannedDurationMinutes, keepDraft, waypoints, website,
tourType, paddle.boatType, paddle.waterContext, paddle.speedKmh, paddle.portageSpeedKmh, paddle.lakeStyle, revision.base, hikingPreferences,
bikeProfile])
@@ -828,6 +837,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
clearHistory()
setEditingPlaceId(result.tour.place_id)
editingPlaceIdRef.current = result.tour.place_id
setDraftSource(null)
setSaveOutcome(result.tour)
}
if (mountedRef.current && String(tripIdRef.current) === submittedTripId && !deletedTourPlaceIdsRef.current.has(result.tour.place_id)) {
@@ -873,6 +883,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
startNewTour,
startDerivedTour,
derivedFromPlaceId,
draftSource,
newTourConfirmationOpen, cancelNewTour, forgetDeletedTour,
elevationProfileExpanded, toggleElevationProfile, newDraftGeneration, draftRestored, mapFocusKey,
editingPlaceId, openingTourId, openTour,
@@ -0,0 +1,174 @@
import { act, renderHook } from '@testing-library/react';
import type { TourCreateRequest, TourCreateResponse } from '@trek/shared';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const { routeWalkingTour, routeCityWalk, enrichTourElevations, createTour, detailTour, updateTour } = vi.hoisted(
() => ({
routeWalkingTour: vi.fn(),
routeCityWalk: vi.fn(),
enrichTourElevations: vi.fn(),
createTour: vi.fn(),
detailTour: vi.fn(),
updateTour: vi.fn(),
})
);
vi.mock('./tourRouting', () => ({ routeWalkingTour, routeCityWalk, enrichTourElevations }));
vi.mock('../../../repo/tourRepo', () => ({ tourRepo: { create: createTour, detail: detailTour, update: updateTour } }));
vi.mock('../useTourPermissions', () => ({ useTourPermissions: () => ({ canEdit: true, canAssign: true }) }));
import { validDraft } from './tourPlannerDraft';
import { useTourPlanner, type DerivedTourDraft } from './useTourPlanner';
// FE-TOUR-WALK-IMPORT-PLANNER-001 to FE-TOUR-WALK-IMPORT-PLANNER-004: a walk read from a Google Maps link,
// opened as a new draft with its stop names, routed on foot by TREK and saved like any other walk (CW-07).
const routed = {
coordinates: [
[41.1425899, -8.6092477],
[41.1382776, -8.6117899],
] as [number, number][],
parts: [
{
coordinates: [
[41.1425899, -8.6092477],
[41.1382776, -8.6117899],
] as [number, number][],
free: false,
},
],
distanceMeters: 1400,
durationSeconds: 1200,
};
const enriched = [
[41.1425899, -8.6092477, 80],
[41.1382776, -8.6117899, 10],
] as [number, number, number][];
const answered = (body: TourCreateRequest): TourCreateResponse => ({
tour: {
place_id: 51,
name: body.name,
tour_type: 'walk',
distance: 1.4,
elevation_gain: 5,
elevation_loss: 75,
duration: 20,
difficulty: null,
wanderer_ref: null,
match_confidence: 1,
max_hiking_difficulty: null,
planned: false,
caution: false,
revision: 1,
},
waypoints: body.waypoints.map((point, index) => ({ ...point, key: point.key ?? `stop-${index}` })),
});
/** What the walk import hands the planner for a route of three stops, the middle one given as coordinates. */
const FROM_GOOGLE: DerivedTourDraft = {
name: 'Walk from Google Maps',
difficulty: 2,
points: [
{ lat: 41.1425899, lng: -8.6092477, name: 'Igreja de Santa Clara' },
{ lat: 41.1428531, lng: -8.6111165, name: null },
{ lat: 41.1382776, lng: -8.6117899, name: 'Ribeira de Gaia' },
],
inPlace: false,
tourType: 'walk',
source: 'google_maps',
};
async function settle() {
await act(async () => {
await vi.advanceTimersByTimeAsync(450);
});
}
const storedDraft = (tripId: number) => JSON.parse(localStorage.getItem(`tour-draft-${tripId}`) ?? 'null') as unknown;
describe('useTourPlanner, a walk read from Google Maps (CW-07)', () => {
beforeEach(() => {
vi.useFakeTimers();
localStorage.clear();
routeWalkingTour.mockReset().mockResolvedValue(routed);
routeCityWalk.mockReset().mockResolvedValue(routed);
enrichTourElevations.mockReset().mockResolvedValue(enriched);
createTour.mockReset().mockImplementation(async (_trip: number, body: TourCreateRequest) => answered(body));
detailTour.mockReset();
updateTour.mockReset();
});
afterEach(() => vi.useRealTimers());
it('FE-TOUR-WALK-IMPORT-PLANNER-001: opens as a new walk with its stop names, routed on foot by TREK', async () => {
const { result } = renderHook(() => useTourPlanner({ tripId: 31 }));
let started = false;
act(() => {
started = result.current.startDerivedTour(FROM_GOOGLE);
});
expect(started).toBe(true);
expect(result.current.mode).toEqual({ type: 'new-draft' });
expect(result.current.tourType).toBe('walk');
expect(result.current.name).toBe('Walk from Google Maps');
expect(result.current.draftSource).toBe('google_maps');
expect(result.current.derivedFromPlaceId).toBeNull();
expect(result.current.editingPlaceId).toBeNull();
expect(result.current.waypoints.map((point) => [point.name, point.role])).toEqual([
['Igreja de Santa Clara', 'start'],
[undefined, 'via'],
['Ribeira de Gaia', 'end'],
]);
await settle();
expect(routeCityWalk).toHaveBeenCalledTimes(1);
expect(routeWalkingTour).not.toHaveBeenCalled();
expect(result.current.status).toBe('ready');
});
it('FE-TOUR-WALK-IMPORT-PLANNER-002: saves as a walk with the stop names and no import it was derived from', async () => {
const { result } = renderHook(() => useTourPlanner({ tripId: 31 }));
act(() => {
result.current.startDerivedTour(FROM_GOOGLE);
});
await settle();
expect(result.current.canSave).toBe(true);
await act(async () => {
await result.current.save();
});
const body = createTour.mock.calls[0]?.[1] as TourCreateRequest;
expect(body.tour_type).toBe('walk');
expect(body.waypoints.map((point) => point.name ?? null)).toEqual([
'Igreja de Santa Clara',
null,
'Ribeira de Gaia',
]);
expect(body).not.toHaveProperty('derived_from_place_id');
// Saved, the walk is TREK's own: the notice of where it came from goes.
expect(result.current.draftSource).toBeNull();
expect(result.current.mode).toEqual({ type: 'edit-saved', placeId: 51 });
});
it('FE-TOUR-WALK-IMPORT-PLANNER-003: the source is kept with the unsaved draft across a reload, and forgotten when it is thrown away', () => {
const first = renderHook(() => useTourPlanner({ tripId: 32 }));
act(() => {
first.result.current.startDerivedTour(FROM_GOOGLE);
});
expect(storedDraft(32)).toMatchObject({ draftSource: 'google_maps', tourType: 'walk' });
first.unmount();
const reloaded = renderHook(() => useTourPlanner({ tripId: 32 }));
expect(reloaded.result.current.draftSource).toBe('google_maps');
expect(reloaded.result.current.waypoints[0]?.name).toBe('Igreja de Santa Clara');
act(() => reloaded.result.current.returnToNeutral());
expect(reloaded.result.current.draftSource).toBeNull();
expect(storedDraft(32)).toBeNull();
});
it('FE-TOUR-WALK-IMPORT-PLANNER-004: a stored draft names no source, or Google Maps; any other is not taken back', () => {
const draft = { version: 10, name: 'Walk', waypoints: [] };
expect(validDraft(draft)).toBe(true);
expect(validDraft({ ...draft, draftSource: null })).toBe(true);
expect(validDraft({ ...draft, draftSource: 'google_maps' })).toBe(true);
expect(validDraft({ ...draft, draftSource: 'komoot' })).toBe(false);
});
});
@@ -0,0 +1,137 @@
import type { WalkImportPreviewResponse } from '@trek/shared';
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, within } from '../../../../tests/helpers/render';
import type { WalkImport } from './useWalkImport';
import { WalkImportDialog, WalkImportDraftNotice } from './WalkImportDialog';
// FE-WALK-IMPORT-DIALOG-001 to FE-WALK-IMPORT-DIALOG-006
const ROUTE = 'https://www.google.com/maps/dir/Cathedral/Market/Park/data=!3e2';
const PREVIEW: WalkImportPreviewResponse = {
stations: [
{ name: 'Cathedral', lat: 48.1, lng: 11.5 },
{ name: 'Market', lat: null, lng: null },
{ name: null, lat: 48.12, lng: 11.52 },
],
resolved_url: ROUTE,
};
function walkImport(over: Partial<WalkImport> = {}): WalkImport {
return {
open: true,
show: vi.fn(),
close: vi.fn(),
url: '',
setUrl: vi.fn(),
phase: 'link',
preview: null,
failure: null,
unplaced: 0,
canRead: false,
canLoad: false,
read: vi.fn().mockResolvedValue(undefined),
back: vi.fn(),
load: vi.fn(),
...over,
};
}
const atPreview = (over: Partial<WalkImport> = {}) =>
walkImport({ phase: 'preview', preview: PREVIEW, unplaced: 1, canLoad: true, url: ROUTE, ...over });
describe('WalkImportDialog (CW-07)', () => {
it('FE-WALK-IMPORT-DIALOG-001: asks for the link, reads it on the button and on Enter, and says why one was refused', () => {
const closed = walkImport({ open: false });
const { rerender } = render(<WalkImportDialog walkImport={closed} hasUnsavedChanges={false} />);
expect(screen.queryByRole('dialog')).toBeNull();
const w = walkImport({ url: 'https://maps.app.goo.gl/abc', canRead: true });
rerender(<WalkImportDialog walkImport={w} hasUnsavedChanges={false} />);
expect(screen.getByText('Walk from a Google Maps link')).toBeInTheDocument();
const input = screen.getByLabelText('Link to the walking route');
fireEvent.change(input, { target: { value: 'https://maps.app.goo.gl/xyz' } });
expect(w.setUrl).toHaveBeenCalledWith('https://maps.app.goo.gl/xyz');
fireEvent.click(screen.getByTestId('walk-import-read'));
expect(w.read).toHaveBeenCalledTimes(1);
fireEvent.submit(input.closest('form') as HTMLFormElement);
expect(w.read).toHaveBeenCalledTimes(2);
fireEvent.click(screen.getByText('Cancel'));
expect(w.close).toHaveBeenCalledTimes(1);
const refused = walkImport({ failure: 'That route is not planned on foot.' });
rerender(<WalkImportDialog walkImport={refused} hasUnsavedChanges={false} />);
expect(screen.getByText('That route is not planned on foot.')).toBeInTheDocument();
expect(screen.getByTestId('walk-import-read')).toBeDisabled();
fireEvent.submit(screen.getByLabelText('Link to the walking route').closest('form') as HTMLFormElement);
expect(refused.read).not.toHaveBeenCalled();
});
it('FE-WALK-IMPORT-DIALOG-002: waits while the link is read', () => {
render(<WalkImportDialog walkImport={walkImport({ phase: 'reading', url: ROUTE })} hasUnsavedChanges={false} />);
expect(screen.getByLabelText('Link to the walking route')).toBeDisabled();
expect(screen.getByTestId('walk-import-read')).toBeDisabled();
});
it('FE-WALK-IMPORT-DIALOG-003: shows the stops in their order, the one without a position marked', () => {
render(<WalkImportDialog walkImport={atPreview()} hasUnsavedChanges={false} />);
const rows = screen.getAllByTestId('walk-import-station');
expect(rows.map((row) => row.textContent)).toEqual([
'1Cathedral48.10000, 11.50000',
'2MarketNo position in the link',
'3Stop 348.12000, 11.52000',
]);
expect(rows.map((row) => row.getAttribute('data-unresolved'))).toEqual([null, 'true', null]);
expect(screen.getByText('1 stop has no position in the link and is left out.')).toBeInTheDocument();
expect(
screen.getByText('TREK plans the way between the stops again; the line drawn in Google Maps is not taken over.')
).toBeInTheDocument();
expect(screen.queryByText('A walk needs at least two stops with a position.')).toBeNull();
expect(screen.queryByText('Loading the walk replaces the unsaved changes in the planner.')).toBeNull();
});
it('FE-WALK-IMPORT-DIALOG-004: names Google Maps as the source and opens the route read there in a new tab', () => {
render(<WalkImportDialog walkImport={atPreview()} hasUnsavedChanges={false} />);
const preview = screen.getByTestId('walk-import-preview');
expect(within(preview).getByText('From Google Maps')).toBeInTheDocument();
const source = screen.getByTestId('walk-import-source');
expect(source).toHaveAttribute('href', ROUTE);
expect(source).toHaveAttribute('target', '_blank');
expect(source).toHaveAttribute('rel', 'noopener noreferrer');
expect(source).toHaveTextContent('Open in Google Maps');
});
it('FE-WALK-IMPORT-DIALOG-005: loads or goes back, warns before replacing unsaved work, and loads nothing with too few positions', () => {
const w = atPreview();
const { rerender } = render(<WalkImportDialog walkImport={w} hasUnsavedChanges />);
expect(screen.getByText('Loading the walk replaces the unsaved changes in the planner.')).toBeInTheDocument();
fireEvent.click(screen.getByTestId('walk-import-load'));
expect(w.load).toHaveBeenCalledTimes(1);
fireEvent.click(screen.getByText('Use another link'));
expect(w.back).toHaveBeenCalledTimes(1);
// Enter does not read again while the stops are shown.
fireEvent.submit(screen.getByTestId('walk-import-preview').closest('form') as HTMLFormElement);
expect(w.read).not.toHaveBeenCalled();
rerender(<WalkImportDialog walkImport={atPreview({ canLoad: false, unplaced: 2 })} hasUnsavedChanges={false} />);
expect(screen.getByTestId('walk-import-load')).toBeDisabled();
expect(screen.getByText('A walk needs at least two stops with a position.')).toBeInTheDocument();
expect(screen.getByText('2 stops have no position in the link and are left out.')).toBeInTheDocument();
});
});
describe('WalkImportDraftNotice (CW-07)', () => {
it('FE-WALK-IMPORT-DIALOG-006: says where an unsaved walk came from, and nothing for any other draft', () => {
const { rerender } = render(
<WalkImportDraftNotice planner={{ draftSource: 'google_maps', mode: { type: 'new-draft' } }} />
);
expect(
screen.getByText('From a Google Maps walking route. TREK planned the way between the stops itself.')
).toBeInTheDocument();
rerender(
<WalkImportDraftNotice planner={{ draftSource: 'google_maps', mode: { type: 'edit-saved', placeId: 3 } }} />
);
expect(screen.queryByRole('status')).toBeNull();
rerender(<WalkImportDraftNotice planner={{ draftSource: null, mode: { type: 'new-draft' } }} />);
expect(screen.queryByRole('status')).toBeNull();
});
});
@@ -0,0 +1,251 @@
import type { WalkImportPreviewResponse, WalkImportStation } from '@trek/shared';
import { AlertTriangle, ExternalLink, Footprints, Link2, Loader2, MapPinOff, Route } from 'lucide-react';
import { useId, type FormEvent } from 'react';
import { useTranslation } from '../../../i18n';
import { EditorField, INPUT } from '../../shared/dialogParts';
import {
DialogButton,
DialogFooter,
DialogHeader,
DialogSection,
DialogShell,
DialogTile,
FooterSpacer,
fs,
NEUTRAL_TINT,
} from '../../shared/DialogShell';
import type { TourPlannerController } from '../planner/useTourPlanner';
import { TourNotice } from '../tourParts';
import type { WalkImport } from './useWalkImport';
/** One stop of the link, in its place in the order; a stop without a position says so instead of a position. */
function WalkImportStationRow({ station, number }: { station: WalkImportStation; number: number }) {
const { t } = useTranslation();
const position =
station.lat !== null && station.lng !== null ? `${station.lat.toFixed(5)}, ${station.lng.toFixed(5)}` : null;
const placed = position !== null;
return (
<li
data-testid="walk-import-station"
data-unresolved={placed ? undefined : 'true'}
className={`flex items-start gap-2.5 rounded-[10px] px-2.5 py-2 ${placed ? 'bg-surface-card' : 'border border-dashed border-edge'}`}
>
<span
className="mt-px grid h-5 w-5 flex-none place-items-center rounded-full bg-surface-secondary font-geist font-semibold text-content-muted"
style={fs(10.5)}
>
{number}
</span>
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
<span
className={`break-words font-medium leading-snug ${placed ? 'text-content' : 'text-content-muted'}`}
style={fs(12.5, 'body')}
>
{station.name ?? t('tours.walk.stationNumbered', { number })}
</span>
{placed ? (
<span className="font-geist text-content-faint" style={fs(11)}>
{position}
</span>
) : (
<span className="inline-flex items-center gap-1 text-warning" style={fs(11, 'body')}>
<MapPinOff size={11} strokeWidth={2.2} className="flex-none" />
{t('tours.walkImport.noPosition')}
</span>
)}
</span>
</li>
);
}
/** The step that asks for the link. */
function WalkImportLinkStep({ walkImport }: { walkImport: WalkImport }) {
const { t } = useTranslation();
const inputId = useId();
return (
<EditorField
label={t('tours.walkImport.urlLabel')}
htmlFor={inputId}
hint={t('tours.walkImport.urlHint')}
error={walkImport.failure}
>
<input
id={inputId}
type="text"
inputMode="url"
autoComplete="off"
spellCheck={false}
className={INPUT}
value={walkImport.url}
placeholder="https://maps.app.goo.gl/…"
disabled={walkImport.phase === 'reading'}
onChange={(event) => walkImport.setUrl(event.target.value)}
data-testid="walk-import-url"
/>
</EditorField>
);
}
/** The step that shows what the link holds, before anything is loaded. */
function WalkImportPreviewStep({
preview,
unplaced,
canLoad,
hasUnsavedChanges,
}: {
preview: WalkImportPreviewResponse;
unplaced: number;
canLoad: boolean;
hasUnsavedChanges: boolean;
}) {
const { t } = useTranslation();
return (
<div className="flex flex-col gap-4" data-testid="walk-import-preview">
<p className="m-0 flex flex-wrap items-center gap-x-2 gap-y-1 text-content-muted" style={fs(12, 'body')}>
<Footprints size={13} strokeWidth={2} className="flex-none" />
<span>{t('tours.walkImport.source')}</span>
<a
href={preview.resolved_url}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 font-medium text-accent hover:underline"
data-testid="walk-import-source"
>
{t('tours.walkImport.openSource')}
<ExternalLink size={12} strokeWidth={2} className="flex-none" />
</a>
</p>
<TourNotice icon={<Route size={13} strokeWidth={2} />}>{t('tours.walkImport.recalculated')}</TourNotice>
<DialogSection label={t('tours.walkImport.stops')}>
<ol className="m-0 flex list-none flex-col gap-1 p-0">
{preview.stations.map((station, index) => (
<WalkImportStationRow key={index} station={station} number={index + 1} />
))}
</ol>
</DialogSection>
{unplaced > 0 && (
<TourNotice tone="warning" icon={<MapPinOff size={13} strokeWidth={2} />}>
{t('tours.walkImport.unresolved', { count: unplaced })}
</TourNotice>
)}
{!canLoad && <TourNotice tone="warning">{t('tours.walkImport.tooFewPositions')}</TourNotice>}
{hasUnsavedChanges && (
<TourNotice tone="warning" icon={<AlertTriangle size={13} strokeWidth={2} />}>
{t('tours.walkImport.replacesDraft')}
</TourNotice>
)}
</div>
);
}
/** The buttons of each step: read the link, or go back and load the walk. */
function WalkImportFooter({ walkImport }: { walkImport: WalkImport }) {
const { t } = useTranslation();
const reading = walkImport.phase === 'reading';
return (
<DialogFooter>
<FooterSpacer />
<DialogButton onClick={walkImport.close}>{t('common.cancel')}</DialogButton>
{walkImport.preview ? (
<>
<DialogButton onClick={walkImport.back}>{t('tours.walkImport.back')}</DialogButton>
<DialogButton
variant="primary"
icon={<Footprints size={14} strokeWidth={2} />}
disabled={!walkImport.canLoad}
onClick={walkImport.load}
data-testid="walk-import-load"
>
{t('tours.walkImport.load')}
</DialogButton>
</>
) : (
<DialogButton
variant="primary"
icon={
reading ? (
<Loader2 size={14} strokeWidth={2} className="animate-spin" />
) : (
<Link2 size={14} strokeWidth={2} />
)
}
disabled={!walkImport.canRead}
onClick={() => void walkImport.read()}
data-testid="walk-import-read"
>
{t('tours.walkImport.read')}
</DialogButton>
)}
</DialogFooter>
);
}
/**
* CW-07: a city walk from a Google Maps walking route, opened from "Add tour".
* First the link, then its stops in their order with the ones the link gives
* no position marked, where the route came from, and that TREK plans the way
* between them itself. Only the load button hands the walk to the planner.
*/
export function WalkImportDialog({
walkImport,
hasUnsavedChanges,
}: {
walkImport: WalkImport;
hasUnsavedChanges: boolean;
}) {
const { t } = useTranslation();
const titleId = useId();
if (!walkImport.open) return null;
const submit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!walkImport.preview && walkImport.canRead) void walkImport.read();
};
const head = (
<DialogHeader
tile={
<DialogTile>
<Footprints size={20} strokeWidth={2} className="text-content" />
</DialogTile>
}
tint={NEUTRAL_TINT}
labelId={titleId}
onClose={walkImport.close}
title={t('tours.walkImport.title')}
sub={t('tours.walkImport.intro')}
subWraps
/>
);
return (
<DialogShell
onClose={walkImport.close}
labelledBy={titleId}
width="narrow"
align="top"
onSubmit={submit}
header={head}
footer={<WalkImportFooter walkImport={walkImport} />}
>
{walkImport.preview ? (
<WalkImportPreviewStep
preview={walkImport.preview}
unplaced={walkImport.unplaced}
canLoad={walkImport.canLoad}
hasUnsavedChanges={hasUnsavedChanges}
/>
) : (
<WalkImportLinkStep walkImport={walkImport} />
)}
</DialogShell>
);
}
/** CW-07: said in the planner while a walk read from Google Maps is not saved yet. */
export function WalkImportDraftNotice({ planner }: { planner: Pick<TourPlannerController, 'draftSource' | 'mode'> }) {
const { t } = useTranslation();
if (planner.draftSource !== 'google_maps' || planner.mode.type !== 'new-draft') return null;
return (
<TourNotice role="status" icon={<Footprints size={13} strokeWidth={2} />}>
{t('tours.walkImport.draftNotice')}
</TourNotice>
);
}
@@ -0,0 +1,191 @@
import { act, renderHook } from '@testing-library/react';
import type { WalkImportPreviewResponse } from '@trek/shared';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { TranslationProvider } from '../../../i18n/TranslationContext';
import { OnlineOnlyError } from '../../../repo/onlineOnly';
import { tourWalkImportRepo } from '../../../repo/tourWalkImportRepo';
import { useWalkImport } from './useWalkImport';
// FE-WALK-IMPORT-001 to FE-WALK-IMPORT-007
const ROUTE = 'https://www.google.com/maps/dir/Cathedral/Market/Park/data=!3e2';
const PREVIEW: WalkImportPreviewResponse = {
stations: [
{ name: 'Cathedral', lat: 48.1, lng: 11.5 },
{ name: 'Market', lat: null, lng: null },
{ name: null, lat: 48.12, lng: 11.52 },
{ name: 'Park', lat: 48.13, lng: 11.53 },
],
resolved_url: ROUTE,
};
let preview: ReturnType<typeof vi.spyOn>;
const planner = () => ({ tripId: 5, startDerivedTour: vi.fn(() => true) });
function setup(p = planner()) {
const hook = renderHook(() => useWalkImport({ planner: p }), { wrapper: TranslationProvider });
return { ...hook, planner: p };
}
async function readLink(result: ReturnType<typeof setup>['result'], text: string) {
act(() => result.current.show());
act(() => result.current.setUrl(text));
await act(() => result.current.read());
}
beforeEach(() => {
preview = vi.spyOn(tourWalkImportRepo, 'preview').mockResolvedValue(PREVIEW);
});
afterEach(() => vi.restoreAllMocks());
describe('useWalkImport (CW-07)', () => {
it('FE-WALK-IMPORT-001: reads the link and shows its stops, counting the ones without a position', async () => {
const { result } = setup();
expect(result.current.open).toBe(false);
act(() => result.current.show());
expect(result.current.open).toBe(true);
expect(result.current.canRead).toBe(false);
act(() => result.current.setUrl(' https://maps.app.goo.gl/abc '));
expect(result.current.canRead).toBe(true);
await act(() => result.current.read());
expect(preview).toHaveBeenCalledWith(5, 'https://maps.app.goo.gl/abc', expect.any(AbortSignal));
expect(result.current.phase).toBe('preview');
expect(result.current.preview).toBe(PREVIEW);
expect(result.current.unplaced).toBe(1);
expect(result.current.canLoad).toBe(true);
});
it('FE-WALK-IMPORT-002: takes the one link out of the share text of the Google Maps app, and sends anything else as typed', async () => {
const { result } = setup();
await readLink(result, 'Walk through the old town\nhttps://maps.app.goo.gl/abc');
expect(preview).toHaveBeenLastCalledWith(5, 'https://maps.app.goo.gl/abc', expect.any(AbortSignal));
await readLink(result, 'https://maps.app.goo.gl/a https://maps.app.goo.gl/b');
expect(preview).toHaveBeenLastCalledWith(
5,
'https://maps.app.goo.gl/a https://maps.app.goo.gl/b',
expect.any(AbortSignal)
);
preview.mockClear();
act(() => result.current.setUrl(' '));
await act(() => result.current.read());
expect(preview).not.toHaveBeenCalled();
});
it('FE-WALK-IMPORT-003: a refusal is said in the reader’s language, offline and other failures too', async () => {
const { result } = setup();
preview.mockRejectedValueOnce({
response: { status: 400, data: { error: 'Not on foot.', reason: 'not_walking' } },
});
await readLink(result, ROUTE);
expect(result.current.phase).toBe('link');
expect(result.current.failure).toBe(
'That route is not planned on foot. Switch Google Maps to walking and share the route again.'
);
preview.mockRejectedValueOnce(new OnlineOnlyError());
await act(() => result.current.read());
expect(result.current.failure).toBe('Reading a link needs a connection.');
preview.mockRejectedValueOnce(new Error('Network Error'));
await act(() => result.current.read());
expect(result.current.failure).toBe('The link could not be read just now. Try again in a moment.');
// The link stays as typed for another try.
expect(result.current.url).toBe(ROUTE);
});
it('FE-WALK-IMPORT-004: a newer read and closing drop the request before it answers', async () => {
const answers: Array<(value: WalkImportPreviewResponse) => void> = [];
preview.mockImplementation(() => new Promise((resolve) => answers.push(resolve)));
const { result } = setup();
act(() => result.current.show());
act(() => result.current.setUrl(ROUTE));
let first: Promise<void> = Promise.resolve();
act(() => {
first = result.current.read();
});
expect(result.current.phase).toBe('reading');
expect(result.current.canRead).toBe(false);
const firstSignal = preview.mock.calls[0][2] as AbortSignal;
let second: Promise<void> = Promise.resolve();
act(() => {
second = result.current.read();
});
expect(firstSignal.aborted).toBe(true);
const secondSignal = preview.mock.calls[1][2] as AbortSignal;
act(() => result.current.close());
expect(secondSignal.aborted).toBe(true);
await act(async () => {
answers.forEach((resolve) => resolve(PREVIEW));
await Promise.all([first, second]);
});
expect(result.current.open).toBe(false);
expect(result.current.preview).toBeNull();
});
it('FE-WALK-IMPORT-005: a failure that comes after closing is not shown, and unmounting drops the request', async () => {
let fail: (reason: unknown) => void = () => undefined;
preview.mockImplementation(() => new Promise((_resolve, reject) => (fail = reject)));
const { result, unmount } = setup();
act(() => result.current.show());
act(() => result.current.setUrl(ROUTE));
let pending: Promise<void> = Promise.resolve();
act(() => {
pending = result.current.read();
});
act(() => result.current.close());
await act(async () => {
fail(new Error('late'));
await pending;
});
expect(result.current.failure).toBeNull();
act(() => result.current.show());
act(() => result.current.setUrl(ROUTE));
act(() => {
void result.current.read();
});
const signal = preview.mock.calls[1][2] as AbortSignal;
unmount();
expect(signal.aborted).toBe(true);
});
it('FE-WALK-IMPORT-006: loads only the stops with a position, in order and with their names, as a walk from Google Maps', async () => {
const { result, planner: p } = setup();
await readLink(result, ROUTE);
act(() => result.current.load());
expect(p.startDerivedTour).toHaveBeenCalledExactlyOnceWith({
name: 'Walk from Google Maps',
difficulty: 2,
points: [
{ lat: 48.1, lng: 11.5, name: 'Cathedral' },
{ lat: 48.12, lng: 11.52, name: null },
{ lat: 48.13, lng: 11.53, name: 'Park' },
],
inPlace: false,
tourType: 'walk',
source: 'google_maps',
});
expect(result.current.open).toBe(false);
});
it('FE-WALK-IMPORT-007: stays open when the planner does not take it, and loads nothing with fewer than two positions', async () => {
const refusing = { tripId: 5, startDerivedTour: vi.fn(() => false) };
const { result } = setup(refusing);
await readLink(result, ROUTE);
act(() => result.current.load());
expect(refusing.startDerivedTour).toHaveBeenCalledTimes(1);
expect(result.current.open).toBe(true);
act(() => result.current.back());
expect(result.current.phase).toBe('link');
expect(result.current.preview).toBeNull();
expect(result.current.url).toBe(ROUTE);
preview.mockResolvedValueOnce({
...PREVIEW,
stations: [PREVIEW.stations[0], PREVIEW.stations[1]],
});
await act(() => result.current.read());
expect(result.current.canLoad).toBe(false);
act(() => result.current.load());
expect(refusing.startDerivedTour).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,132 @@
import type { WalkImportPreviewResponse, WalkImportStation } from '@trek/shared';
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from '../../../i18n';
import { OnlineOnlyError } from '../../../repo/onlineOnly';
import { tourWalkImportRepo, walkImportRefusalOf } from '../../../repo/tourWalkImportRepo';
import type { TourPlannerController } from '../planner/useTourPlanner';
type Phase = 'link' | 'reading' | 'preview';
type Translate = ReturnType<typeof useTranslation>['t'];
/** A stop the link gives a position. */
type PlacedStation = WalkImportStation & { lat: number; lng: number };
const isPlaced = (station: WalkImportStation): station is PlacedStation => station.lat !== null && station.lng !== null;
const WORD = /\s+/;
const HTTPS_LINK = /^https:\/\/\S+$/i;
/**
* The link in what was pasted. The Google Maps app shares a route as its
* title and the link; a text holding exactly one https link among other words
* is taken as that link. Anything else goes to the server as typed.
*/
function linkIn(text: string): string {
const typed = text.trim();
const links = typed.split(WORD).filter((word) => HTTPS_LINK.test(word));
return links.length === 1 ? links[0] : typed;
}
/** What the dialog says when a link was not read, in the reader's language. */
function failureOf(err: unknown, t: Translate): string {
if (err instanceof OnlineOnlyError) return t('tours.walkImport.offline');
const reason = walkImportRefusalOf(err);
return reason ? t(`tours.walkImport.refusal.${reason}`) : t('tours.walkImport.failed');
}
/**
* CW-07: a city walk from a Google Maps walking route. The dialog reads the
* link pasted into it (the server follows a short link and refuses a route not
* on foot), shows the stops in their order, those without a position marked,
* and only on an explicit load hands the positioned stops to the planner as a
* new, unsaved walk with their names, which TREK then routes on foot itself.
* Closing, going back or a failure leaves the planner as it was.
*/
export function useWalkImport({ planner }: { planner: Pick<TourPlannerController, 'tripId' | 'startDerivedTour'> }) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const [url, setUrl] = useState('');
const [phase, setPhase] = useState<Phase>('link');
const [preview, setPreview] = useState<WalkImportPreviewResponse | null>(null);
const [failure, setFailure] = useState<string | null>(null);
const requestRef = useRef<AbortController | null>(null);
// A read still under way when the planner goes is dropped with it.
useEffect(() => () => requestRef.current?.abort(), []);
const stations = preview?.stations ?? [];
const placed = stations.filter(isPlaced);
const reset = () => {
requestRef.current?.abort();
requestRef.current = null;
setPhase('link');
setPreview(null);
setFailure(null);
};
const show = () => {
reset();
setUrl('');
setOpen(true);
};
const close = () => {
reset();
setOpen(false);
};
const read = async () => {
const link = linkIn(url);
if (!link) return;
requestRef.current?.abort();
const request = new AbortController();
requestRef.current = request;
setPhase('reading');
setFailure(null);
try {
const answer = await tourWalkImportRepo.preview(planner.tripId, link, request.signal);
if (request.signal.aborted) return;
setPreview(answer);
setPhase('preview');
} catch (err: unknown) {
if (request.signal.aborted) return;
setFailure(failureOf(err, t));
setPhase('link');
}
};
const load = () => {
if (placed.length < 2) return;
const started = planner.startDerivedTour({
name: t('tours.walkImport.defaultName'),
difficulty: 2,
points: placed.map(({ lat, lng, name }) => ({ lat, lng, name })),
inPlace: false,
tourType: 'walk',
source: 'google_maps',
});
if (started) close();
};
return {
open,
show,
close,
url,
setUrl,
phase,
preview,
failure,
/** How many stops the link leaves without a position; they are left out on load. */
unplaced: stations.length - placed.length,
canRead: phase !== 'reading' && url.trim().length > 0,
canLoad: phase === 'preview' && placed.length >= 2,
read,
/** Back to the link, which stays as typed. */
back: reset,
load,
};
}
export type WalkImport = ReturnType<typeof useWalkImport>;