mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 23:50:08 +00:00
feat(tours): download a saved tour as a GPX file (PR1-06A)
A saved tour can be handed over as a GPX file on purpose: its whole saved line as one track with the heights it has and none it lacks, its name, description and link, and the activity in <type>. The file is named after the tour. A tour without a line of two points is refused with 422 rather than written as a file that imports as nothing; the export changes nothing. GET /api/trips/:tripId/tours/:placeId/export.gpx, readable by anyone who sees the trip, and the MCP tool export_tour_gpx with the same rules. The tour detail gets a "GPX" action beside the navigation, the planner head a download button that waits while the tour has unsaved changes. The tours rail head now uses the same plain icon buttons as the editor.
This commit is contained in:
@@ -15,8 +15,11 @@ import { fs } from '../shared/DialogShell'
|
||||
export const PANEL_BAR = 'flex min-h-[52px] flex-none items-center gap-1.5 border-b border-edge-faint px-3 py-2'
|
||||
|
||||
/** A 32px icon control on a panel bar. Raised like an active filter tab while `active`. */
|
||||
export function BarButton({ label, onClick, active = false, disabled = false, children, className = '', ariaPressed, ariaExpanded, ariaHaspopup, placement = 'bottom' }: {
|
||||
export function BarButton({ label, tooltip, onClick, active = false, disabled = false, children, className = '', ariaPressed, ariaExpanded, ariaHaspopup, placement = 'bottom', testId }: {
|
||||
label: string
|
||||
/** A longer explanation for the tooltip; the label still names the button. */
|
||||
tooltip?: string
|
||||
testId?: string
|
||||
onClick: (e: MouseEvent<HTMLButtonElement>) => void
|
||||
active?: boolean
|
||||
disabled?: boolean
|
||||
@@ -28,8 +31,8 @@ export function BarButton({ label, onClick, active = false, disabled = false, ch
|
||||
placement?: 'top' | 'bottom' | 'left' | 'right'
|
||||
}) {
|
||||
return (
|
||||
<Tooltip label={label} placement={placement}>
|
||||
<button type="button" onClick={onClick} disabled={disabled} aria-label={label}
|
||||
<Tooltip label={tooltip ?? label} placement={placement}>
|
||||
<button type="button" onClick={onClick} disabled={disabled} aria-label={label} data-testid={testId}
|
||||
aria-pressed={ariaPressed} aria-expanded={ariaExpanded} aria-haspopup={ariaHaspopup}
|
||||
className={`grid h-8 w-8 flex-none place-items-center rounded-[10px] transition-colors disabled:cursor-default disabled:opacity-40 ${active ? 'bg-surface-card text-content shadow-sm' : 'text-content-muted enabled:hover:bg-surface-card enabled:hover:text-content'} ${className}`}>
|
||||
{children}
|
||||
|
||||
@@ -47,6 +47,7 @@ import { Tooltip } from '../shared/Tooltip';
|
||||
import TrackColorPicker from '../shared/TrackColorPicker';
|
||||
import { markdownLinkComponents } from '../shared/markdownLink';
|
||||
import { TourDayRowAvatar } from './TourDayRowFacts';
|
||||
import { TourGpxExportButton } from './TourGpxExportButton';
|
||||
import { PaddleCheckSection } from './paddle/PaddleCheckSection';
|
||||
import { PaddleWindSection } from './paddle/PaddleWindCard';
|
||||
import { TourProvenanceBlock } from './provenance/TourProvenanceSection';
|
||||
@@ -588,6 +589,10 @@ export default function TourDetailDialog({
|
||||
</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
{/* A tour written here offline has no server copy to export until it syncs. */}
|
||||
{analysis && place.id > 0 && (
|
||||
<TourGpxExportButton target={{ tripId: place.trip_id, placeId: place.id, name: place.name }} />
|
||||
)}
|
||||
{canEdit && onSaveAsNew && <SaveAsNewButton onSave={() => onSaveAsNew(tour)} />}
|
||||
<FooterSpacer />
|
||||
{canEdit && onDelete && (
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Download, Loader2 } from 'lucide-react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { BarButton } from '../Planner/planParts';
|
||||
import { DialogButton } from '../shared/DialogShell';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
import { useTourGpxExport, type TourGpxExportTarget } from './useTourGpxExport';
|
||||
|
||||
/**
|
||||
* PR1-06A in a footer: the saved tour as a GPX file, its own action beside
|
||||
* the navigation, which only leads to the start. "GPX" says the format, the
|
||||
* tooltip what the file holds.
|
||||
*/
|
||||
export function TourGpxExportButton({ target }: { target: TourGpxExportTarget }) {
|
||||
const { t } = useTranslation();
|
||||
const { exportGpx, exporting } = useTourGpxExport();
|
||||
return (
|
||||
<Tooltip label={t('tours.gpxExport.hint')}>
|
||||
<span className="inline-flex">
|
||||
<DialogButton
|
||||
onClick={() => void exportGpx(target)}
|
||||
disabled={exporting}
|
||||
aria-label={t('tours.gpxExport.action')}
|
||||
data-testid="tour-gpx-export"
|
||||
icon={exporting ? <Loader2 size={14} className="animate-spin" /> : <Download size={14} strokeWidth={2} />}
|
||||
>
|
||||
<span className="max-sm:hidden">GPX</span>
|
||||
</DialogButton>
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The same export in the planner's head. While the tour has unsaved changes
|
||||
* the file would not hold them, so the button waits for the save and says so.
|
||||
*/
|
||||
export function TourGpxExportBarButton({ target, unsaved }: { target: TourGpxExportTarget; unsaved: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const { exportGpx, exporting } = useTourGpxExport();
|
||||
return (
|
||||
<BarButton
|
||||
label={t(unsaved ? 'tours.gpxExport.saveFirst' : 'tours.gpxExport.action')}
|
||||
onClick={() => void exportGpx(target)}
|
||||
disabled={unsaved || exporting}
|
||||
>
|
||||
{exporting ? <Loader2 size={15} className="animate-spin" /> : <Download size={15} strokeWidth={2} />}
|
||||
</BarButton>
|
||||
);
|
||||
}
|
||||
@@ -38,6 +38,7 @@ import type { RecordedTrack } from '../useRecordedTrack'
|
||||
import type { TourGpxImport } from '../useTourGpxImport'
|
||||
import { type AssignTourToDay, useTourDayAssignment } from '../useTourDayAssignment'
|
||||
import WandererMark from '../wanderer/WandererMark'
|
||||
import { TourGpxExportBarButton } from '../TourGpxExportButton'
|
||||
|
||||
const STATUS_KEY: Partial<Record<TourPlannerStatus, string>> = {
|
||||
dirty: 'tours.planner.status.dirty',
|
||||
@@ -291,6 +292,9 @@ function GpxViewRail({
|
||||
sub={tour.name}
|
||||
aside={<SoftPill>{hikeSourceBadgeLabel(tour, t)}</SoftPill>}
|
||||
/>
|
||||
{tour.place_id > 0 && (
|
||||
<TourGpxExportBarButton target={{ tripId: planner.tripId, placeId: tour.place_id, name: tour.name }} unsaved={false} />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto px-3 py-3">
|
||||
{conversion && <TourConversionSection conversion={conversion} />}
|
||||
@@ -399,6 +403,12 @@ export function TourPlannerRail({ planner,
|
||||
<ArrowLeft size={16} strokeWidth={2} />
|
||||
</BarButton>
|
||||
<RailTitle title={t(isSavedEdit ? 'tours.planner.editTitle' : 'tours.planner.newTitle')} aside={<RailStatusBadges planner={planner} />} />
|
||||
{planner.mode.type === 'edit-saved' && planner.mode.placeId > 0 && (
|
||||
<TourGpxExportBarButton
|
||||
target={{ tripId: planner.tripId, placeId: planner.mode.placeId, name: planner.name }}
|
||||
unsaved={planner.hasUnsavedChanges}
|
||||
/>
|
||||
)}
|
||||
<BarButton label={t('tours.planner.undo')} onClick={() => { if (canEdit && !isSaving) planner.undo() }} disabled={locked || !planner.canUndo}>
|
||||
<Undo2 size={15} strokeWidth={2} />
|
||||
</BarButton>
|
||||
@@ -557,26 +567,20 @@ function NewTourConfirmDialog({ planner, canEdit }: { planner: TourPlannerContro
|
||||
)
|
||||
}
|
||||
|
||||
/** The round GPX import button in the tours rail's head; the file drop on the workspace does the same. */
|
||||
/** The GPX import in the tours rail's head, an icon like the editor's; the file drop on the workspace does the same. */
|
||||
function RailImportButton({ gpxImport, disabled }: { gpxImport: TourGpxImport; disabled: boolean }) {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<Tooltip label={t('tours.import.hint')}>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('tours.import.button')}
|
||||
data-testid="tour-rail-import-gpx"
|
||||
disabled={gpxImport.importing || disabled}
|
||||
onClick={gpxImport.pick}
|
||||
className="mt-1 grid h-[26px] w-[26px] flex-none place-items-center rounded-full bg-surface-card text-content-muted shadow-sm ring-1 ring-edge-faint transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent enabled:hover:bg-accent enabled:hover:text-accent-text enabled:hover:ring-transparent disabled:cursor-default disabled:opacity-40"
|
||||
>
|
||||
{gpxImport.importing ? (
|
||||
<Loader2 size={13} strokeWidth={2.4} className="animate-spin" />
|
||||
) : (
|
||||
<FileDown size={13} strokeWidth={2.4} />
|
||||
)}
|
||||
</button>
|
||||
</Tooltip>
|
||||
<BarButton
|
||||
label={t('tours.import.button')}
|
||||
tooltip={t('tours.import.hint')}
|
||||
testId="tour-rail-import-gpx"
|
||||
disabled={gpxImport.importing || disabled}
|
||||
onClick={gpxImport.pick}
|
||||
className="focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent"
|
||||
>
|
||||
{gpxImport.importing ? <Loader2 size={15} strokeWidth={2} className="animate-spin" /> : <FileDown size={15} strokeWidth={2} />}
|
||||
</BarButton>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -673,13 +677,11 @@ export function TourPlannerToursRail({ planner, tours, days, loading, onAssignTo
|
||||
<RailTitle title={t('tours.planner.tripTours')} />
|
||||
{canEdit && gpxImport && <RailImportButton gpxImport={gpxImport} disabled={isSaving} />}
|
||||
{canEdit && planner.mode.type !== 'neutral' && (
|
||||
<Tooltip label={t('tours.planner.newTour')}>
|
||||
<button type="button" aria-label={t('tours.planner.newTour')} data-testid="tour-rail-new-tour"
|
||||
disabled={isSaving} onClick={() => { if (!isSaving) planner.startNewTour() }}
|
||||
className="mt-1 grid h-[26px] w-[26px] flex-none place-items-center rounded-full bg-accent text-accent-text shadow-sm transition-opacity hover:opacity-90 focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent disabled:cursor-default disabled:opacity-40">
|
||||
<Plus size={14} strokeWidth={2.4} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
<BarButton label={t('tours.planner.newTour')} testId="tour-rail-new-tour" disabled={isSaving}
|
||||
onClick={() => { if (!isSaving) planner.startNewTour() }}
|
||||
className="focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent">
|
||||
<Plus size={16} strokeWidth={2} />
|
||||
</BarButton>
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -927,7 +927,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
description, savedDurationSeconds, editingPlaceId, enrichedGeometry, invalidateDetailRequest, name, onSaved, plannedDurationMinutes, storageKey, tripId, typeFields, waypoints, website])
|
||||
|
||||
return {
|
||||
canEdit, canAssign,
|
||||
tripId, canEdit, canAssign,
|
||||
name, setName, maxHikingDifficulty, setMaxHikingDifficulty,
|
||||
tourType, setTourType, isPaddle, paddle, paddleSpeedInvalid, paddleIncomplete,
|
||||
description, setDescription, website, setWebsite, websiteInvalid,
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import { act, fireEvent, render, renderHook, screen } from '@testing-library/react';
|
||||
import { AxiosError, AxiosHeaders } from 'axios';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { attachmentFilename } from '../../api/tourGpxExport';
|
||||
import { TourGpxExportBarButton, TourGpxExportButton } from './TourGpxExportButton';
|
||||
import { useTourGpxExport } from './useTourGpxExport';
|
||||
|
||||
const repo = vi.hoisted(() => ({ exportGpx: vi.fn() }));
|
||||
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }));
|
||||
const download = vi.hoisted(() => ({ downloadBlob: vi.fn() }));
|
||||
vi.mock('../../repo/tourRepo', () => ({ tourRepo: repo }));
|
||||
vi.mock('../shared/Toast', () => ({ useToast: () => toast }));
|
||||
vi.mock('../../utils/fileDownload', () => download);
|
||||
|
||||
const target = { tripId: 1, placeId: 7, name: 'Kramer' };
|
||||
const blob = new Blob(['<gpx/>'], { type: 'application/gpx+xml' });
|
||||
|
||||
function refused(status: number) {
|
||||
const headers = new AxiosHeaders();
|
||||
return new AxiosError('refused', 'ERR', undefined, undefined, {
|
||||
status,
|
||||
statusText: '',
|
||||
headers,
|
||||
config: { headers },
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
repo.exportGpx.mockResolvedValue({ offline: false, blob, filename: 'Kramer-über.gpx' });
|
||||
});
|
||||
|
||||
describe('attachmentFilename (PR1-06A)', () => {
|
||||
it('prefers the UTF-8 name, falls back to the plain one, and reads nothing from nothing', () => {
|
||||
expect(attachmentFilename(`attachment; filename="Kramer-_ber.gpx"; filename*=UTF-8''Kramer-%C3%BCber.gpx`)).toBe(
|
||||
'Kramer-über.gpx'
|
||||
);
|
||||
expect(attachmentFilename('attachment; filename="plain.gpx"')).toBe('plain.gpx');
|
||||
expect(attachmentFilename(`attachment; filename="safe.gpx"; filename*=UTF-8''%E0%A4%A`)).toBe('safe.gpx');
|
||||
expect(attachmentFilename('attachment')).toBeNull();
|
||||
expect(attachmentFilename(undefined)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('useTourGpxExport (PR1-06A)', () => {
|
||||
it('hands the server file to the browser under its own name', async () => {
|
||||
const { result } = renderHook(() => useTourGpxExport());
|
||||
await act(() => result.current.exportGpx(target));
|
||||
expect(repo.exportGpx).toHaveBeenCalledWith(1, 7, expect.any(AbortSignal));
|
||||
expect(download.downloadBlob).toHaveBeenCalledWith(blob, 'Kramer-über.gpx');
|
||||
expect(result.current.exporting).toBe(false);
|
||||
expect(toast.error).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('names the file after the tour when the server gave no name', async () => {
|
||||
repo.exportGpx.mockResolvedValue({ offline: false, blob, filename: null });
|
||||
const { result } = renderHook(() => useTourGpxExport());
|
||||
await act(() => result.current.exportGpx({ ...target, name: ' ' }));
|
||||
expect(download.downloadBlob).toHaveBeenCalledWith(blob, 'tour.gpx');
|
||||
});
|
||||
|
||||
it('says why nothing came: offline, a tour without a route, or a failure', async () => {
|
||||
const { result } = renderHook(() => useTourGpxExport());
|
||||
repo.exportGpx.mockResolvedValueOnce({ offline: true });
|
||||
await act(() => result.current.exportGpx(target));
|
||||
expect(toast.info).toHaveBeenCalledWith('tours.gpxExport.offline');
|
||||
|
||||
repo.exportGpx.mockRejectedValueOnce(refused(422));
|
||||
await act(() => result.current.exportGpx(target));
|
||||
expect(toast.error).toHaveBeenLastCalledWith('tours.gpxExport.noRoute');
|
||||
|
||||
repo.exportGpx.mockRejectedValueOnce(new Error('network'));
|
||||
await act(() => result.current.exportGpx(target));
|
||||
expect(toast.error).toHaveBeenLastCalledWith('tours.gpxExport.failed');
|
||||
expect(download.downloadBlob).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('runs one export at a time, and a caller gone mid-download cancels it quietly', async () => {
|
||||
let finish: (value: unknown) => void = () => undefined;
|
||||
repo.exportGpx.mockImplementation(() => new Promise((resolve) => (finish = resolve)));
|
||||
const { result, unmount } = renderHook(() => useTourGpxExport());
|
||||
act(() => {
|
||||
void result.current.exportGpx(target);
|
||||
});
|
||||
expect(result.current.exportingId).toBe(7);
|
||||
await act(() => result.current.exportGpx(target));
|
||||
expect(repo.exportGpx).toHaveBeenCalledTimes(1);
|
||||
|
||||
const signal = repo.exportGpx.mock.calls[0][2] as AbortSignal;
|
||||
unmount();
|
||||
expect(signal.aborted).toBe(true);
|
||||
await act(async () => finish({ offline: false, blob, filename: 'late.gpx' }));
|
||||
expect(toast.error).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('TourGpxExportButton (PR1-06A)', () => {
|
||||
it('exports from the footer, apart from the navigation', async () => {
|
||||
render(<TourGpxExportButton target={target} />);
|
||||
const button = screen.getByTestId('tour-gpx-export');
|
||||
expect(button).toHaveAccessibleName('tours.gpxExport.action');
|
||||
await act(async () => fireEvent.click(button));
|
||||
expect(repo.exportGpx).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('waits in the planner head while the tour has unsaved changes, and says so', () => {
|
||||
const { rerender } = render(<TourGpxExportBarButton target={target} unsaved />);
|
||||
expect(screen.getByRole('button', { name: 'tours.gpxExport.saveFirst' })).toBeDisabled();
|
||||
rerender(<TourGpxExportBarButton target={target} unsaved={false} />);
|
||||
const button = screen.getByRole('button', { name: 'tours.gpxExport.action' });
|
||||
expect(button).toBeEnabled();
|
||||
fireEvent.click(button);
|
||||
expect(repo.exportGpx).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { isAxiosError } from 'axios';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { tourRepo } from '../../repo/tourRepo';
|
||||
import { downloadBlob } from '../../utils/fileDownload';
|
||||
import { useToast } from '../shared/Toast';
|
||||
|
||||
/** What a tour's GPX export needs to know about the tour. */
|
||||
export interface TourGpxExportTarget {
|
||||
tripId: number | string;
|
||||
placeId: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* PR1-06A: a saved tour handed over as a GPX file, started on purpose. The
|
||||
* file is the server's (the saved line, as saved), so an unsaved edit in the
|
||||
* planner is not in it. One export at a time per caller; a dialog closed
|
||||
* mid-download cancels it. Nothing about the tour changes either way.
|
||||
*/
|
||||
export function useTourGpxExport() {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const [exportingId, setExportingId] = useState<number | null>(null);
|
||||
const abortRef = useRef<AbortController | null>(null);
|
||||
|
||||
useEffect(() => () => abortRef.current?.abort(), []);
|
||||
|
||||
const exportGpx = useCallback(
|
||||
async ({ tripId, placeId, name }: TourGpxExportTarget) => {
|
||||
if (abortRef.current) return;
|
||||
const controller = new AbortController();
|
||||
abortRef.current = controller;
|
||||
setExportingId(placeId);
|
||||
try {
|
||||
const result = await tourRepo.exportGpx(tripId, placeId, controller.signal);
|
||||
if (!('blob' in result)) {
|
||||
toast.info(t('tours.gpxExport.offline'));
|
||||
return;
|
||||
}
|
||||
downloadBlob(result.blob, result.filename ?? `${name.trim() || 'tour'}.gpx`);
|
||||
} catch (error: unknown) {
|
||||
if (controller.signal.aborted) return;
|
||||
const noRoute = isAxiosError(error) && error.response?.status === 422;
|
||||
toast.error(t(noRoute ? 'tours.gpxExport.noRoute' : 'tours.gpxExport.failed'));
|
||||
} finally {
|
||||
if (abortRef.current === controller) abortRef.current = null;
|
||||
if (!controller.signal.aborted) setExportingId(null);
|
||||
}
|
||||
},
|
||||
[t, toast]
|
||||
);
|
||||
|
||||
return { exportGpx, exportingId, exporting: exportingId !== null };
|
||||
}
|
||||
Reference in New Issue
Block a user