mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-10-20 22:16:26 +00:00
Compare commits
163 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 988890866a | |||
| 0dda5bc3e9 | |||
| 7fa8b3fe35 | |||
| 112017a9e8 | |||
| cb5c5ab4a1 | |||
| bed9f53615 | |||
| a8e2486cd3 | |||
| 5d5015066f | |||
| 3e8d192305 | |||
| bafb74f872 | |||
| b71e32cf12 | |||
| 786df612fd | |||
| e6002444a1 | |||
| e453816ded | |||
| b9ca822d51 | |||
| 20537193b6 | |||
| 60611aee65 | |||
| 6c66cff365 | |||
| d3f574f225 | |||
| e5c5ffbc00 | |||
| 562176bd83 | |||
| ae699187f7 | |||
| 1d72fbd25f | |||
| 2d0c0597b3 | |||
| a85a50e186 | |||
| c8eb510bd4 | |||
| beea4c762b | |||
| d924dcf99d | |||
| 371083ed47 | |||
| eaeaf68352 | |||
| 5156fa2c0a | |||
| 6c6e285c3d | |||
| 93e1156aa4 | |||
| dc19807126 | |||
| 5580ff71a9 | |||
| e42622d71d | |||
| 94674e7572 | |||
| 7f14dde362 | |||
| 9765cf3fee | |||
| c38eb7ebf0 | |||
| e653733390 | |||
| 2655e510fc | |||
| 904eb31e62 | |||
| 76ec302526 | |||
| 810feba413 | |||
| 4009588078 | |||
| ef583ede18 | |||
| 9bc543a387 | |||
| 7291555e95 | |||
| 57f0e2f263 | |||
| de043cfb58 | |||
| 69df85bfa2 | |||
| be6702f3ab | |||
| 164a3633ac | |||
| 204ee2ef86 | |||
| baba2de344 | |||
| 49dd2db040 | |||
| 49e306ea48 | |||
| 1d7c8a63e2 | |||
| fb208a88e2 | |||
| 5ae8ac8e70 | |||
| 20bd384feb | |||
| 58302dc9e4 | |||
| b460cfd9a7 | |||
| 2b8d2e790f | |||
| 2fc9b1991a | |||
| 4d81180fc1 | |||
| 0f600d04f5 | |||
| b53257deaf | |||
| b284095ee0 | |||
| e40e576e39 | |||
| 4d9b84f681 | |||
| 223b056de2 | |||
| 981c372640 | |||
| 839d736905 | |||
| b9391a9921 | |||
| 5e0f216b0c | |||
| a249c861e6 | |||
| 2a40b884a1 | |||
| f5be556c27 | |||
| 6b1488994f | |||
| 2ee4ea1e65 | |||
| a1d683d7bc | |||
| ae726ed370 | |||
| f4750352e6 | |||
| 65ee472d66 | |||
| 73fa7aeb19 | |||
| fbba4fd73b | |||
| 2e1dca9fe9 | |||
| aacc7f2c8d | |||
| f833a05461 | |||
| 65fe8cd6e5 | |||
| 3fe34061fd | |||
| 3659297af1 | |||
| f57a0dbd31 | |||
| 3748bdb815 | |||
| 8fa75b3c4e | |||
| 6ec06c90f4 | |||
| 2449616ee9 | |||
| acc294dd8e | |||
| bde2ad2ca8 | |||
| ae79ab8dad | |||
| 6a0c54cb2f | |||
| a8be1c5b45 | |||
| d0cc6fc2f4 | |||
| f016972a4e | |||
| c80152f41d | |||
| f745ca13c9 | |||
| 4f68029b2c | |||
| 64445a5204 | |||
| bff9bcde92 | |||
| 3572f4b8a3 | |||
| ea9e997338 | |||
| ad2d653e9a | |||
| b177daea3c | |||
| 63a7a4d397 | |||
| f4533fc69b | |||
| 1993ed4d28 | |||
| 1969ca57d9 | |||
| b826ecd425 | |||
| 19946039ad | |||
| 6577595058 | |||
| 78366a9024 | |||
| 0331d9950f | |||
| dfe11e9c4c | |||
| fcdb7e48cd | |||
| 008aaeb408 | |||
| 5ff7e54e09 | |||
| 0169be3d79 | |||
| 68907ec811 | |||
| 51bfb5abd1 | |||
| 1d9b9bf838 | |||
| c83eb42730 | |||
| cd407cf80c | |||
| 71fe69c1f1 | |||
| 54baf85a2a | |||
| 3882feec5c | |||
| 6477bf5e39 | |||
| 971133a1eb | |||
| 0344db6d0c | |||
| 5d265c98de | |||
| 554d6f1b9f | |||
| f79b2020d6 | |||
| 9f0caf8539 | |||
| 7470a2c6d4 | |||
| 4ca5728072 | |||
| 2203ff3a2e | |||
| 0d7e3ceb3d | |||
| 93a508a0e6 | |||
| 0b92dcc86b | |||
| c836ee3988 | |||
| 188953158a | |||
| 20f8266439 | |||
| e5f01e570a | |||
| 2a8dbf91a8 | |||
| ec9e1a7533 | |||
| 3c823e07f4 | |||
| 9ed944c1e6 | |||
| 2955c61c86 | |||
| c97105ce61 | |||
| 290961cced | |||
| 4c594876ef | |||
| d5d2d6b25e |
@@ -26,5 +26,8 @@
|
|||||||
*.eot binary
|
*.eot binary
|
||||||
*.pdf binary
|
*.pdf binary
|
||||||
*.zip binary
|
*.zip binary
|
||||||
|
# Ski area graphs (SGR1) as the Places host writes them, byte for byte
|
||||||
|
*.sgr binary
|
||||||
|
*.gz binary
|
||||||
# A GPX fixture whose byte-order mark and CRLF line endings are what it tests
|
# A GPX fixture whose byte-order mark and CRLF line endings are what it tests
|
||||||
server/tests/fixtures/gpx/bom-crlf.gpx -text
|
server/tests/fixtures/gpx/bom-crlf.gpx -text
|
||||||
|
|||||||
@@ -261,8 +261,11 @@ jobs:
|
|||||||
# constructor parameter does not break its hand-wired call sites at
|
# constructor parameter does not break its hand-wired call sites at
|
||||||
# compile time: the argument arrives as undefined and throws at
|
# compile time: the argument arrives as undefined and throws at
|
||||||
# runtime, if anything reads it at all. This is the step that
|
# runtime, if anything reads it at all. This is the step that
|
||||||
# catches it.
|
# catches it. src and tests together are past 570,000 lines and need
|
||||||
|
# about 4.3 GB, over Node's default heap.
|
||||||
run: cd server && npm run typecheck:tests
|
run: cd server && npm run typecheck:tests
|
||||||
|
env:
|
||||||
|
NODE_OPTIONS: --max-old-space-size=8192
|
||||||
|
|
||||||
- name: Typecheck entity generator
|
- name: Typecheck entity generator
|
||||||
# tsconfig.scripts.json covers generate-entities.ts and migrate-encryption.ts;
|
# tsconfig.scripts.json covers generate-entities.ts and migrate-encryption.ts;
|
||||||
|
|||||||
@@ -102,8 +102,8 @@ env:
|
|||||||
# lower value hangs up on answers that were still coming. Raise it for a slow self-hosted Overpass instance.
|
# lower value hangs up on answers that were still coming. Raise it for a slow self-hosted Overpass instance.
|
||||||
# Defaults to 25000.
|
# Defaults to 25000.
|
||||||
# TREK_PLACES_ENABLED: "false"
|
# TREK_PLACES_ENABLED: "false"
|
||||||
# Place search (suggestions, full search, category buttons, Road trip search, import geocoding, offline downloads)
|
# Place search (suggestions, full search, category buttons, Road trip search, import geocoding, offline downloads,
|
||||||
# asks the TREK Places API at https://places.liketrek.com by default, so the pod makes outbound requests to that
|
# and the OpenStreetMap ways and horse routes Tours reads) asks the TREK Places API at https://places.liketrek.com by default, so the pod makes outbound requests to that
|
||||||
# host. Set "false" to search the way it did before 4.3.0 (OpenStreetMap, or your Google/Amap key) and send
|
# host. Set "false" to search the way it did before 4.3.0 (OpenStreetMap, or your Google/Amap key) and send
|
||||||
# nothing there. There is no switch in the admin panel on purpose: whether searches leave the instance is decided
|
# nothing there. There is no switch in the admin panel on purpose: whether searches leave the instance is decided
|
||||||
# here. Defaults to on.
|
# here. Defaults to on.
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
"trek/no-swallowed-catch": 133,
|
"trek/no-swallowed-catch": 133,
|
||||||
"max-params": 35,
|
"max-params": 35,
|
||||||
"trek/store-without-selector": 69,
|
"trek/store-without-selector": 69,
|
||||||
"react-hooks/refs": 559,
|
"react-hooks/refs": 558,
|
||||||
"react-hooks/set-state-in-effect": 197,
|
"react-hooks/set-state-in-effect": 197,
|
||||||
"@typescript-eslint/no-floating-promises": 167,
|
"@typescript-eslint/no-floating-promises": 167,
|
||||||
"react-hooks/exhaustive-deps": 121,
|
"react-hooks/exhaustive-deps": 121,
|
||||||
@@ -16,7 +16,7 @@
|
|||||||
"react-hooks/immutability": 28,
|
"react-hooks/immutability": 28,
|
||||||
"max-lines-per-function": 133,
|
"max-lines-per-function": 133,
|
||||||
"react-hooks/static-components": 78,
|
"react-hooks/static-components": 78,
|
||||||
"react-hooks/preserve-manual-memoization": 15,
|
"react-hooks/preserve-manual-memoization": 12,
|
||||||
"no-useless-assignment": 7,
|
"no-useless-assignment": 7,
|
||||||
"no-empty": 19,
|
"no-empty": 19,
|
||||||
"trek/no-window-globals": 41,
|
"trek/no-window-globals": 41,
|
||||||
|
|||||||
@@ -223,6 +223,15 @@
|
|||||||
"desktop": ["src/pages/CollectionsPage.tsx"],
|
"desktop": ["src/pages/CollectionsPage.tsx"],
|
||||||
"mobile": ["src/mobile/screens/collections/MCollections.tsx"]
|
"mobile": ["src/mobile/screens/collections/MCollections.tsx"]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"feature": "Collection tours (LIB-03): useCollectionTours, useCollectionTourTakeOver",
|
||||||
|
"hooks": [
|
||||||
|
"src/components/Tours/collection/useCollectionTours.ts",
|
||||||
|
"src/components/Tours/collection/useCollectionTourTakeOver.ts"
|
||||||
|
],
|
||||||
|
"desktop": ["src/components/Tours/collection/CollectionToursSection.tsx"],
|
||||||
|
"mobile": ["src/mobile/screens/collections/MCollTours.tsx"]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"feature": "Copy collection places to a trip",
|
"feature": "Copy collection places to a trip",
|
||||||
"hooks": ["src/components/Collections/useTripCopyPicker.ts"],
|
"hooks": ["src/components/Collections/useTripCopyPicker.ts"],
|
||||||
@@ -571,6 +580,24 @@
|
|||||||
"desktop": ["src/components/Admin/AdminPluginsPanel.tsx"],
|
"desktop": ["src/components/Admin/AdminPluginsPanel.tsx"],
|
||||||
"mobile": ["src/mobile/screens/admin/MAdminPluginsPanel.tsx"]
|
"mobile": ["src/mobile/screens/admin/MAdminPluginsPanel.tsx"]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"feature": "Public transit for one leg, between two city walks from the first one's end, and a journey late for the next walk",
|
||||||
|
"hooks": ["src/components/Planner/useTransitLegPlanner.ts"],
|
||||||
|
"desktop": ["src/components/Planner/DayPlanSidebar.tsx"],
|
||||||
|
"mobile": ["src/mobile/screens/trip/plan/useMPlanTimeline.ts"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"feature": "A tour's start and end in the day plan, its end worked out from its time, and an end that runs into the next timed item",
|
||||||
|
"hooks": ["src/components/Tours/tourDayTime.ts"],
|
||||||
|
"desktop": ["src/components/Planner/DayPlanSidebar.tsx"],
|
||||||
|
"mobile": ["src/mobile/screens/trip/plan/useMPlanTimeline.ts"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"feature": "A multi-day tour put on a day: the whole tour there, or a stage a day from that day on",
|
||||||
|
"hooks": ["src/components/Tours/stages/stageSpread.ts"],
|
||||||
|
"desktop": ["src/components/Tours/stages/TourDayChoiceDialog.tsx", "src/components/Tours/stages/TourDayAddButton.tsx"],
|
||||||
|
"mobile": ["src/mobile/screens/trip/sheets/MTourDayChoiceSheet.tsx"]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"feature": "Reservation form incl. hotel accommodation creation",
|
"feature": "Reservation form incl. hotel accommodation creation",
|
||||||
"hooks": ["src/components/Planner/reservationFormModel.ts", "src/components/Planner/useReservationForm.ts"],
|
"hooks": ["src/components/Planner/reservationFormModel.ts", "src/components/Planner/useReservationForm.ts"],
|
||||||
|
|||||||
@@ -7,14 +7,14 @@
|
|||||||
"src/components/Budget/CostsPanel.tsx": 1816,
|
"src/components/Budget/CostsPanel.tsx": 1816,
|
||||||
"src/components/Map/MapView.tsx": 1401,
|
"src/components/Map/MapView.tsx": 1401,
|
||||||
"src/components/Map/MapViewGL.test.tsx": 2920,
|
"src/components/Map/MapViewGL.test.tsx": 2920,
|
||||||
"src/components/Map/MapViewGL.tsx": 2296,
|
"src/components/Map/MapViewGL.tsx": 2293,
|
||||||
"src/components/Map/RouteCalculator.ts": 1195,
|
"src/components/Map/RouteCalculator.ts": 1195,
|
||||||
"src/components/PDF/TripPDF.tsx": 1082,
|
"src/components/PDF/TripPDF.tsx": 1082,
|
||||||
"src/components/Planner/DayDetailPanel.test.tsx": 2333,
|
"src/components/Planner/DayDetailPanel.test.tsx": 2333,
|
||||||
"src/components/Planner/DayPlanSidebar.test.tsx": 5378,
|
"src/components/Planner/DayPlanSidebar.test.tsx": 5378,
|
||||||
"src/components/Planner/DayPlanSidebar.tsx": 2971,
|
"src/components/Planner/DayPlanSidebar.tsx": 2963,
|
||||||
"src/components/Planner/PlaceFormModal.test.tsx": 2864,
|
"src/components/Planner/PlaceFormModal.test.tsx": 2836,
|
||||||
"src/components/Planner/PlaceFormModal.tsx": 1250,
|
"src/components/Planner/PlaceFormModal.tsx": 1193,
|
||||||
"src/components/Planner/PlaceInspector.tsx": 1304,
|
"src/components/Planner/PlaceInspector.tsx": 1304,
|
||||||
"src/components/Studio/TravelElements.tsx": 1738,
|
"src/components/Studio/TravelElements.tsx": 1738,
|
||||||
"src/components/Studio/autoLayout.ts": 1691,
|
"src/components/Studio/autoLayout.ts": 1691,
|
||||||
@@ -24,7 +24,7 @@
|
|||||||
"src/mobile/screens/admin/MAdminPluginsPanel.tsx": 1507,
|
"src/mobile/screens/admin/MAdminPluginsPanel.tsx": 1507,
|
||||||
"src/pages/JourneyDetailPage.test.tsx": 4030,
|
"src/pages/JourneyDetailPage.test.tsx": 4030,
|
||||||
"src/pages/LoginPage.tsx": 1348,
|
"src/pages/LoginPage.tsx": 1348,
|
||||||
"src/pages/TripPlannerPage.tsx": 1142,
|
"src/pages/TripPlannerPage.tsx": 1140,
|
||||||
"src/pages/atlas/useAtlas.ts": 1287,
|
"src/pages/atlas/useAtlas.ts": 1287,
|
||||||
"src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518,
|
"src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518,
|
||||||
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3309,
|
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3309,
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
// FE-API-COLLECTION-TOURS-001 to FE-API-COLLECTION-TOURS-002
|
||||||
|
//
|
||||||
|
// LIB-03: every method pins its verb, its path and its body, and hands back what
|
||||||
|
// the server answered.
|
||||||
|
import { http, HttpResponse, type JsonBodyType } from 'msw';
|
||||||
|
import { beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
import { server } from '../../tests/helpers/msw/server';
|
||||||
|
import { collectionToursApi } from './collectionTours';
|
||||||
|
|
||||||
|
const BASE = '/api/addons/collections/3/tours';
|
||||||
|
|
||||||
|
let calls: Array<{ method: string; path: string; body: unknown }> = [];
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
calls = [];
|
||||||
|
});
|
||||||
|
|
||||||
|
function record(data: JsonBodyType | null) {
|
||||||
|
return async ({ request }: { request: Request }) => {
|
||||||
|
const text = await request.text();
|
||||||
|
calls.push({ method: request.method, path: new URL(request.url).pathname, body: text ? JSON.parse(text) : null });
|
||||||
|
return data === null ? new HttpResponse(null, { status: 200 }) : HttpResponse.json(data);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('collectionToursApi', () => {
|
||||||
|
it('FE-API-COLLECTION-TOURS-001: lists, reads, keeps and removes the tours of a collection', async () => {
|
||||||
|
server.use(
|
||||||
|
http.get(BASE, record({ tours: [] })),
|
||||||
|
http.get(`${BASE}/4`, record({ tour: { id: 4 }, line: [], points: [], trips: [] })),
|
||||||
|
http.post(BASE, record({ tour: { id: 5 } })),
|
||||||
|
http.delete(`${BASE}/4`, record({ success: true }))
|
||||||
|
);
|
||||||
|
expect(await collectionToursApi.list(3)).toEqual({ tours: [] });
|
||||||
|
expect((await collectionToursApi.detail(3, 4)).tour).toEqual({ id: 4 });
|
||||||
|
expect(await collectionToursApi.save(3, { source_trip_id: 2, source_place_id: 7, name: 'Kept' })).toEqual({
|
||||||
|
tour: { id: 5 },
|
||||||
|
});
|
||||||
|
expect(await collectionToursApi.remove(3, 4)).toBeUndefined();
|
||||||
|
expect(calls).toEqual([
|
||||||
|
{ method: 'GET', path: BASE, body: null },
|
||||||
|
{ method: 'GET', path: `${BASE}/4`, body: null },
|
||||||
|
{ method: 'POST', path: BASE, body: { source_trip_id: 2, source_place_id: 7, name: 'Kept' } },
|
||||||
|
{ method: 'DELETE', path: `${BASE}/4`, body: null },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-API-COLLECTION-TOURS-002: takes a kept tour into a trip with the choice about its points', async () => {
|
||||||
|
server.use(http.post('/api/trips/6/tours/from-collection', record({ tour: { place_id: 9 }, waypoints: [] })));
|
||||||
|
const body = { collection_id: 3, collection_tour_id: 4, include_waypoints: false };
|
||||||
|
expect((await collectionToursApi.takeOver(6, body)).tour).toEqual({ place_id: 9 });
|
||||||
|
expect(calls).toEqual([{ method: 'POST', path: '/api/trips/6/tours/from-collection', body }]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import type {
|
||||||
|
CollectionTourDetailResponse,
|
||||||
|
CollectionTourListResponse,
|
||||||
|
CollectionTourSaveRequest,
|
||||||
|
CollectionTourSaveResponse,
|
||||||
|
CollectionTourTakeOverRequest,
|
||||||
|
TourCreateResponse,
|
||||||
|
} from '@trek/shared';
|
||||||
|
import apiClient from './client';
|
||||||
|
|
||||||
|
const base = (collectionId: number) => `/addons/collections/${collectionId}/tours`;
|
||||||
|
|
||||||
|
/** LIB-03: the whole tours a collection keeps, keeping one, removing one and taking one into a trip. */
|
||||||
|
export const collectionToursApi = {
|
||||||
|
list: (collectionId: number, signal?: AbortSignal): Promise<CollectionTourListResponse> =>
|
||||||
|
apiClient.get(base(collectionId), { signal }).then((r) => r.data),
|
||||||
|
detail: (collectionId: number, tourId: number, signal?: AbortSignal): Promise<CollectionTourDetailResponse> =>
|
||||||
|
apiClient.get(`${base(collectionId)}/${tourId}`, { signal }).then((r) => r.data),
|
||||||
|
save: (collectionId: number, body: CollectionTourSaveRequest): Promise<CollectionTourSaveResponse> =>
|
||||||
|
apiClient.post(base(collectionId), body).then((r) => r.data),
|
||||||
|
remove: (collectionId: number, tourId: number): Promise<void> =>
|
||||||
|
apiClient.delete(`${base(collectionId)}/${tourId}`).then(() => undefined),
|
||||||
|
takeOver: (tripId: number, body: CollectionTourTakeOverRequest): Promise<TourCreateResponse> =>
|
||||||
|
apiClient.post(`/trips/${tripId}/tours/from-collection`, body).then((r) => r.data),
|
||||||
|
};
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
// FE-API-HORSE-001 to FE-API-HORSE-002
|
||||||
|
import { http, HttpResponse } from 'msw';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
|
import { server } from '../../tests/helpers/msw/server';
|
||||||
|
import { horseRoutesApi } from './horseRoutes';
|
||||||
|
|
||||||
|
const reply = { routes: [], truncated: false, source: 'openstreetmap', attribution: '© OpenStreetMap contributors' };
|
||||||
|
const BBOX = '47.10000,11.20000,47.30000,11.50000';
|
||||||
|
|
||||||
|
describe('horseRoutesApi.list', () => {
|
||||||
|
it('FE-API-HORSE-001: asks GET /api/trips/:tripId/tours/horse-routes with the view and returns the body', async () => {
|
||||||
|
let url = '';
|
||||||
|
server.use(
|
||||||
|
http.get('/api/trips/7/tours/horse-routes', ({ request }) => {
|
||||||
|
url = request.url;
|
||||||
|
return HttpResponse.json(reply);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(horseRoutesApi.list(7, BBOX)).resolves.toEqual(reply);
|
||||||
|
expect(new URL(url).searchParams.get('bbox')).toBe(BBOX);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-API-HORSE-002: no Overpass mirror answering (502) rejects', async () => {
|
||||||
|
server.use(
|
||||||
|
http.get('/api/trips/7/tours/horse-routes', () =>
|
||||||
|
HttpResponse.json({ error: 'Horse route data is unavailable right now' }, { status: 502 })
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(horseRoutesApi.list(7, BBOX)).rejects.toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import apiClient from './client';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How long the browser waits for GET /api/trips/:tripId/tours/horse-routes.
|
||||||
|
* The server races the Overpass mirrors under its own deadline (25 s by
|
||||||
|
* default) and answers 502 when none made it, so this sits just above it, as
|
||||||
|
* the via ferrata layer's wait does.
|
||||||
|
*/
|
||||||
|
const HORSE_ROUTES_TIMEOUT_MS = 30_000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HOR-01 GET /api/trips/:tripId/tours/horse-routes: the signposted horse
|
||||||
|
* routes OpenStreetMap knows inside one map view. The answer comes back
|
||||||
|
* unparsed; repo/horseRouteRepo.ts checks it against the shared contract.
|
||||||
|
*/
|
||||||
|
export const horseRoutesApi = {
|
||||||
|
list: (tripId: number | string, bbox: string, signal?: AbortSignal): Promise<unknown> =>
|
||||||
|
apiClient
|
||||||
|
.get(`/trips/${tripId}/tours/horse-routes`, { params: { bbox }, signal, timeout: HORSE_ROUTES_TIMEOUT_MS })
|
||||||
|
.then((response) => response.data as unknown),
|
||||||
|
};
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { skiRouteResponseSchema, type SkiRouteInput, type SkiRouteResponse } from '@trek/shared';
|
||||||
|
import apiClient from './client';
|
||||||
|
|
||||||
|
/** The piste router: a ski tour's legs planned on the piste data the server keeps, held to the contract. */
|
||||||
|
export const skiRouteApi = {
|
||||||
|
plan: (tripId: number | string, request: SkiRouteInput, signal?: AbortSignal): Promise<SkiRouteResponse> =>
|
||||||
|
apiClient.post(`/trips/${tripId}/ski/route`, request, { signal }).then((r) => skiRouteResponseSchema.parse(r.data)),
|
||||||
|
};
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import type { TourActivityAssignRequest, TourDetailResponse } from '@trek/shared';
|
||||||
|
import apiClient from './client';
|
||||||
|
|
||||||
|
/** ACT-01: the recorded tracks of a tour, assigned and taken off; both answer the tour's detail. */
|
||||||
|
export const tourActivitiesApi = {
|
||||||
|
assign: (
|
||||||
|
tripId: number | string,
|
||||||
|
placeId: number | string,
|
||||||
|
body: TourActivityAssignRequest
|
||||||
|
): Promise<TourDetailResponse> =>
|
||||||
|
apiClient.put(`/trips/${tripId}/tours/${placeId}/activities`, body).then((r) => r.data),
|
||||||
|
unassign: (tripId: number | string, placeId: number | string, activityId: number): Promise<TourDetailResponse> =>
|
||||||
|
apiClient.delete(`/trips/${tripId}/tours/${placeId}/activities/${activityId}`).then((r) => r.data),
|
||||||
|
};
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import type { TourActivityExclusionRequest, TourActivityStatsResponse } from '@trek/shared';
|
||||||
|
import apiClient from './client';
|
||||||
|
|
||||||
|
/** STA-02: the user's own tour activities across their trips, and leaving one out of them; both answer the sums. */
|
||||||
|
export const tourActivityStatsApi = {
|
||||||
|
get: (signal?: AbortSignal): Promise<TourActivityStatsResponse> =>
|
||||||
|
apiClient.get('/tours/activity-stats', { signal }).then((r) => r.data),
|
||||||
|
setExcluded: (body: TourActivityExclusionRequest): Promise<TourActivityStatsResponse> =>
|
||||||
|
apiClient.put('/tours/activity-stats/exclusions', body).then((r) => r.data),
|
||||||
|
};
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { AdminFeatureToggleResponse } from '@trek/shared';
|
import type { AdminFeatureToggleResponse } from '@trek/shared';
|
||||||
import apiClient from './client';
|
import apiClient from './client';
|
||||||
|
|
||||||
/** An admin's switch for a map the Tours planner offers on its operator's terms. */
|
/** An admin's switch for a map or a service the Tours planner offers on its operator's terms. */
|
||||||
function tourBaseMapAdminApi(path: string) {
|
function tourBaseMapAdminApi(path: string) {
|
||||||
return {
|
return {
|
||||||
get: (): Promise<AdminFeatureToggleResponse> => apiClient.get(path).then((r) => r.data),
|
get: (): Promise<AdminFeatureToggleResponse> => apiClient.get(path).then((r) => r.data),
|
||||||
@@ -14,3 +14,5 @@ function tourBaseMapAdminApi(path: string) {
|
|||||||
export const hikingMapAdminApi = tourBaseMapAdminApi('/admin/tours-hiking-map');
|
export const hikingMapAdminApi = tourBaseMapAdminApi('/admin/tours-hiking-map');
|
||||||
/** BIK-06: CyclOSM for a bike tour. */
|
/** BIK-06: CyclOSM for a bike tour. */
|
||||||
export const cycleMapAdminApi = tourBaseMapAdminApi('/admin/tours-cycle-map');
|
export const cycleMapAdminApi = tourBaseMapAdminApi('/admin/tours-cycle-map');
|
||||||
|
/** SKI-02: the piste router, which plans ski tours on the Places host's piste data. */
|
||||||
|
export const skiRoutingAdminApi = tourBaseMapAdminApi('/admin/tours-ski-routing');
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { TourGpxImportFields, TourGpxPreviewResponse, TourImportGpxResponse } from '@trek/shared';
|
import type { TourGpxImportFields, TourGpxPreviewResponse, TourImportGpxResponse } from '@trek/shared';
|
||||||
import { postMultipart } from './client';
|
import { postMultipart } from './client';
|
||||||
|
|
||||||
/** A GPX file and the fields beside it, as the Tours import routes read a multipart body. */
|
/** A GPX, KML or KMZ file and the fields beside it, as the Tours import routes read a multipart body. */
|
||||||
function gpxForm(file: File, fields?: TourGpxImportFields): FormData {
|
function gpxForm(file: File, fields?: TourGpxImportFields): FormData {
|
||||||
const fd = new FormData();
|
const fd = new FormData();
|
||||||
fd.append('file', file);
|
fd.append('file', file);
|
||||||
@@ -9,7 +9,10 @@ function gpxForm(file: File, fields?: TourGpxImportFields): FormData {
|
|||||||
return fd;
|
return fd;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The Tours GPX import: a file read for its preview first (PAD-02), then imported as the type chosen. */
|
/**
|
||||||
|
* The Tours file import: a GPX, KML or KMZ file (IO-02) read for its preview
|
||||||
|
* first (PAD-02), then imported as the type chosen.
|
||||||
|
*/
|
||||||
export const tourGpxApi = {
|
export const tourGpxApi = {
|
||||||
/** What the file holds, read by the import's own parser; nothing is stored. */
|
/** What the file holds, read by the import's own parser; nothing is stored. */
|
||||||
preview: (tripId: number | string, file: File): Promise<TourGpxPreviewResponse> =>
|
preview: (tripId: number | string, file: File): Promise<TourGpxPreviewResponse> =>
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import type { TourDetailResponse, TourPackingLinkRequest, TourPackingLinkResponse } from '@trek/shared';
|
||||||
|
import apiClient from './client';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where a tour's packing link lives; a write queued offline replays to the
|
||||||
|
* same path, `{id}` standing for a tour that has not synced yet.
|
||||||
|
*/
|
||||||
|
export function tourPackingLinkPath(tripId: number | string, placeId: number | string): string {
|
||||||
|
return `/trips/${tripId}/tours/${placeId}/packing-link`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** P2D-XD-01: the packing list, or the category of it, a tour points at. */
|
||||||
|
export const tourPackingLinkApi = {
|
||||||
|
read: (tripId: number | string, placeId: number, signal?: AbortSignal): Promise<TourPackingLinkResponse> =>
|
||||||
|
apiClient.get(tourPackingLinkPath(tripId, placeId), { signal }).then((r) => r.data),
|
||||||
|
link: (tripId: number | string, placeId: number, body: TourPackingLinkRequest): Promise<TourDetailResponse> =>
|
||||||
|
apiClient.put(tourPackingLinkPath(tripId, placeId), body).then((r) => r.data),
|
||||||
|
unlink: (tripId: number | string, placeId: number): Promise<TourDetailResponse> =>
|
||||||
|
apiClient.delete(tourPackingLinkPath(tripId, placeId)).then((r) => r.data),
|
||||||
|
};
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import type { TourDetailResponse, TourSkiClassificationRequest } from '@trek/shared';
|
||||||
|
import apiClient from './client';
|
||||||
|
|
||||||
|
/** SKI-02: a ski track classified again, its discipline and cross-country technique. */
|
||||||
|
export const tourSkiApi = {
|
||||||
|
classify: (
|
||||||
|
tripId: number | string,
|
||||||
|
placeId: number | string,
|
||||||
|
body: TourSkiClassificationRequest
|
||||||
|
): Promise<TourDetailResponse> => apiClient.put(`/trips/${tripId}/tours/${placeId}/ski`, body).then((r) => r.data),
|
||||||
|
};
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import type { TourVisitListResponse, TourVisitUpdateRequest } from '@trek/shared';
|
||||||
|
import apiClient from './client';
|
||||||
|
|
||||||
|
/** Where one station of a walk is marked for one day; a write queued offline replays to the same path. */
|
||||||
|
export function tourVisitPath(tripId: number | string, assignmentId: number, stationKey: string): string {
|
||||||
|
return `/trips/${tripId}/tour-visits/${assignmentId}/${encodeURIComponent(stationKey)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** CW-03: the stations of a trip's city walks visited or skipped on their days. */
|
||||||
|
export const tourVisitsApi = {
|
||||||
|
list: (tripId: number | string): Promise<TourVisitListResponse> =>
|
||||||
|
apiClient.get(`/trips/${tripId}/tour-visits`).then((r) => r.data),
|
||||||
|
update: (
|
||||||
|
tripId: number | string,
|
||||||
|
assignmentId: number,
|
||||||
|
stationKey: string,
|
||||||
|
body: TourVisitUpdateRequest
|
||||||
|
): Promise<TourVisitListResponse> =>
|
||||||
|
apiClient.put(tourVisitPath(tripId, assignmentId, stationKey), body).then((r) => r.data),
|
||||||
|
};
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import type { WalkImportPreviewRequest, WalkImportPreviewResponse } from '@trek/shared';
|
||||||
|
import apiClient from './client';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CW-07: a Google Maps walking route read into its stops. The server may
|
||||||
|
* follow a short link a few hops within its own deadline, so the call waits
|
||||||
|
* a little longer than that before it gives up.
|
||||||
|
*/
|
||||||
|
const WALK_IMPORT_TIMEOUT_MS = 20_000;
|
||||||
|
|
||||||
|
export const tourWalkImportApi = {
|
||||||
|
preview: (
|
||||||
|
tripId: number | string,
|
||||||
|
body: WalkImportPreviewRequest,
|
||||||
|
signal?: AbortSignal
|
||||||
|
): Promise<WalkImportPreviewResponse> =>
|
||||||
|
apiClient
|
||||||
|
.post(`/trips/${tripId}/tours/import/google-maps/preview`, body, { signal, timeout: WALK_IMPORT_TIMEOUT_MS })
|
||||||
|
.then((r) => r.data),
|
||||||
|
};
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import type {
|
import type {
|
||||||
AdminFeatureToggleResponse,
|
AdminFeatureToggleResponse,
|
||||||
TourSourceCheckResponse,
|
TourSourceCheckResponse,
|
||||||
|
TourSourceHintResponse,
|
||||||
WandererConnection,
|
WandererConnection,
|
||||||
WandererImportPreview,
|
WandererImportPreview,
|
||||||
WandererImportRequest,
|
WandererImportRequest,
|
||||||
@@ -11,6 +12,7 @@ import type {
|
|||||||
WandererSettingsRequest,
|
WandererSettingsRequest,
|
||||||
WandererTestRequest,
|
WandererTestRequest,
|
||||||
WandererTestResponse,
|
WandererTestResponse,
|
||||||
|
WandererWatch,
|
||||||
} from '@trek/shared';
|
} from '@trek/shared';
|
||||||
import apiClient from './client';
|
import apiClient from './client';
|
||||||
|
|
||||||
@@ -31,6 +33,10 @@ export const wandererApi = {
|
|||||||
disconnect: (): Promise<{ success: true }> => apiClient.delete('/integrations/wanderer/settings').then((r) => r.data),
|
disconnect: (): Promise<{ success: true }> => apiClient.delete('/integrations/wanderer/settings').then((r) => r.data),
|
||||||
test: (data: WandererTestRequest): Promise<WandererTestResponse> =>
|
test: (data: WandererTestRequest): Promise<WandererTestResponse> =>
|
||||||
apiClient.post('/integrations/wanderer/test', data, upstream).then((r) => r.data),
|
apiClient.post('/integrations/wanderer/test', data, upstream).then((r) => r.data),
|
||||||
|
/** WAN-02: the optional background watch of the connection, with the open hints. */
|
||||||
|
getWatch: (): Promise<WandererWatch> => apiClient.get('/integrations/wanderer/watch').then((r) => r.data),
|
||||||
|
setWatch: (enabled: boolean): Promise<WandererWatch> =>
|
||||||
|
apiClient.put('/integrations/wanderer/watch', { enabled }).then((r) => r.data),
|
||||||
|
|
||||||
search: (tripId: number, body: WandererSearchRequest, signal?: AbortSignal): Promise<WandererSearchResponse> =>
|
search: (tripId: number, body: WandererSearchRequest, signal?: AbortSignal): Promise<WandererSearchResponse> =>
|
||||||
apiClient.post(`/trips/${tripId}/tours/wanderer/search`, body, { ...upstream, signal }).then((r) => r.data),
|
apiClient.post(`/trips/${tripId}/tours/wanderer/search`, body, { ...upstream, signal }).then((r) => r.data),
|
||||||
@@ -43,6 +49,9 @@ export const wandererApi = {
|
|||||||
/** MF-03: whether the trail a snapshot came from changed since; the server reads, it writes nothing. */
|
/** MF-03: whether the trail a snapshot came from changed since; the server reads, it writes nothing. */
|
||||||
checkSource: (tripId: number, placeId: number): Promise<TourSourceCheckResponse> =>
|
checkSource: (tripId: number, placeId: number): Promise<TourSourceCheckResponse> =>
|
||||||
apiClient.post(`/trips/${tripId}/tours/wanderer/sources/${placeId}/check`, {}, upstream).then((r) => r.data),
|
apiClient.post(`/trips/${tripId}/tours/wanderer/sources/${placeId}/check`, {}, upstream).then((r) => r.data),
|
||||||
|
/** WAN-02: the caller's own background hint on a snapshot; the server only reads its own rows. */
|
||||||
|
sourceHint: (tripId: number, placeId: number, signal?: AbortSignal): Promise<TourSourceHintResponse> =>
|
||||||
|
apiClient.get(`/trips/${tripId}/tours/wanderer/sources/${placeId}/hint`, { signal }).then((r) => r.data),
|
||||||
};
|
};
|
||||||
|
|
||||||
/** The admin's switch for wanderer under the Tours addon. */
|
/** The admin's switch for wanderer under the Tours addon. */
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ export const HANDLED_OUTSIDE_TRIP_STORE = [
|
|||||||
// Tours facet invalidation — hooks/useTripWebSocket forwards tours:changed to
|
// Tours facet invalidation — hooks/useTripWebSocket forwards tours:changed to
|
||||||
// useTourPlaceIds so the active trip refreshes its Tours/Places read model.
|
// useTourPlaceIds so the active trip refreshes its Tours/Places read model.
|
||||||
'tours:changed',
|
'tours:changed',
|
||||||
|
// CW-03: store/tourVisitStore (watchTourVisits) keeps the visits store current.
|
||||||
|
'tours:visits',
|
||||||
// Collab — Collab/MCollab components + useTripWebSocket's collabFileSync
|
// Collab — Collab/MCollab components + useTripWebSocket's collabFileSync
|
||||||
'collab:note:created',
|
'collab:note:created',
|
||||||
'collab:note:updated',
|
'collab:note:updated',
|
||||||
|
|||||||
@@ -78,7 +78,11 @@ beforeEach(() => {
|
|||||||
vi.spyOn(useAddonStore.getState(), 'loadAddons').mockResolvedValue(undefined);
|
vi.spyOn(useAddonStore.getState(), 'loadAddons').mockResolvedValue(undefined);
|
||||||
server.use(
|
server.use(
|
||||||
http.get('/api/admin/addons', () => HttpResponse.json({ addons: [] })),
|
http.get('/api/admin/addons', () => HttpResponse.json({ addons: [] })),
|
||||||
http.get('/api/admin/tours-wanderer', () => HttpResponse.json({ enabled: false }))
|
http.get('/api/admin/tours-wanderer', () => HttpResponse.json({ enabled: false })),
|
||||||
|
// The Tours switches load beside the list; unanswered, each would toast the same error as a failed list.
|
||||||
|
http.get('/api/admin/tours-hiking-map', () => HttpResponse.json({ enabled: false })),
|
||||||
|
http.get('/api/admin/tours-cycle-map', () => HttpResponse.json({ enabled: false })),
|
||||||
|
http.get('/api/admin/tours-ski-routing', () => HttpResponse.json({ enabled: false }))
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { act, renderHook, waitFor } from '@testing-library/react';
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
import { adminApi } from '../../../api/client';
|
import { adminApi } from '../../../api/client';
|
||||||
import { cycleMapAdminApi, hikingMapAdminApi } from '../../../api/tourBaseMaps';
|
import { cycleMapAdminApi, hikingMapAdminApi, skiRoutingAdminApi } from '../../../api/tourBaseMaps';
|
||||||
import { wandererAdminApi } from '../../../api/wanderer';
|
import { wandererAdminApi } from '../../../api/wanderer';
|
||||||
import { useAddonStore } from '../../../store/addonStore';
|
import { useAddonStore } from '../../../store/addonStore';
|
||||||
import type { Addon } from './addonModel';
|
import type { Addon } from './addonModel';
|
||||||
@@ -40,6 +40,7 @@ beforeEach(() => {
|
|||||||
vi.spyOn(wandererAdminApi, 'get').mockResolvedValue({ enabled: false });
|
vi.spyOn(wandererAdminApi, 'get').mockResolvedValue({ enabled: false });
|
||||||
vi.spyOn(hikingMapAdminApi, 'get').mockResolvedValue({ enabled: true });
|
vi.spyOn(hikingMapAdminApi, 'get').mockResolvedValue({ enabled: true });
|
||||||
vi.spyOn(cycleMapAdminApi, 'get').mockResolvedValue({ enabled: true });
|
vi.spyOn(cycleMapAdminApi, 'get').mockResolvedValue({ enabled: true });
|
||||||
|
vi.spyOn(skiRoutingAdminApi, 'get').mockResolvedValue({ enabled: true });
|
||||||
});
|
});
|
||||||
afterEach(() => vi.restoreAllMocks());
|
afterEach(() => vi.restoreAllMocks());
|
||||||
|
|
||||||
@@ -52,7 +53,7 @@ async function loaded() {
|
|||||||
const enabledOf = (addons: Addon[], id: string) => addons.find((a) => a.id === id)?.enabled;
|
const enabledOf = (addons: Addon[], id: string) => addons.find((a) => a.id === id)?.enabled;
|
||||||
|
|
||||||
/** One of the map switches under Tours, by its key. */
|
/** One of the map switches under Tours, by its key. */
|
||||||
function mapSwitch(manager: ReturnType<typeof useAddonManager>, key: 'hiking' | 'cycle') {
|
function mapSwitch(manager: ReturnType<typeof useAddonManager>, key: 'hiking' | 'cycle' | 'ski') {
|
||||||
const found = manager.mapSwitches.find((entry) => entry.key === key);
|
const found = manager.mapSwitches.find((entry) => entry.key === key);
|
||||||
if (!found) throw new Error(`no ${key} map switch`);
|
if (!found) throw new Error(`no ${key} map switch`);
|
||||||
return found;
|
return found;
|
||||||
@@ -149,6 +150,16 @@ describe('useAddonManager', () => {
|
|||||||
expect(mapSwitch(result.current, 'hiking').enabled).toBe(true);
|
expect(mapSwitch(result.current, 'hiking').enabled).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('FE-HOOK-ADDONMGR-010: the piste router switch under Tours loads on, flips and saves on its own (SKI-02)', async () => {
|
||||||
|
const update = vi.spyOn(skiRoutingAdminApi, 'update').mockResolvedValue({ enabled: false });
|
||||||
|
const { result } = await loaded();
|
||||||
|
await waitFor(() => expect(mapSwitch(result.current, 'ski').enabled).toBe(true));
|
||||||
|
await act(() => mapSwitch(result.current, 'ski').toggle());
|
||||||
|
expect(update).toHaveBeenCalledWith(false);
|
||||||
|
expect(mapSwitch(result.current, 'ski').enabled).toBe(false);
|
||||||
|
expect(mapSwitch(result.current, 'cycle').enabled).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
it('FE-HOOK-ADDONMGR-008: a failed save puts the switch under Tours back and says so', async () => {
|
it('FE-HOOK-ADDONMGR-008: a failed save puts the switch under Tours back and says so', async () => {
|
||||||
vi.spyOn(wandererAdminApi, 'update').mockRejectedValue(new Error('500'));
|
vi.spyOn(wandererAdminApi, 'update').mockRejectedValue(new Error('500'));
|
||||||
const { result } = await loaded();
|
const { result } = await loaded();
|
||||||
|
|||||||
@@ -1,14 +1,27 @@
|
|||||||
import { Bike, Footprints } from 'lucide-react';
|
import type { AdminFeatureToggleResponse } from '@trek/shared';
|
||||||
|
import { Bike, Footprints, MountainSnow } from 'lucide-react';
|
||||||
import { useEffect, useEffectEvent, useState } from 'react';
|
import { useEffect, useEffectEvent, useState } from 'react';
|
||||||
|
|
||||||
import { adminApi } from '../../../api/client';
|
import { adminApi } from '../../../api/client';
|
||||||
import { cycleMapAdminApi, hikingMapAdminApi } from '../../../api/tourBaseMaps';
|
import { cycleMapAdminApi, hikingMapAdminApi, skiRoutingAdminApi } from '../../../api/tourBaseMaps';
|
||||||
import { wandererAdminApi } from '../../../api/wanderer';
|
import { wandererAdminApi } from '../../../api/wanderer';
|
||||||
import { useTranslation } from '../../../i18n';
|
import { useTranslation } from '../../../i18n';
|
||||||
import { useAddonStore } from '../../../store/addonStore';
|
import { useAddonStore } from '../../../store/addonStore';
|
||||||
import { useToast } from '../../shared/Toast';
|
import { useToast } from '../../shared/Toast';
|
||||||
import { type Addon, type ProviderOption, isPhotosAddon } from './addonModel';
|
import { type Addon, type ProviderOption, isPhotosAddon } from './addonModel';
|
||||||
|
|
||||||
|
/** A switch under Tours as the server keeps it, read into `set`; `onError` tells the admin it could not be read. */
|
||||||
|
function loadToursFlag(
|
||||||
|
api: { get: () => Promise<AdminFeatureToggleResponse> },
|
||||||
|
set: (enabled: boolean) => void,
|
||||||
|
onError: () => void
|
||||||
|
) {
|
||||||
|
api
|
||||||
|
.get()
|
||||||
|
.then((flag) => set(flag.enabled))
|
||||||
|
.catch(onError);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The addon switches behind both admin shells: the addon list loaded on mount, an
|
* The addon switches behind both admin shells: the addon list loaded on mount, an
|
||||||
* optimistic toggle with a per row rollback, and the lists each shell groups its tiles
|
* optimistic toggle with a per row rollback, and the lists each shell groups its tiles
|
||||||
@@ -24,6 +37,7 @@ export function useAddonManager() {
|
|||||||
const [toursWanderer, setToursWanderer] = useState(false);
|
const [toursWanderer, setToursWanderer] = useState(false);
|
||||||
const [toursHikingMap, setToursHikingMap] = useState(false);
|
const [toursHikingMap, setToursHikingMap] = useState(false);
|
||||||
const [toursCycleMap, setToursCycleMap] = useState(false);
|
const [toursCycleMap, setToursCycleMap] = useState(false);
|
||||||
|
const [toursSkiRouting, setToursSkiRouting] = useState(false);
|
||||||
|
|
||||||
const loadAddons = async () => {
|
const loadAddons = async () => {
|
||||||
try {
|
try {
|
||||||
@@ -36,18 +50,11 @@ export function useAddonManager() {
|
|||||||
|
|
||||||
const loadOnMount = useEffectEvent(() => {
|
const loadOnMount = useEffectEvent(() => {
|
||||||
void loadAddons().finally(() => setLoading(false));
|
void loadAddons().finally(() => setLoading(false));
|
||||||
wandererAdminApi
|
const unreadable = () => toast.error(t('admin.addons.toast.error'));
|
||||||
.get()
|
loadToursFlag(wandererAdminApi, setToursWanderer, unreadable);
|
||||||
.then((flag) => setToursWanderer(flag.enabled))
|
loadToursFlag(hikingMapAdminApi, setToursHikingMap, unreadable);
|
||||||
.catch(() => toast.error(t('admin.addons.toast.error')));
|
loadToursFlag(cycleMapAdminApi, setToursCycleMap, unreadable);
|
||||||
hikingMapAdminApi
|
loadToursFlag(skiRoutingAdminApi, setToursSkiRouting, unreadable);
|
||||||
.get()
|
|
||||||
.then((flag) => setToursHikingMap(flag.enabled))
|
|
||||||
.catch(() => toast.error(t('admin.addons.toast.error')));
|
|
||||||
cycleMapAdminApi
|
|
||||||
.get()
|
|
||||||
.then((flag) => setToursCycleMap(flag.enabled))
|
|
||||||
.catch(() => toast.error(t('admin.addons.toast.error')));
|
|
||||||
});
|
});
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
loadOnMount();
|
loadOnMount();
|
||||||
@@ -94,7 +101,7 @@ export function useAddonManager() {
|
|||||||
toast.success(t('admin.addons.toast.updated'));
|
toast.success(t('admin.addons.toast.updated'));
|
||||||
};
|
};
|
||||||
const toggleToursWanderer = () => flipToursSwitch(toursWanderer, setToursWanderer, wandererAdminApi.update);
|
const toggleToursWanderer = () => flipToursSwitch(toursWanderer, setToursWanderer, wandererAdminApi.update);
|
||||||
/** The maps the Tours planner offers on their operators' terms, one switch each (MAP-01, BIK-06). */
|
/** The maps and the piste router Tours offers on their operators' terms, one switch each (MAP-01, BIK-06, SKI-02). */
|
||||||
const mapSwitches = [
|
const mapSwitches = [
|
||||||
{
|
{
|
||||||
key: 'hiking',
|
key: 'hiking',
|
||||||
@@ -112,6 +119,14 @@ export function useAddonManager() {
|
|||||||
enabled: toursCycleMap,
|
enabled: toursCycleMap,
|
||||||
toggle: () => flipToursSwitch(toursCycleMap, setToursCycleMap, cycleMapAdminApi.update),
|
toggle: () => flipToursSwitch(toursCycleMap, setToursCycleMap, cycleMapAdminApi.update),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
key: 'ski',
|
||||||
|
Icon: MountainSnow,
|
||||||
|
titleKey: 'admin.toursSkiRouting.title',
|
||||||
|
subtitleKey: 'admin.toursSkiRouting.subtitle',
|
||||||
|
enabled: toursSkiRouting,
|
||||||
|
toggle: () => flipToursSwitch(toursSkiRouting, setToursSkiRouting, skiRoutingAdminApi.update),
|
||||||
|
},
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
const asOption = (provider: Addon): ProviderOption => ({
|
const asOption = (provider: Addon): ProviderOption => ({
|
||||||
|
|||||||
@@ -0,0 +1,150 @@
|
|||||||
|
// FE-STA2-PANE-001 to FE-STA2-PANE-006
|
||||||
|
// STA-02: the Atlas tab of the user's own tour activities: the distance large
|
||||||
|
// with how many tours at its corner, the climb, the types, what the numbers
|
||||||
|
// rest on, and the full list in a dialog.
|
||||||
|
import userEvent from '@testing-library/user-event';
|
||||||
|
import { summarizeTourActivities, type TourActivityStatsEntry, type TourActivityStatsResponse } from '@trek/shared';
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { buildSettings } from '../../../../tests/helpers/factories';
|
||||||
|
import { render, screen } from '../../../../tests/helpers/render';
|
||||||
|
import { resetAllStores, seedStore } from '../../../../tests/helpers/store';
|
||||||
|
import { useSettingsStore } from '../../../store/settingsStore';
|
||||||
|
import { AtlasTourActivityPane } from './AtlasTourActivityPane';
|
||||||
|
import type { TourActivityStats } from './useTourActivityStats';
|
||||||
|
|
||||||
|
const hook = vi.hoisted(() => ({ current: null as unknown, active: [] as boolean[] }));
|
||||||
|
vi.mock('./useTourActivityStats', () => ({
|
||||||
|
useTourActivityStats: (active: boolean) => {
|
||||||
|
hook.active.push(active);
|
||||||
|
return hook.current;
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
const TODAY = '2026-10-20';
|
||||||
|
|
||||||
|
function entry(overrides: Partial<TourActivityStatsEntry> = {}): TourActivityStatsEntry {
|
||||||
|
return {
|
||||||
|
place_id: 1,
|
||||||
|
name: 'Ridge',
|
||||||
|
tour_type: 'hike',
|
||||||
|
trip: { id: 5, title: 'Alps' },
|
||||||
|
derived_from_place_id: null,
|
||||||
|
date: '2026-07-02',
|
||||||
|
basis: 'plan',
|
||||||
|
track: null,
|
||||||
|
day_count: 1,
|
||||||
|
distance_km: 12,
|
||||||
|
ascent_m: 800,
|
||||||
|
descent_m: 790,
|
||||||
|
excluded: false,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function statsOf(data: TourActivityStatsResponse | null, overrides: Partial<TourActivityStats> = {}) {
|
||||||
|
const stats: TourActivityStats = {
|
||||||
|
status: data ? 'ready' : 'loading',
|
||||||
|
data,
|
||||||
|
summary: data ? summarizeTourActivities(data.entries, { today: TODAY }) : null,
|
||||||
|
period: 'all',
|
||||||
|
setPeriod: vi.fn(),
|
||||||
|
periods: ['all', 'thisYear', 'last12'],
|
||||||
|
type: 'all',
|
||||||
|
setType: vi.fn(),
|
||||||
|
types: ['all', 'hike', 'kayak'],
|
||||||
|
pending: new Set(),
|
||||||
|
setExcluded: vi.fn().mockResolvedValue(undefined),
|
||||||
|
retry: vi.fn(),
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
hook.current = stats;
|
||||||
|
return stats;
|
||||||
|
}
|
||||||
|
|
||||||
|
const data: TourActivityStatsResponse = {
|
||||||
|
entries: [
|
||||||
|
entry(),
|
||||||
|
entry({ place_id: 2, name: 'Summit', date: '2026-08-01', distance_km: 20.5, ascent_m: 1200, descent_m: 1200 }),
|
||||||
|
entry({
|
||||||
|
place_id: 3,
|
||||||
|
name: 'Lake',
|
||||||
|
tour_type: 'kayak',
|
||||||
|
basis: 'track',
|
||||||
|
track: { place_id: 9, name: 'Watch' },
|
||||||
|
distance_km: 8,
|
||||||
|
ascent_m: null,
|
||||||
|
descent_m: null,
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
uncounted: { unassigned: 0, undated: 1 },
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
resetAllStores();
|
||||||
|
vi.clearAllMocks();
|
||||||
|
hook.active = [];
|
||||||
|
seedStore(useSettingsStore, { settings: buildSettings({ distance_unit: 'metric' }) });
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('AtlasTourActivityPane', () => {
|
||||||
|
it('FE-STA2-PANE-001: follows whether the tab is shown, silent before, loading until the read is there', () => {
|
||||||
|
statsOf(null, { status: 'idle' });
|
||||||
|
const { rerender } = render(<AtlasTourActivityPane active={false} />);
|
||||||
|
expect(hook.active).toEqual([false]);
|
||||||
|
expect(screen.queryByRole('status')).not.toBeInTheDocument();
|
||||||
|
statsOf(null);
|
||||||
|
rerender(<AtlasTourActivityPane active />);
|
||||||
|
expect(hook.active).toEqual([false, true]);
|
||||||
|
expect(screen.getByRole('status')).toHaveTextContent('Loading');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-PANE-002: shows the distance large with the tour count at its corner, and the climb', () => {
|
||||||
|
statsOf(data);
|
||||||
|
render(<AtlasTourActivityPane active />);
|
||||||
|
expect(screen.getByTestId('atlas-tour-activity-distance')).toHaveTextContent('40.5km');
|
||||||
|
expect(screen.getByTestId('atlas-tour-activity-count')).toHaveTextContent('3');
|
||||||
|
expect(screen.getByTestId('atlas-tour-activity-ascent')).toHaveTextContent('2000m');
|
||||||
|
expect(screen.getByTestId('atlas-tour-activity-type-hike')).toHaveTextContent('2');
|
||||||
|
expect(screen.getByTestId('atlas-tour-activity-type-kayak')).toHaveTextContent('8 km');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-PANE-003: says what the numbers rest on and what does not count', () => {
|
||||||
|
statsOf(data);
|
||||||
|
render(<AtlasTourActivityPane active />);
|
||||||
|
expect(screen.getByTestId('tour-activity-basis-plan')).toHaveTextContent('Planned2');
|
||||||
|
expect(screen.getByTestId('tour-activity-basis-track')).toHaveTextContent('Recorded1');
|
||||||
|
expect(screen.getByTestId('tour-activity-undated')).toHaveTextContent('1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-PANE-004: one type chosen leaves the type columns out; nothing done says so', () => {
|
||||||
|
statsOf(data, { type: 'hike', summary: summarizeTourActivities(data.entries, { today: TODAY, type: 'hike' }) });
|
||||||
|
const { rerender } = render(<AtlasTourActivityPane active />);
|
||||||
|
expect(screen.queryByTestId('atlas-tour-activity-type-hike')).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
statsOf(data, { summary: summarizeTourActivities(data.entries, { today: TODAY, from: '2027-01-01' }) });
|
||||||
|
rerender(<AtlasTourActivityPane active />);
|
||||||
|
expect(screen.getByText('No completed tours in this period')).toBeInTheDocument();
|
||||||
|
expect(screen.queryByRole('button', { name: 'Show tours' })).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-PANE-005: the full list opens in the dialog', async () => {
|
||||||
|
statsOf(data);
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<AtlasTourActivityPane active />);
|
||||||
|
await user.click(screen.getByRole('button', { name: 'Show tours' }));
|
||||||
|
expect(screen.getByRole('heading', { name: 'My tour activities' })).toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId('tour-activity-list')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-PANE-006: offline and failed reads say so, a failed one with a retry', async () => {
|
||||||
|
statsOf(null, { status: 'offline' });
|
||||||
|
const { rerender } = render(<AtlasTourActivityPane active />);
|
||||||
|
expect(screen.getByText(/needs a connection/i)).toBeInTheDocument();
|
||||||
|
|
||||||
|
const failed = statsOf(null, { status: 'error' });
|
||||||
|
rerender(<AtlasTourActivityPane active />);
|
||||||
|
expect(screen.getByRole('alert')).toHaveTextContent('Tour activities could not be loaded');
|
||||||
|
await userEvent.setup().click(screen.getByRole('button', { name: 'Try again' }));
|
||||||
|
expect(failed.retry).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
import type { TourActivitySummary } from '@trek/shared';
|
||||||
|
import { Footprints, ListOrdered } from 'lucide-react';
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { useTranslation } from '../../../i18n';
|
||||||
|
import type { DistanceUnit } from '../../../types';
|
||||||
|
import { fs } from '../../shared/DialogShell';
|
||||||
|
import { Tooltip } from '../../shared/Tooltip';
|
||||||
|
import { CardAction, InfoDot } from '../../Tours/tourParts';
|
||||||
|
import { ActivityFilters, ActivityStatusLine, BasisBadges, UncountedBadges } from './tourActivityParts';
|
||||||
|
import { distanceReading, heightReading, typeIcon, typeLabel, useDistanceUnit } from './tourActivityReading';
|
||||||
|
import { TourActivityStatsDialog } from './TourActivityStatsDialog';
|
||||||
|
import { splitMeasure } from './tourActivityStatsModel';
|
||||||
|
import { useTourActivityStats, type TourActivityStats } from './useTourActivityStats';
|
||||||
|
|
||||||
|
/** The wash the hero tile sits on, as the Atlas numbers do: the text colour, faintly, over the glass. */
|
||||||
|
const HERO_TINT = 'color-mix(in srgb, var(--text-primary) 7%, transparent)';
|
||||||
|
/** How many types the strip names before the dialog takes over. */
|
||||||
|
const STRIP_TYPES = 3;
|
||||||
|
const EYEBROW = 'mt-1.5 whitespace-nowrap font-semibold uppercase tracking-wide text-content-faint';
|
||||||
|
|
||||||
|
function Divider() {
|
||||||
|
return <span aria-hidden="true" className="mx-3 my-3 w-0.5 flex-none rounded-full bg-edge-faint" />;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The distance of the period, large, with how many tours at its corner; the
|
||||||
|
* tour count stands in when no tour knows its distance.
|
||||||
|
*/
|
||||||
|
function Hero({ summary, unit }: { summary: TourActivitySummary; unit: DistanceUnit }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const reading = distanceReading(summary.totals, unit);
|
||||||
|
const shown = reading ? splitMeasure(reading.text) : { value: String(summary.totals.count), unit: '' };
|
||||||
|
const countLabel = `${t('tours.mode.tours')}: ${summary.totals.count}`;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="relative mx-2 my-2 flex flex-col justify-center rounded-xl px-5 py-4"
|
||||||
|
style={{ background: HERO_TINT }}
|
||||||
|
>
|
||||||
|
<div className="flex items-baseline gap-1.5" data-testid="atlas-tour-activity-distance">
|
||||||
|
<span className="font-black tabular-nums leading-none text-content" style={fs(40, 'title')}>
|
||||||
|
{shown.value}
|
||||||
|
</span>
|
||||||
|
{shown.unit && (
|
||||||
|
<span className="font-medium text-content-muted" style={fs(14, 'body')}>
|
||||||
|
{shown.unit}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<span className={EYEBROW} style={fs(9)}>
|
||||||
|
{reading ? t('tours.detail.distance') : t('tours.mode.tours')}
|
||||||
|
</span>
|
||||||
|
{reading && (
|
||||||
|
<Tooltip label={countLabel}>
|
||||||
|
<span
|
||||||
|
aria-label={countLabel}
|
||||||
|
data-testid="atlas-tour-activity-count"
|
||||||
|
className="absolute -end-2 -top-2 inline-flex h-[22px] items-center gap-1 rounded-full bg-surface-card px-2 font-geist font-semibold tabular-nums text-content shadow-sm ring-1 ring-inset ring-edge-faint"
|
||||||
|
style={fs(11)}
|
||||||
|
>
|
||||||
|
<Footprints size={11} strokeWidth={2.2} className="flex-none text-content-muted" />
|
||||||
|
{summary.totals.count}
|
||||||
|
</span>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A height sum as the Atlas numbers stand: the value, its unit, and what it is below. */
|
||||||
|
function Figure({ label, text, testId }: { label: string; text: string; testId: string }) {
|
||||||
|
const { value, unit } = splitMeasure(text);
|
||||||
|
return (
|
||||||
|
<div className="flex flex-none flex-col items-center justify-center px-3 py-4" data-testid={testId}>
|
||||||
|
<span className="flex items-baseline gap-1">
|
||||||
|
<span className="font-black tabular-nums leading-none text-content" style={fs(24, 'subtitle')}>
|
||||||
|
{value}
|
||||||
|
</span>
|
||||||
|
<span className="font-medium text-content-muted" style={fs(11, 'body')}>
|
||||||
|
{unit}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
<span className={EYEBROW} style={fs(9)}>
|
||||||
|
{label}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The types of the period, the most tours first: each an icon with its count at the corner, its distance below. */
|
||||||
|
function TypeColumns({ summary, unit }: { summary: TourActivitySummary; unit: DistanceUnit }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<div className="flex flex-none items-center gap-4 px-2 py-3">
|
||||||
|
{summary.types.slice(0, STRIP_TYPES).map((scope) => {
|
||||||
|
const Icon = typeIcon(scope.type);
|
||||||
|
const distance = distanceReading(scope, unit);
|
||||||
|
const label = `${typeLabel(scope.type, t)}: ${scope.count}${distance ? `, ${distance.text}` : ''}`;
|
||||||
|
return (
|
||||||
|
<Tooltip key={scope.type} label={label}>
|
||||||
|
<span
|
||||||
|
aria-label={label}
|
||||||
|
className="flex flex-col items-center gap-1.5"
|
||||||
|
data-testid={`atlas-tour-activity-type-${scope.type}`}
|
||||||
|
>
|
||||||
|
<span className="relative">
|
||||||
|
<span className="grid h-8 w-8 place-items-center rounded-full bg-surface-card text-content-secondary shadow-sm ring-1 ring-inset ring-edge-faint">
|
||||||
|
<Icon size={15} strokeWidth={1.9} />
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className="absolute -end-1.5 -top-1.5 grid h-4 min-w-4 place-items-center rounded-full bg-accent px-1 font-geist font-semibold tabular-nums text-accent-text ring-2 ring-surface-card"
|
||||||
|
style={fs(9)}
|
||||||
|
>
|
||||||
|
{scope.count}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
{distance && (
|
||||||
|
<span
|
||||||
|
className="whitespace-nowrap font-semibold tabular-nums text-content-secondary"
|
||||||
|
style={fs(11, 'body')}
|
||||||
|
>
|
||||||
|
{distance.text}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
</Tooltip>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the sums rest on, what does not count, and the way into the full list. */
|
||||||
|
interface StripProps {
|
||||||
|
stats: TourActivityStats;
|
||||||
|
summary: TourActivitySummary;
|
||||||
|
onOpen: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function SideColumn({ stats, summary, onOpen }: StripProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const uncounted = stats.data?.uncounted ?? { unassigned: 0, undated: 0 };
|
||||||
|
return (
|
||||||
|
<div className="flex flex-none flex-col items-start justify-center gap-1.5 px-3 py-3">
|
||||||
|
<div className="flex flex-wrap items-center gap-1.5">
|
||||||
|
<BasisBadges byBasis={summary.totals.byBasis} />
|
||||||
|
<InfoDot label={t('tours.stats.title')} description={t('tours.stats.basisInfo')} />
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap items-center gap-1.5">
|
||||||
|
<UncountedBadges upcoming={summary.upcoming} {...uncounted} />
|
||||||
|
</div>
|
||||||
|
{summary.done.length > 0 && (
|
||||||
|
<CardAction icon={<ListOrdered size={13} strokeWidth={2.2} />} onClick={onOpen}>
|
||||||
|
{t('tours.stats.showTours')}
|
||||||
|
</CardAction>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The numbers of the period, or why there are none, with the filters before them. */
|
||||||
|
function Strip({ stats, summary, onOpen }: StripProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const unit = useDistanceUnit();
|
||||||
|
const ascent = heightReading(summary.totals.ascentM, unit);
|
||||||
|
const descent = heightReading(summary.totals.descentM, unit);
|
||||||
|
const counted = summary.totals.count > 0;
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="flex flex-none flex-col items-start justify-center gap-1.5 px-3 py-3">
|
||||||
|
<ActivityFilters stats={stats} quiet />
|
||||||
|
</div>
|
||||||
|
{counted ? (
|
||||||
|
<>
|
||||||
|
<Hero summary={summary} unit={unit} />
|
||||||
|
{ascent && <Figure label={t('tours.detail.ascent')} text={ascent.text} testId="atlas-tour-activity-ascent" />}
|
||||||
|
{descent && (
|
||||||
|
<Figure label={t('tours.detail.descent')} text={descent.text} testId="atlas-tour-activity-descent" />
|
||||||
|
)}
|
||||||
|
{stats.type === 'all' && summary.types.length > 1 && (
|
||||||
|
<>
|
||||||
|
<Divider />
|
||||||
|
<TypeColumns summary={summary} unit={unit} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<p className="m-0 flex max-w-[260px] items-center px-4 py-5 text-content-muted" style={fs(12, 'body')}>
|
||||||
|
{t(stats.data?.entries.length ? 'tours.stats.none' : 'tours.stats.empty')}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<Divider />
|
||||||
|
<SideColumn stats={stats} summary={summary} onOpen={onOpen} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* STA-02: the Atlas tab of the user's own tour activities: the period and type,
|
||||||
|
* the distance done with how many tours at its corner, the climb, the types,
|
||||||
|
* and what the numbers rest on (the trip planning, or recorded tracks where
|
||||||
|
* linked). The full list, where a tour can be left out, opens in a dialog. The
|
||||||
|
* read waits until the tab is first shown.
|
||||||
|
*/
|
||||||
|
export function AtlasTourActivityPane({ active, maxWidth }: { active: boolean; maxWidth?: number }) {
|
||||||
|
const stats = useTourActivityStats(active);
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="flex w-full items-stretch justify-center overflow-x-auto px-2"
|
||||||
|
style={{ maxWidth }}
|
||||||
|
data-testid="atlas-tour-activity"
|
||||||
|
>
|
||||||
|
{stats.summary ? (
|
||||||
|
<Strip stats={stats} summary={stats.summary} onOpen={() => setOpen(true)} />
|
||||||
|
) : (
|
||||||
|
<div className="flex items-center px-6 py-5">
|
||||||
|
<ActivityStatusLine stats={stats} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<TourActivityStatsDialog stats={stats} open={open} onClose={() => setOpen(false)} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
import type { TourActivityStatsEntry } from '@trek/shared';
|
||||||
|
import { Ban, Briefcase, CalendarDays, Footprints, Loader2, Repeat, RotateCcw } from 'lucide-react';
|
||||||
|
import { useNavigate } from 'react-router';
|
||||||
|
import { useTranslation } from '../../../i18n';
|
||||||
|
import { formatDate } from '../../../utils/formatters';
|
||||||
|
import { formatDistance, formatElevation } from '../../../utils/units';
|
||||||
|
import { SoftPill, WhiteBadge } from '../../Planner/planParts';
|
||||||
|
import { fs } from '../../shared/DialogShell';
|
||||||
|
import { Tooltip } from '../../shared/Tooltip';
|
||||||
|
import { EntryTile, MeasurePills } from './tourActivityParts';
|
||||||
|
import { useDistanceUnit } from './tourActivityReading';
|
||||||
|
|
||||||
|
const ROW_BADGE_ICON = 'flex-none text-content-faint';
|
||||||
|
|
||||||
|
/** What the entry's values rest on, as a pill: the plan, or the track that replaced it, named in the tooltip. */
|
||||||
|
function BasisPill({ entry }: { entry: TourActivityStatsEntry }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const track = entry.basis === 'track';
|
||||||
|
const hint = track
|
||||||
|
? t('tours.stats.basisTrackHint', { name: entry.track?.name ?? '' })
|
||||||
|
: t('tours.stats.basisPlanHint');
|
||||||
|
return (
|
||||||
|
<Tooltip label={hint}>
|
||||||
|
<span
|
||||||
|
className="inline-flex"
|
||||||
|
aria-label={hint}
|
||||||
|
data-testid={`tour-activity-basis-${entry.basis}-${entry.place_id}`}
|
||||||
|
>
|
||||||
|
<SoftPill
|
||||||
|
tone={track ? 'success' : 'neutral'}
|
||||||
|
icon={
|
||||||
|
track ? (
|
||||||
|
<Footprints size={10} strokeWidth={2.2} className="flex-none" />
|
||||||
|
) : (
|
||||||
|
<CalendarDays size={10} strokeWidth={2.2} className={ROW_BADGE_ICON} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{t(track ? 'tours.stats.basisTrack' : 'tours.stats.basisPlan')}
|
||||||
|
</SoftPill>
|
||||||
|
</span>
|
||||||
|
</Tooltip>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The day it counts on, the trip it is in (a way into that trip), and how many days the plan has it on. */
|
||||||
|
function EntryFacts({ entry }: { entry: TourActivityStatsEntry }) {
|
||||||
|
const { t, locale } = useTranslation();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
return (
|
||||||
|
<span className="mt-1 flex min-w-0 flex-wrap items-center gap-1">
|
||||||
|
<WhiteBadge icon={<CalendarDays size={10} strokeWidth={2.2} className={ROW_BADGE_ICON} />}>
|
||||||
|
{formatDate(entry.date, locale) ?? entry.date}
|
||||||
|
</WhiteBadge>
|
||||||
|
<Tooltip label={t('tours.stats.openTrip')}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void navigate(`/trips/${entry.trip.id}`)}
|
||||||
|
className="inline-flex min-w-0 max-w-[220px] rounded-full transition-opacity hover:opacity-75 focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent"
|
||||||
|
>
|
||||||
|
<WhiteBadge
|
||||||
|
className="min-w-0 max-w-full"
|
||||||
|
icon={<Briefcase size={10} strokeWidth={2.2} className={ROW_BADGE_ICON} />}
|
||||||
|
>
|
||||||
|
<span className="truncate">{entry.trip.title}</span>
|
||||||
|
</WhiteBadge>
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
{entry.day_count > 1 && (
|
||||||
|
<Tooltip label={t('tours.stats.multiDayHint')}>
|
||||||
|
<span className="inline-flex" aria-label={t('tours.stats.multiDayHint')}>
|
||||||
|
<WhiteBadge icon={<Repeat size={10} strokeWidth={2.2} className={ROW_BADGE_ICON} />}>
|
||||||
|
{entry.day_count}
|
||||||
|
</WhiteBadge>
|
||||||
|
</span>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
<BasisPill entry={entry} />
|
||||||
|
{entry.excluded && <SoftPill caps>{t('tours.stats.excluded')}</SoftPill>}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The round button that leaves the tour out, or counts it again; named by its tooltip. */
|
||||||
|
function ExcludeToggle({
|
||||||
|
entry,
|
||||||
|
busy,
|
||||||
|
onToggle,
|
||||||
|
}: {
|
||||||
|
entry: TourActivityStatsEntry;
|
||||||
|
busy: boolean;
|
||||||
|
onToggle: () => void;
|
||||||
|
}) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const label = entry.excluded ? t('tours.stats.include') : t('tours.stats.exclude');
|
||||||
|
const hint = entry.excluded ? label : `${label}: ${t('tours.stats.excludeHint')}`;
|
||||||
|
let icon = <Ban size={14} strokeWidth={2} />;
|
||||||
|
if (busy) icon = <Loader2 size={14} strokeWidth={2} className="animate-spin" />;
|
||||||
|
else if (entry.excluded) icon = <RotateCcw size={14} strokeWidth={2} />;
|
||||||
|
return (
|
||||||
|
<Tooltip label={hint}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onToggle}
|
||||||
|
disabled={busy}
|
||||||
|
aria-label={label}
|
||||||
|
aria-pressed={entry.excluded}
|
||||||
|
data-testid={`tour-activity-toggle-${entry.place_id}`}
|
||||||
|
className="grid h-8 w-8 flex-none place-items-center rounded-full bg-surface-card text-content-muted shadow-sm ring-1 ring-inset ring-edge-faint transition-colors hover:text-content focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent disabled:cursor-default disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{icon}
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* STA-02: one tour of the user's activities: its type, name and where it
|
||||||
|
* counts, its distance and climb, and the switch to leave it out. A tour left
|
||||||
|
* out stays in the list, dimmed, so it can be counted again in place.
|
||||||
|
*/
|
||||||
|
export function TourActivityEntryRow({
|
||||||
|
entry,
|
||||||
|
busy,
|
||||||
|
onToggleExcluded,
|
||||||
|
}: {
|
||||||
|
entry: TourActivityStatsEntry;
|
||||||
|
busy: boolean;
|
||||||
|
onToggleExcluded: (entry: TourActivityStatsEntry) => void;
|
||||||
|
}) {
|
||||||
|
const unit = useDistanceUnit();
|
||||||
|
const key = entry.track ? `${entry.place_id}-${entry.track.place_id}` : String(entry.place_id);
|
||||||
|
return (
|
||||||
|
<li
|
||||||
|
data-testid={`tour-activity-row-${key}`}
|
||||||
|
className="flex min-w-0 items-center gap-3 rounded-[12px] px-2.5 py-2 transition-colors hover:bg-surface-hover"
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className={`flex min-w-0 flex-1 items-center gap-3 transition-opacity ${entry.excluded ? 'opacity-50' : ''}`}
|
||||||
|
>
|
||||||
|
<EntryTile entry={entry} />
|
||||||
|
<span className="min-w-0 flex-1">
|
||||||
|
<span className="block truncate font-semibold text-content" style={fs(13, 'body')}>
|
||||||
|
{entry.name}
|
||||||
|
</span>
|
||||||
|
<EntryFacts entry={entry} />
|
||||||
|
</span>
|
||||||
|
<span className="flex flex-none flex-col items-end gap-1">
|
||||||
|
<MeasurePills
|
||||||
|
distance={entry.distance_km === null ? null : formatDistance(entry.distance_km, unit)}
|
||||||
|
ascent={entry.ascent_m === null ? null : formatElevation(entry.ascent_m, unit)}
|
||||||
|
testId={`tour-activity-${key}`}
|
||||||
|
/>
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
<ExcludeToggle entry={entry} busy={busy} onToggle={() => onToggleExcluded(entry)} />
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
// FE-STA2-DIALOG-001 to FE-STA2-DIALOG-008
|
||||||
|
// STA-02: the full list of the user's tour activities: the sums with what they
|
||||||
|
// rest on, the split by type, each tour with its basis and a switch to leave it
|
||||||
|
// out (dimmed, never hidden), and the way into its trip.
|
||||||
|
import userEvent from '@testing-library/user-event';
|
||||||
|
import { summarizeTourActivities, type TourActivityStatsEntry, type TourActivityStatsResponse } from '@trek/shared';
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { buildSettings } from '../../../../tests/helpers/factories';
|
||||||
|
import { render, screen, within } from '../../../../tests/helpers/render';
|
||||||
|
import { resetAllStores, seedStore } from '../../../../tests/helpers/store';
|
||||||
|
import { useSettingsStore } from '../../../store/settingsStore';
|
||||||
|
import { TourActivityStatsDialog } from './TourActivityStatsDialog';
|
||||||
|
import type { TourActivityStats } from './useTourActivityStats';
|
||||||
|
|
||||||
|
const navigate = vi.hoisted(() => vi.fn());
|
||||||
|
vi.mock('react-router', async (importOriginal) => ({
|
||||||
|
...(await importOriginal<typeof import('react-router')>()),
|
||||||
|
useNavigate: () => navigate,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const TODAY = '2026-10-20';
|
||||||
|
|
||||||
|
function entry(overrides: Partial<TourActivityStatsEntry> = {}): TourActivityStatsEntry {
|
||||||
|
return {
|
||||||
|
place_id: 1,
|
||||||
|
name: 'Ridge',
|
||||||
|
tour_type: 'hike',
|
||||||
|
trip: { id: 5, title: 'Alps' },
|
||||||
|
derived_from_place_id: null,
|
||||||
|
date: '2026-07-02',
|
||||||
|
basis: 'plan',
|
||||||
|
track: null,
|
||||||
|
day_count: 1,
|
||||||
|
distance_km: 12,
|
||||||
|
ascent_m: 800,
|
||||||
|
descent_m: 790,
|
||||||
|
excluded: false,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function statsOf(
|
||||||
|
data: TourActivityStatsResponse | null,
|
||||||
|
overrides: Partial<TourActivityStats> = {}
|
||||||
|
): TourActivityStats {
|
||||||
|
return {
|
||||||
|
status: data ? 'ready' : 'loading',
|
||||||
|
data,
|
||||||
|
summary: data ? summarizeTourActivities(data.entries, { today: TODAY }) : null,
|
||||||
|
period: 'all',
|
||||||
|
setPeriod: vi.fn(),
|
||||||
|
periods: ['all', 'thisYear', 'last12'],
|
||||||
|
type: 'all',
|
||||||
|
setType: vi.fn(),
|
||||||
|
types: ['all', 'hike', 'kayak'],
|
||||||
|
pending: new Set(),
|
||||||
|
setExcluded: vi.fn().mockResolvedValue(undefined),
|
||||||
|
retry: vi.fn(),
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const data: TourActivityStatsResponse = {
|
||||||
|
entries: [
|
||||||
|
entry(),
|
||||||
|
entry({
|
||||||
|
place_id: 2,
|
||||||
|
name: 'Lake',
|
||||||
|
tour_type: 'kayak',
|
||||||
|
date: '2026-08-01',
|
||||||
|
basis: 'track',
|
||||||
|
track: { place_id: 9, name: 'Watch export' },
|
||||||
|
distance_km: 8.5,
|
||||||
|
ascent_m: null,
|
||||||
|
descent_m: null,
|
||||||
|
}),
|
||||||
|
entry({ place_id: 3, name: 'Long trail', date: '2026-06-01', day_count: 3, distance_km: null }),
|
||||||
|
entry({ place_id: 4, name: 'Rained off', date: '2026-05-01', excluded: true }),
|
||||||
|
entry({ place_id: 5, name: 'Next week', date: '2026-10-27' }),
|
||||||
|
],
|
||||||
|
uncounted: { unassigned: 2, undated: 0 },
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
resetAllStores();
|
||||||
|
vi.clearAllMocks();
|
||||||
|
seedStore(useSettingsStore, { settings: buildSettings({ distance_unit: 'metric' }) });
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('TourActivityStatsDialog', () => {
|
||||||
|
it('FE-STA2-DIALOG-001: shows the sums, at least where a tour lacks the distance, and what they rest on', () => {
|
||||||
|
render(<TourActivityStatsDialog stats={statsOf(data)} open onClose={vi.fn()} />);
|
||||||
|
expect(screen.getByRole('heading', { name: 'My tour activities' })).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('≥ 20.5 km')).toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId('tour-activity-basis-plan')).toHaveTextContent('2');
|
||||||
|
expect(screen.getByTestId('tour-activity-basis-track')).toHaveTextContent('1');
|
||||||
|
expect(screen.getByTestId('tour-activity-upcoming')).toHaveTextContent('1');
|
||||||
|
expect(screen.getByTestId('tour-activity-unassigned')).toHaveTextContent('2');
|
||||||
|
expect(screen.queryByTestId('tour-activity-undated')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-DIALOG-002: splits by type, the count at the corner of each type', () => {
|
||||||
|
render(<TourActivityStatsDialog stats={statsOf(data)} open onClose={vi.fn()} />);
|
||||||
|
expect(within(screen.getByTestId('tour-activity-type-hike')).getByText('2')).toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId('tour-activity-type-kayak-distance')).toHaveTextContent('8.5 km');
|
||||||
|
expect(screen.queryByTestId('tour-activity-type-kayak-ascent')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-DIALOG-003: lists every done tour, newest first, with its basis; the one ahead is not there', () => {
|
||||||
|
render(<TourActivityStatsDialog stats={statsOf(data)} open onClose={vi.fn()} />);
|
||||||
|
const list = screen.getByTestId('tour-activity-list');
|
||||||
|
expect(within(list).getAllByRole('listitem')).toHaveLength(4);
|
||||||
|
expect(screen.queryByText('Next week')).not.toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId('tour-activity-row-2-9')).toHaveTextContent('Recorded');
|
||||||
|
expect(screen.getByTestId('tour-activity-track-corner')).toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId('tour-activity-row-1')).toHaveTextContent('Planned');
|
||||||
|
expect(
|
||||||
|
within(screen.getByTestId('tour-activity-row-3')).getByLabelText('Planned on several days, counted once')
|
||||||
|
).toHaveTextContent('3');
|
||||||
|
expect(screen.queryByTestId('tour-activity-3-distance')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-DIALOG-004: a tour left out stays listed and can be counted again, a counted one left out', async () => {
|
||||||
|
const stats = statsOf(data);
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<TourActivityStatsDialog stats={stats} open onClose={vi.fn()} />);
|
||||||
|
expect(screen.getByTestId('tour-activity-row-4')).toHaveTextContent('Left out');
|
||||||
|
await user.click(screen.getByRole('button', { name: 'Count again' }));
|
||||||
|
expect(stats.setExcluded).toHaveBeenCalledWith(expect.objectContaining({ place_id: 4 }), false);
|
||||||
|
await user.click(within(screen.getByTestId('tour-activity-row-1')).getByRole('button', { name: 'Leave out' }));
|
||||||
|
expect(stats.setExcluded).toHaveBeenCalledWith(expect.objectContaining({ place_id: 1 }), true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-DIALOG-005: a tour on its way to the server cannot be switched twice', () => {
|
||||||
|
render(<TourActivityStatsDialog stats={statsOf(data, { pending: new Set([1]) })} open onClose={vi.fn()} />);
|
||||||
|
expect(screen.getByTestId('tour-activity-toggle-1')).toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-DIALOG-006: the trip of a tour opens from its badge', async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<TourActivityStatsDialog stats={statsOf(data)} open onClose={vi.fn()} />);
|
||||||
|
await user.click(within(screen.getByTestId('tour-activity-row-1')).getByText('Alps'));
|
||||||
|
expect(navigate).toHaveBeenCalledWith('/trips/5');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-DIALOG-007: the filters sit on the head band and change period and type', async () => {
|
||||||
|
const stats = statsOf(data);
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<TourActivityStatsDialog stats={stats} open onClose={vi.fn()} />);
|
||||||
|
await user.click(screen.getByRole('button', { name: /Period/ }));
|
||||||
|
await user.click(screen.getByRole('button', { name: 'This year' }));
|
||||||
|
expect(stats.setPeriod).toHaveBeenCalledWith('thisYear');
|
||||||
|
await user.click(screen.getByRole('button', { name: /Type/ }));
|
||||||
|
await user.click(screen.getByRole('button', { name: 'Paddle tour' }));
|
||||||
|
expect(stats.setType).toHaveBeenCalledWith('kayak');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-DIALOG-008: before the read, while empty, and closed', async () => {
|
||||||
|
const onClose = vi.fn();
|
||||||
|
const user = userEvent.setup();
|
||||||
|
const { rerender } = render(<TourActivityStatsDialog stats={statsOf(null)} open onClose={onClose} />);
|
||||||
|
expect(screen.getByRole('status')).toHaveTextContent('Loading');
|
||||||
|
rerender(
|
||||||
|
<TourActivityStatsDialog
|
||||||
|
stats={statsOf({ entries: [], uncounted: { unassigned: 0, undated: 0 } })}
|
||||||
|
open
|
||||||
|
onClose={onClose}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
expect(screen.getByText('No completed tours yet')).toBeInTheDocument();
|
||||||
|
const [closeButton] = screen.getAllByRole('button', { name: 'Close' });
|
||||||
|
await user.click(closeButton as HTMLElement);
|
||||||
|
expect(onClose).toHaveBeenCalled();
|
||||||
|
rerender(<TourActivityStatsDialog stats={statsOf(null)} open={false} onClose={onClose} />);
|
||||||
|
expect(screen.queryByText('My tour activities')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
import type { TourActivityTotals, TourTypeKey } from '@trek/shared';
|
||||||
|
import { Footprints } from 'lucide-react';
|
||||||
|
import { createElement, useId } from 'react';
|
||||||
|
import { useTranslation } from '../../../i18n';
|
||||||
|
import type { DistanceUnit } from '../../../types';
|
||||||
|
import {
|
||||||
|
DialogButton,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogSection,
|
||||||
|
DialogShell,
|
||||||
|
DialogTile,
|
||||||
|
FooterSpacer,
|
||||||
|
fs,
|
||||||
|
NEUTRAL_TINT,
|
||||||
|
} from '../../shared/DialogShell';
|
||||||
|
import { InfoDot, TourFactFields, type TourMetricField } from '../../Tours/tourParts';
|
||||||
|
import { TourActivityEntryRow } from './TourActivityEntryRow';
|
||||||
|
import { ActivityFilters, ActivityStatusLine, BasisBadges, MeasurePills, UncountedBadges } from './tourActivityParts';
|
||||||
|
import { distanceReading, heightReading, partialHint, typeIcon, useDistanceUnit } from './tourActivityReading';
|
||||||
|
import type { TourActivityStats } from './useTourActivityStats';
|
||||||
|
|
||||||
|
type Translate = (key: string, params?: Record<string, unknown>) => string;
|
||||||
|
|
||||||
|
/** The sums as labelled fields; a sum nobody knows is left out, a short one says at least and why. */
|
||||||
|
function totalFields(totals: TourActivityTotals, unit: DistanceUnit, t: Translate): TourMetricField[] {
|
||||||
|
const fields: TourMetricField[] = [{ label: t('tours.mode.tours'), value: String(totals.count) }];
|
||||||
|
const sums = [
|
||||||
|
{ label: t('tours.detail.distance'), sum: totals.distanceKm, reading: distanceReading(totals, unit) },
|
||||||
|
{ label: t('tours.detail.ascent'), sum: totals.ascentM, reading: heightReading(totals.ascentM, unit) },
|
||||||
|
{ label: t('tours.detail.descent'), sum: totals.descentM, reading: heightReading(totals.descentM, unit) },
|
||||||
|
];
|
||||||
|
for (const { label, sum, reading } of sums) {
|
||||||
|
if (!reading) continue;
|
||||||
|
const info = reading.partial ? { label, description: partialHint(sum, t) } : undefined;
|
||||||
|
fields.push({ label, value: reading.text, info });
|
||||||
|
}
|
||||||
|
return fields;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One type of the period: its icon with how many tours at the corner, its name, its distance and climb. */
|
||||||
|
function TypeLine({ type, totals }: { type: TourTypeKey; totals: TourActivityTotals }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const unit = useDistanceUnit();
|
||||||
|
const distance = distanceReading(totals, unit);
|
||||||
|
const ascent = heightReading(totals.ascentM, unit);
|
||||||
|
return (
|
||||||
|
<li className="flex min-w-0 items-center gap-3 py-1" data-testid={`tour-activity-type-${type}`}>
|
||||||
|
<span className="relative flex-none">
|
||||||
|
<span className="grid h-[30px] w-[30px] place-items-center rounded-full bg-edge text-content-secondary">
|
||||||
|
{createElement(typeIcon(type), { size: 14, strokeWidth: 1.9 })}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
aria-hidden="true"
|
||||||
|
className="absolute -end-1.5 -top-1.5 grid h-4 min-w-4 place-items-center rounded-full bg-surface-card px-1 font-geist font-semibold tabular-nums text-content shadow-sm ring-1 ring-edge-faint"
|
||||||
|
style={fs(9)}
|
||||||
|
>
|
||||||
|
{totals.count}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
<span className="min-w-0 flex-1 truncate font-semibold text-content" style={fs(12.5, 'body')}>
|
||||||
|
{t(`tourTypes.${type}`)}
|
||||||
|
<span className="sr-only">{`: ${t('tours.mode.tours')} ${totals.count}`}</span>
|
||||||
|
</span>
|
||||||
|
<span className="flex flex-none items-center gap-1.5">
|
||||||
|
<MeasurePills
|
||||||
|
distance={distance?.text ?? null}
|
||||||
|
ascent={ascent?.text ?? null}
|
||||||
|
testId={`tour-activity-type-${type}`}
|
||||||
|
/>
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The sums, what they rest on, the split by type, and every tour of the period with its switch. */
|
||||||
|
function StatsBody({ stats }: { stats: TourActivityStats }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const unit = useDistanceUnit();
|
||||||
|
const { summary, data } = stats;
|
||||||
|
if (!summary || !data) return <ActivityStatusLine stats={stats} />;
|
||||||
|
const showTypes = stats.type === 'all' && summary.types.length > 1;
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="flex flex-col gap-2.5">
|
||||||
|
<TourFactFields fields={totalFields(summary.totals, unit, t)} />
|
||||||
|
<div className="flex flex-wrap items-center gap-1.5">
|
||||||
|
<BasisBadges byBasis={summary.totals.byBasis} />
|
||||||
|
<UncountedBadges upcoming={summary.upcoming} {...data.uncounted} />
|
||||||
|
<InfoDot label={t('tours.stats.title')} description={t('tours.stats.basisInfo')} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{showTypes && (
|
||||||
|
<DialogSection label={t('tours.stats.byType')}>
|
||||||
|
<ul className="m-0 flex list-none flex-col gap-1 p-0">
|
||||||
|
{summary.types.map(({ type, ...totals }) => (
|
||||||
|
<TypeLine key={type} type={type} totals={totals} />
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</DialogSection>
|
||||||
|
)}
|
||||||
|
<DialogSection
|
||||||
|
label={t('tours.mode.tours')}
|
||||||
|
action={
|
||||||
|
<span className="font-geist tabular-nums text-content-faint" style={fs(11)}>
|
||||||
|
{summary.done.length}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{summary.done.length === 0 ? (
|
||||||
|
<p className="m-0 py-4 text-center text-content-muted" style={fs(12.5, 'body')}>
|
||||||
|
{t(data.entries.length === 0 ? 'tours.stats.empty' : 'tours.stats.none')}
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<ul className="-mx-2.5 my-0 flex list-none flex-col gap-0.5 p-0" data-testid="tour-activity-list">
|
||||||
|
{summary.done.map((entry) => (
|
||||||
|
<TourActivityEntryRow
|
||||||
|
key={entry.track ? `${entry.place_id}-${entry.track.place_id}` : entry.place_id}
|
||||||
|
entry={entry}
|
||||||
|
busy={stats.pending.has(entry.place_id)}
|
||||||
|
onToggleExcluded={(target) => void stats.setExcluded(target, !target.excluded)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</DialogSection>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* STA-02: the user's tour activities in full, opened from the Atlas: the
|
||||||
|
* period and type on the head band, the sums with what they rest on, the
|
||||||
|
* split by type, and every tour done in the period, each one able to be left
|
||||||
|
* out (a tour that fell through) and counted again without touching its plan.
|
||||||
|
*/
|
||||||
|
export function TourActivityStatsDialog({
|
||||||
|
stats,
|
||||||
|
open,
|
||||||
|
onClose,
|
||||||
|
}: {
|
||||||
|
stats: TourActivityStats;
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
}) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const labelId = useId();
|
||||||
|
return (
|
||||||
|
<DialogShell
|
||||||
|
open={open}
|
||||||
|
onClose={onClose}
|
||||||
|
labelledBy={labelId}
|
||||||
|
width="editor"
|
||||||
|
header={
|
||||||
|
<DialogHeader
|
||||||
|
tile={
|
||||||
|
<DialogTile>
|
||||||
|
<Footprints size={20} strokeWidth={2} className="text-content" />
|
||||||
|
</DialogTile>
|
||||||
|
}
|
||||||
|
tint={NEUTRAL_TINT}
|
||||||
|
labelId={labelId}
|
||||||
|
onClose={onClose}
|
||||||
|
title={t('tours.stats.title')}
|
||||||
|
sub={t('tours.stats.sub')}
|
||||||
|
subWraps
|
||||||
|
pills={<ActivityFilters stats={stats} />}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
footer={
|
||||||
|
<DialogFooter>
|
||||||
|
<FooterSpacer />
|
||||||
|
<DialogButton onClick={onClose}>{t('common.close')}</DialogButton>
|
||||||
|
</DialogFooter>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<StatsBody stats={stats} />
|
||||||
|
</DialogShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
import type { TourActivityBasis, TourActivityStatsEntry } from '@trek/shared';
|
||||||
|
import {
|
||||||
|
AlertTriangle,
|
||||||
|
ArrowUp,
|
||||||
|
CalendarClock,
|
||||||
|
CalendarDays,
|
||||||
|
CalendarRange,
|
||||||
|
Footprints,
|
||||||
|
Loader2,
|
||||||
|
Ruler,
|
||||||
|
WifiOff,
|
||||||
|
} from 'lucide-react';
|
||||||
|
import { createElement } from 'react';
|
||||||
|
import { useTranslation } from '../../../i18n';
|
||||||
|
import { PillSelect } from '../../shared/dialogParts';
|
||||||
|
import { fs } from '../../shared/DialogShell';
|
||||||
|
import { Tooltip } from '../../shared/Tooltip';
|
||||||
|
import { FigureBadge } from '../../Tours/paddle/FigureBadge';
|
||||||
|
import { TourDayRowPill } from '../../Tours/TourDayRowFacts';
|
||||||
|
import { tourDayRowIcon } from '../../Tours/tourDayRowIcon';
|
||||||
|
import { typeIcon, typeLabel, type Translate } from './tourActivityReading';
|
||||||
|
import { periodYear, type ActivityPeriod, type ActivityType } from './tourActivityStatsModel';
|
||||||
|
import type { TourActivityStats } from './useTourActivityStats';
|
||||||
|
|
||||||
|
/** What a period is called in the filter. */
|
||||||
|
function periodLabel(period: ActivityPeriod, t: Translate): string {
|
||||||
|
if (period === 'all') return t('tours.stats.period.all');
|
||||||
|
if (period === 'thisYear') return t('tours.stats.period.thisYear');
|
||||||
|
if (period === 'last12') return t('tours.stats.period.last12');
|
||||||
|
return String(periodYear(period));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The period and type filters, as head band pills or quiet ones in a panel. */
|
||||||
|
export function ActivityFilters({ stats, quiet = false }: { stats: TourActivityStats; quiet?: boolean }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const typeOption = (type: ActivityType) => ({
|
||||||
|
value: type,
|
||||||
|
label: typeLabel(type, t),
|
||||||
|
icon: createElement(typeIcon(type), { size: 12, strokeWidth: 2.2, className: 'flex-none text-content-muted' }),
|
||||||
|
});
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<PillSelect
|
||||||
|
quiet={quiet}
|
||||||
|
label={t('tours.stats.period')}
|
||||||
|
value={stats.period}
|
||||||
|
options={stats.periods.map((period) => ({
|
||||||
|
value: period,
|
||||||
|
label: periodLabel(period, t),
|
||||||
|
icon: <CalendarRange size={12} strokeWidth={2.2} className="flex-none text-content-muted" />,
|
||||||
|
}))}
|
||||||
|
fallback={{ label: periodLabel(stats.period, t) }}
|
||||||
|
onChange={stats.setPeriod}
|
||||||
|
/>
|
||||||
|
<PillSelect
|
||||||
|
quiet={quiet}
|
||||||
|
label={t('tours.filter.type')}
|
||||||
|
value={stats.type}
|
||||||
|
options={stats.types.map(typeOption)}
|
||||||
|
fallback={typeOption(stats.type)}
|
||||||
|
onChange={stats.setType}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A distance and a climb as white badges, each named in full by its tooltip; one not known is left out. */
|
||||||
|
export function MeasurePills({
|
||||||
|
distance,
|
||||||
|
ascent,
|
||||||
|
testId,
|
||||||
|
}: {
|
||||||
|
distance: string | null;
|
||||||
|
ascent: string | null;
|
||||||
|
/** Prefix of the badges' test ids: `<testId>-distance`, `<testId>-ascent`. */
|
||||||
|
testId: string;
|
||||||
|
}) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{distance !== null && (
|
||||||
|
<TourDayRowPill
|
||||||
|
icon={Ruler}
|
||||||
|
value={distance}
|
||||||
|
label={`${t('tours.detail.distance')}: ${distance}`}
|
||||||
|
testId={`${testId}-distance`}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{ascent !== null && (
|
||||||
|
<TourDayRowPill
|
||||||
|
icon={ArrowUp}
|
||||||
|
value={ascent}
|
||||||
|
label={`${t('tours.detail.ascent')}: ${ascent}`}
|
||||||
|
testId={`${testId}-ascent`}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What the sums rest on, each as a figure badge: how many tours count with
|
||||||
|
* their planned values and how many with a recorded track. The planned values
|
||||||
|
* are never passed off as measured, so they always say so.
|
||||||
|
*/
|
||||||
|
export function BasisBadges({ byBasis }: { byBasis: Record<TourActivityBasis, number> }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{byBasis.plan > 0 && (
|
||||||
|
<FigureBadge
|
||||||
|
testId="tour-activity-basis-plan"
|
||||||
|
label={t('tours.stats.basisPlan')}
|
||||||
|
value={String(byBasis.plan)}
|
||||||
|
icon={<CalendarDays size={10} strokeWidth={2.2} className="flex-none text-content-faint" />}
|
||||||
|
info={t('tours.stats.basisPlanHint')}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{byBasis.track > 0 && (
|
||||||
|
<FigureBadge
|
||||||
|
testId="tour-activity-basis-track"
|
||||||
|
label={t('tours.stats.basisTrack')}
|
||||||
|
value={String(byBasis.track)}
|
||||||
|
icon={<Footprints size={10} strokeWidth={2.2} className="flex-none text-success" />}
|
||||||
|
info={t('tours.stats.basisTrackCountHint')}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What does not count, said as quiet figure badges: tours still ahead, on no day, on days without a date. */
|
||||||
|
export function UncountedBadges({
|
||||||
|
upcoming,
|
||||||
|
unassigned,
|
||||||
|
undated,
|
||||||
|
}: {
|
||||||
|
upcoming: number;
|
||||||
|
unassigned: number;
|
||||||
|
undated: number;
|
||||||
|
}) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const badges = [
|
||||||
|
{ key: 'upcoming', value: upcoming, labelKey: 'tours.stats.upcoming', infoKey: 'tours.stats.upcomingHint' },
|
||||||
|
{
|
||||||
|
key: 'unassigned',
|
||||||
|
value: unassigned,
|
||||||
|
labelKey: 'tours.stats.unassigned',
|
||||||
|
infoKey: 'tours.stats.unassignedHint',
|
||||||
|
},
|
||||||
|
{ key: 'undated', value: undated, labelKey: 'tours.stats.undated', infoKey: 'tours.stats.undatedHint' },
|
||||||
|
];
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{badges
|
||||||
|
.filter((badge) => badge.value > 0)
|
||||||
|
.map((badge) => (
|
||||||
|
<FigureBadge
|
||||||
|
key={badge.key}
|
||||||
|
testId={`tour-activity-${badge.key}`}
|
||||||
|
label={t(badge.labelKey)}
|
||||||
|
value={String(badge.value)}
|
||||||
|
icon={<CalendarClock size={10} strokeWidth={2.2} className="flex-none text-content-faint" />}
|
||||||
|
info={t(badge.infoKey)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A tour's type as a round tile; a tour done with a recorded track carries
|
||||||
|
* the footprints at its corner, the way a waypoint's number carries its kind.
|
||||||
|
*/
|
||||||
|
export function EntryTile({ entry }: { entry: Pick<TourActivityStatsEntry, 'tour_type' | 'basis'> }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<Tooltip label={t(`tourTypes.${entry.tour_type}`)}>
|
||||||
|
<span className="relative flex-none" aria-label={t(`tourTypes.${entry.tour_type}`)}>
|
||||||
|
<span className="grid h-[34px] w-[34px] place-items-center rounded-full bg-edge text-content-secondary">
|
||||||
|
{createElement(tourDayRowIcon(entry.tour_type), { size: 15, strokeWidth: 1.9 })}
|
||||||
|
</span>
|
||||||
|
{entry.basis === 'track' && (
|
||||||
|
<span
|
||||||
|
aria-hidden="true"
|
||||||
|
data-testid="tour-activity-track-corner"
|
||||||
|
className="absolute -bottom-1 -end-1 grid h-4 w-4 place-items-center rounded-full bg-success-soft text-success ring-2 ring-surface-card"
|
||||||
|
>
|
||||||
|
<Footprints size={9} strokeWidth={2.6} />
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
</Tooltip>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where the read stands while there is nothing to show yet: on its way, refused
|
||||||
|
* offline, or failed with a way to try again.
|
||||||
|
*/
|
||||||
|
export function ActivityStatusLine({ stats }: { stats: Pick<TourActivityStats, 'status' | 'retry'> }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
// Not asked yet: the tab has not been shown, so there is nothing to say.
|
||||||
|
if (stats.status === 'idle') return null;
|
||||||
|
if (stats.status === 'offline')
|
||||||
|
return (
|
||||||
|
<p className="m-0 flex items-center gap-2 text-content-muted" style={fs(12, 'body')}>
|
||||||
|
<WifiOff size={13} strokeWidth={2} className="flex-none" />
|
||||||
|
{t('common.needsConnection')}
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
if (stats.status === 'error')
|
||||||
|
return (
|
||||||
|
<p role="alert" className="m-0 flex flex-wrap items-center gap-2 text-content-muted" style={fs(12, 'body')}>
|
||||||
|
<AlertTriangle size={13} strokeWidth={2} className="flex-none text-warning" />
|
||||||
|
{t('tours.stats.unavailable')}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={stats.retry}
|
||||||
|
className="font-semibold text-content underline underline-offset-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent"
|
||||||
|
>
|
||||||
|
{t('common.errorRetry')}
|
||||||
|
</button>
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<p role="status" className="m-0 flex items-center gap-2 text-content-faint" style={fs(12, 'body')}>
|
||||||
|
<Loader2 size={13} strokeWidth={2.2} className="flex-none animate-spin" />
|
||||||
|
{t('common.loading')}
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import type { TourActivityTotals } from '@trek/shared';
|
||||||
|
import { Layers, type LucideIcon } from 'lucide-react';
|
||||||
|
import { useSettingsStore } from '../../../store/settingsStore';
|
||||||
|
import type { DistanceUnit } from '../../../types';
|
||||||
|
import { formatDistance, formatElevation } from '../../../utils/units';
|
||||||
|
import { tourDayRowIcon } from '../../Tours/tourDayRowIcon';
|
||||||
|
import { sumReading, type ActivityType } from './tourActivityStatsModel';
|
||||||
|
|
||||||
|
export type Translate = (key: string, params?: Record<string, unknown>) => string;
|
||||||
|
|
||||||
|
/** The distance unit the user reads in. */
|
||||||
|
export function useDistanceUnit(): DistanceUnit {
|
||||||
|
return useSettingsStore((state) => state.settings.distance_unit) ?? 'metric';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What a type is called in the filter. */
|
||||||
|
export function typeLabel(type: ActivityType, t: Translate): string {
|
||||||
|
return type === 'all' ? t('tours.stats.allTypes') : t(`tourTypes.${type}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The icon a type is drawn with; every type at once is a stack. */
|
||||||
|
export function typeIcon(type: ActivityType): LucideIcon {
|
||||||
|
return type === 'all' ? Layers : tourDayRowIcon(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A distance as said, at least that much when some tours do not know theirs; null when none does. */
|
||||||
|
export function distanceReading(totals: Pick<TourActivityTotals, 'distanceKm'>, unit: DistanceUnit) {
|
||||||
|
return sumReading(totals.distanceKm, (km) => formatDistance(km, unit));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A height sum as said, the same way. */
|
||||||
|
export function heightReading(sum: TourActivityTotals['ascentM'], unit: DistanceUnit) {
|
||||||
|
return sumReading(sum, (metres) => formatElevation(metres, unit));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How a short sum explains itself: known for some of the tours only. */
|
||||||
|
export function partialHint(sum: TourActivityTotals['distanceKm'], t: Translate): string {
|
||||||
|
return t('tours.scope.partialBody', { known: sum.known, of: sum.of });
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
// FE-STA2-MODEL-001 to FE-STA2-MODEL-007
|
||||||
|
// STA-02: the periods and types the Atlas offers for the user's tour
|
||||||
|
// activities, and how a sum reads when some tours do not know the value.
|
||||||
|
import type { TourActivityStatsEntry } from '@trek/shared';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import {
|
||||||
|
periodOptions,
|
||||||
|
periodRange,
|
||||||
|
periodYear,
|
||||||
|
splitMeasure,
|
||||||
|
sumReading,
|
||||||
|
typeOptions,
|
||||||
|
} from './tourActivityStatsModel';
|
||||||
|
|
||||||
|
const TODAY = '2026-10-20';
|
||||||
|
|
||||||
|
function entry(overrides: Partial<TourActivityStatsEntry> = {}): TourActivityStatsEntry {
|
||||||
|
return {
|
||||||
|
place_id: 1,
|
||||||
|
name: 'Ridge',
|
||||||
|
tour_type: 'hike',
|
||||||
|
trip: { id: 5, title: 'Alps' },
|
||||||
|
derived_from_place_id: null,
|
||||||
|
date: '2026-07-02',
|
||||||
|
basis: 'plan',
|
||||||
|
track: null,
|
||||||
|
day_count: 1,
|
||||||
|
distance_km: 10,
|
||||||
|
ascent_m: 500,
|
||||||
|
descent_m: 400,
|
||||||
|
excluded: false,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('tourActivityStatsModel', () => {
|
||||||
|
it('FE-STA2-MODEL-001: each period covers its days, both ends included', () => {
|
||||||
|
expect(periodRange('all', TODAY)).toEqual({ from: null, to: null });
|
||||||
|
expect(periodRange('thisYear', TODAY)).toEqual({ from: '2026-01-01', to: '2026-12-31' });
|
||||||
|
expect(periodRange('last12', TODAY)).toEqual({ from: '2025-10-20', to: TODAY });
|
||||||
|
expect(periodRange('year:2024', TODAY)).toEqual({ from: '2024-01-01', to: '2024-12-31' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-MODEL-002: offers the earlier years a done tour is in, the newest first, and no empty one', () => {
|
||||||
|
const entries = [
|
||||||
|
entry({ date: '2023-05-01' }),
|
||||||
|
entry({ date: '2025-08-01' }),
|
||||||
|
entry({ date: '2025-09-01' }),
|
||||||
|
entry({ date: '2026-03-01' }),
|
||||||
|
];
|
||||||
|
expect(periodOptions(entries, TODAY)).toEqual(['all', 'thisYear', 'last12', 'year:2025', 'year:2023']);
|
||||||
|
expect(periodOptions([], TODAY)).toEqual(['all', 'thisYear', 'last12']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-MODEL-003: offers the types of done tours only, in planning order, older types after them', () => {
|
||||||
|
const entries = [
|
||||||
|
entry({ tour_type: 'kayak' }),
|
||||||
|
entry({ tour_type: 'run' }),
|
||||||
|
entry({ tour_type: 'hike' }),
|
||||||
|
entry({ tour_type: 'bike', date: '2026-12-01' }),
|
||||||
|
];
|
||||||
|
expect(typeOptions(entries, TODAY)).toEqual(['all', 'hike', 'run', 'kayak']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-MODEL-004: reads the year of a year period only', () => {
|
||||||
|
expect(periodYear('year:2024')).toBe(2024);
|
||||||
|
expect(periodYear('thisYear')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-MODEL-005: a sum nobody knows says nothing, a short one says at least', () => {
|
||||||
|
const km = (value: number) => `${value} km`;
|
||||||
|
expect(sumReading({ value: null, known: 0, of: 2 }, km)).toBeNull();
|
||||||
|
expect(sumReading({ value: 12, known: 2, of: 2 }, km)).toEqual({ text: '12 km', partial: false });
|
||||||
|
expect(sumReading({ value: 12, known: 1, of: 2 }, km)).toEqual({ text: '≥ 12 km', partial: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-MODEL-006: splits a measure into its number and unit', () => {
|
||||||
|
expect(splitMeasure('128.4 km')).toEqual({ value: '128.4', unit: 'km' });
|
||||||
|
expect(splitMeasure('≥ 12 km')).toEqual({ value: '≥ 12', unit: 'km' });
|
||||||
|
expect(splitMeasure('12')).toEqual({ value: '12', unit: '' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-MODEL-007: a tour still ahead offers neither its year nor its type', () => {
|
||||||
|
expect(periodOptions([entry({ date: '2025-01-01' }), entry({ date: '2027-01-01' })], TODAY)).toEqual([
|
||||||
|
'all',
|
||||||
|
'thisYear',
|
||||||
|
'last12',
|
||||||
|
'year:2025',
|
||||||
|
]);
|
||||||
|
expect(typeOptions([entry({ tour_type: 'walk', date: TODAY })], TODAY)).toEqual(['all']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-MODEL-008: a planned ski tour is a type of its own, after the types planned before it', () => {
|
||||||
|
const entries = [entry({ tour_type: 'ski' }), entry({ tour_type: 'horse' }), entry({ tour_type: 'hike' })];
|
||||||
|
expect(typeOptions(entries, TODAY)).toEqual(['all', 'hike', 'horse', 'ski']);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import {
|
||||||
|
isTourActivityDone,
|
||||||
|
plannableTourTypeSchema,
|
||||||
|
type TourActivityStatsEntry,
|
||||||
|
type TourActivitySum,
|
||||||
|
type TourTypeKey,
|
||||||
|
} from '@trek/shared';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* STA-02: the periods and types the Atlas narrows the user's tour activities
|
||||||
|
* by, and how a sum reads. Pure, so the hook and its views share one answer.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** All time, the calendar year, the last twelve months, or one earlier year. */
|
||||||
|
export type ActivityPeriod = 'all' | 'thisYear' | 'last12' | `year:${number}`;
|
||||||
|
|
||||||
|
/** One type, or every type at once. */
|
||||||
|
export type ActivityType = TourTypeKey | 'all';
|
||||||
|
|
||||||
|
interface PeriodRange {
|
||||||
|
from: string | null;
|
||||||
|
to: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The days a period covers, both included, for `today` (YYYY-MM-DD in the user's own calendar). */
|
||||||
|
export function periodRange(period: ActivityPeriod, today: string): PeriodRange {
|
||||||
|
const year = Number(today.slice(0, 4));
|
||||||
|
if (period === 'thisYear') return { from: `${year}-01-01`, to: `${year}-12-31` };
|
||||||
|
// A year back to the day, today included: the same day a year ago is the first one.
|
||||||
|
if (period === 'last12') return { from: `${year - 1}${today.slice(4)}`, to: today };
|
||||||
|
if (period.startsWith('year:')) {
|
||||||
|
const chosen = period.slice(5);
|
||||||
|
return { from: `${chosen}-01-01`, to: `${chosen}-12-31` };
|
||||||
|
}
|
||||||
|
return { from: null, to: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The periods worth offering: all time, this year and the last twelve months,
|
||||||
|
* then each earlier year a done tour is in, the newest first. A year without
|
||||||
|
* a tour would only ever show nothing.
|
||||||
|
*/
|
||||||
|
export function periodOptions(entries: readonly TourActivityStatsEntry[], today: string): ActivityPeriod[] {
|
||||||
|
const thisYear = today.slice(0, 4);
|
||||||
|
const years = new Set(
|
||||||
|
entries
|
||||||
|
.filter((entry) => isTourActivityDone(entry, today))
|
||||||
|
.map((entry) => entry.date.slice(0, 4))
|
||||||
|
.filter((year) => year < thisYear)
|
||||||
|
);
|
||||||
|
const earlier = [...years].sort((a, b) => b.localeCompare(a)).map((year): ActivityPeriod => `year:${Number(year)}`);
|
||||||
|
return ['all', 'thisYear', 'last12', ...earlier];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The types a done tour has, in the order tours are planned in, the older types after them. */
|
||||||
|
export function typeOptions(entries: readonly TourActivityStatsEntry[], today: string): ActivityType[] {
|
||||||
|
const present = new Set(entries.filter((entry) => isTourActivityDone(entry, today)).map((entry) => entry.tour_type));
|
||||||
|
const planned: readonly string[] = plannableTourTypeSchema.options;
|
||||||
|
const ordered = [...present].sort((a, b) => rank(planned, a) - rank(planned, b) || a.localeCompare(b));
|
||||||
|
return ['all', ...ordered];
|
||||||
|
}
|
||||||
|
|
||||||
|
function rank(order: readonly string[], value: string): number {
|
||||||
|
const index = order.indexOf(value);
|
||||||
|
return index === -1 ? order.length : index;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The year of a `year:` period, or null for the others. */
|
||||||
|
export function periodYear(period: ActivityPeriod): number | null {
|
||||||
|
return period.startsWith('year:') ? Number(period.slice(5)) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A sum as it is said: nothing when nobody knows the value, else the value,
|
||||||
|
* marked as at least that much when some of the tours lack it.
|
||||||
|
*/
|
||||||
|
export function sumReading(
|
||||||
|
sum: TourActivitySum,
|
||||||
|
format: (value: number) => string
|
||||||
|
): { text: string; partial: boolean } | null {
|
||||||
|
if (sum.value === null) return null;
|
||||||
|
const partial = sum.known < sum.of;
|
||||||
|
return { text: partial ? `≥ ${format(sum.value)}` : format(sum.value), partial };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A formatted measure split into its number and its unit, so the number can stand large ("128.4", "km"). */
|
||||||
|
export function splitMeasure(text: string): { value: string; unit: string } {
|
||||||
|
const at = text.lastIndexOf(' ');
|
||||||
|
return at === -1 ? { value: text, unit: '' } : { value: text.slice(0, at), unit: text.slice(at + 1) };
|
||||||
|
}
|
||||||
@@ -0,0 +1,226 @@
|
|||||||
|
// FE-STA2-HOOK-001 to FE-STA2-HOOK-009
|
||||||
|
// STA-02: the user's own tour activities are read when the tab is first shown,
|
||||||
|
// narrowed by period and type, and a tour left out shows at once and comes back
|
||||||
|
// with a message when the server refuses.
|
||||||
|
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||||
|
import type { TourActivityStatsEntry, TourActivityStatsResponse } from '@trek/shared';
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { useTourActivityStats } from './useTourActivityStats';
|
||||||
|
|
||||||
|
const repo = vi.hoisted(() => ({ get: vi.fn(), setExcluded: vi.fn() }));
|
||||||
|
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }));
|
||||||
|
vi.mock('../../../repo/tourActivityStatsRepo', () => ({
|
||||||
|
tourActivityStatsRepo: repo,
|
||||||
|
TourActivityStatsOfflineError: class TourActivityStatsOfflineError extends Error {},
|
||||||
|
}));
|
||||||
|
vi.mock('../../shared/Toast', () => ({ useToast: () => toast }));
|
||||||
|
|
||||||
|
function entry(overrides: Partial<TourActivityStatsEntry> = {}): TourActivityStatsEntry {
|
||||||
|
return {
|
||||||
|
place_id: 1,
|
||||||
|
name: 'Ridge',
|
||||||
|
tour_type: 'hike',
|
||||||
|
trip: { id: 5, title: 'Alps' },
|
||||||
|
derived_from_place_id: null,
|
||||||
|
date: '2026-07-02',
|
||||||
|
basis: 'plan',
|
||||||
|
track: null,
|
||||||
|
day_count: 1,
|
||||||
|
distance_km: 10,
|
||||||
|
ascent_m: 500,
|
||||||
|
descent_m: 400,
|
||||||
|
excluded: false,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const stats: TourActivityStatsResponse = {
|
||||||
|
entries: [
|
||||||
|
entry(),
|
||||||
|
entry({ place_id: 2, name: 'Lake', tour_type: 'kayak', date: '2025-08-01', distance_km: 8 }),
|
||||||
|
entry({ place_id: 3, name: 'Summit', date: '2026-11-01' }),
|
||||||
|
],
|
||||||
|
uncounted: { unassigned: 0, undated: 0 },
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
vi.useFakeTimers({ toFake: ['Date'] });
|
||||||
|
vi.setSystemTime(new Date(2026, 9, 20, 12));
|
||||||
|
repo.get.mockResolvedValue(stats);
|
||||||
|
});
|
||||||
|
afterEach(() => vi.useRealTimers());
|
||||||
|
|
||||||
|
describe('useTourActivityStats', () => {
|
||||||
|
it('FE-STA2-HOOK-001: reads nothing until the tab is shown, then sums what is done', async () => {
|
||||||
|
const { result, rerender } = renderHook(({ active }) => useTourActivityStats(active), {
|
||||||
|
initialProps: { active: false },
|
||||||
|
});
|
||||||
|
expect(result.current.status).toBe('idle');
|
||||||
|
expect(repo.get).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
rerender({ active: true });
|
||||||
|
expect(result.current.status).toBe('loading');
|
||||||
|
await waitFor(() => expect(result.current.status).toBe('ready'));
|
||||||
|
expect(result.current.summary?.totals.count).toBe(2);
|
||||||
|
expect(result.current.summary?.totals.distanceKm.value).toBe(18);
|
||||||
|
expect(result.current.summary?.upcoming).toBe(1);
|
||||||
|
expect(result.current.periods).toEqual(['all', 'thisYear', 'last12', 'year:2025']);
|
||||||
|
expect(result.current.types).toEqual(['all', 'hike', 'kayak']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-HOOK-002: narrows by period and by type', async () => {
|
||||||
|
const { result } = renderHook(() => useTourActivityStats(true));
|
||||||
|
await waitFor(() => expect(result.current.status).toBe('ready'));
|
||||||
|
act(() => result.current.setPeriod('thisYear'));
|
||||||
|
expect(result.current.summary?.done.map((item) => item.place_id)).toEqual([1]);
|
||||||
|
act(() => {
|
||||||
|
result.current.setPeriod('all');
|
||||||
|
result.current.setType('kayak');
|
||||||
|
});
|
||||||
|
expect(result.current.summary?.done.map((item) => item.place_id)).toEqual([2]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-HOOK-003: offline and failed reads are told apart, and a retry reads again', async () => {
|
||||||
|
const { TourActivityStatsOfflineError } = await import('../../../repo/tourActivityStatsRepo');
|
||||||
|
repo.get.mockRejectedValueOnce(new TourActivityStatsOfflineError());
|
||||||
|
const { result } = renderHook(() => useTourActivityStats(true));
|
||||||
|
await waitFor(() => expect(result.current.status).toBe('offline'));
|
||||||
|
|
||||||
|
repo.get.mockRejectedValueOnce(new Error('boom'));
|
||||||
|
act(() => result.current.retry());
|
||||||
|
expect(result.current.status).toBe('loading');
|
||||||
|
await waitFor(() => expect(result.current.status).toBe('error'));
|
||||||
|
|
||||||
|
act(() => result.current.retry());
|
||||||
|
await waitFor(() => expect(result.current.status).toBe('ready'));
|
||||||
|
expect(repo.get).toHaveBeenCalledTimes(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-HOOK-004: leaving a tour out shows at once and takes the server answer', async () => {
|
||||||
|
let answer: (value: TourActivityStatsResponse) => void = () => undefined;
|
||||||
|
repo.setExcluded.mockReturnValue(new Promise((resolve) => (answer = resolve)));
|
||||||
|
const { result } = renderHook(() => useTourActivityStats(true));
|
||||||
|
await waitFor(() => expect(result.current.status).toBe('ready'));
|
||||||
|
|
||||||
|
let write: Promise<void> = Promise.resolve();
|
||||||
|
act(() => {
|
||||||
|
write = result.current.setExcluded(entry(), true);
|
||||||
|
});
|
||||||
|
expect(result.current.pending.has(1)).toBe(true);
|
||||||
|
expect(result.current.summary?.totals.count).toBe(1);
|
||||||
|
expect(repo.setExcluded).toHaveBeenCalledWith({ place_id: 1, excluded: true });
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
const entries = stats.entries.map((item) => (item.place_id === 1 ? { ...item, excluded: true } : item));
|
||||||
|
answer({ ...stats, entries });
|
||||||
|
await write;
|
||||||
|
});
|
||||||
|
expect(result.current.pending.size).toBe(0);
|
||||||
|
expect(result.current.summary?.done.find((item) => item.place_id === 1)?.excluded).toBe(true);
|
||||||
|
expect(toast.error).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-HOOK-005: a refused exclusion counts the tour again and says so', async () => {
|
||||||
|
repo.setExcluded.mockRejectedValue(new Error('nope'));
|
||||||
|
const { result } = renderHook(() => useTourActivityStats(true));
|
||||||
|
await waitFor(() => expect(result.current.status).toBe('ready'));
|
||||||
|
await act(async () => {
|
||||||
|
await result.current.setExcluded(entry(), true);
|
||||||
|
});
|
||||||
|
expect(result.current.summary?.totals.count).toBe(2);
|
||||||
|
expect(result.current.pending.size).toBe(0);
|
||||||
|
expect(toast.error).toHaveBeenCalledWith('tours.stats.excludeFailed');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-HOOK-006: a read answered after the tab went away is dropped', async () => {
|
||||||
|
let answer: (value: TourActivityStatsResponse) => void = () => undefined;
|
||||||
|
repo.get.mockReturnValue(new Promise((resolve) => (answer = resolve)));
|
||||||
|
const { result, unmount } = renderHook(() => useTourActivityStats(true));
|
||||||
|
expect(result.current.status).toBe('loading');
|
||||||
|
unmount();
|
||||||
|
await act(async () => answer(stats));
|
||||||
|
expect(result.current.data).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-HOOK-007: a write before the first read leaves the empty state empty', async () => {
|
||||||
|
repo.get.mockReturnValue(new Promise(() => undefined));
|
||||||
|
repo.setExcluded.mockRejectedValue(new Error('offline'));
|
||||||
|
const { result } = renderHook(() => useTourActivityStats(true));
|
||||||
|
await act(async () => {
|
||||||
|
await result.current.setExcluded(entry(), true);
|
||||||
|
});
|
||||||
|
expect(result.current.data).toBeNull();
|
||||||
|
expect(toast.error).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-HOOK-008: an older exclusion answered last never puts a newer one back', async () => {
|
||||||
|
const answers: Array<(value: TourActivityStatsResponse) => void> = [];
|
||||||
|
repo.setExcluded.mockImplementation(() => new Promise((resolve) => answers.push(resolve)));
|
||||||
|
const { result } = renderHook(() => useTourActivityStats(true));
|
||||||
|
await waitFor(() => expect(result.current.status).toBe('ready'));
|
||||||
|
const excludedOf = (placeId: number) =>
|
||||||
|
result.current.data?.entries.find((item) => item.place_id === placeId)?.excluded;
|
||||||
|
const withExcluded = (...ids: number[]) => ({
|
||||||
|
...stats,
|
||||||
|
entries: stats.entries.map((item) => ({ ...item, excluded: ids.includes(item.place_id) })),
|
||||||
|
});
|
||||||
|
|
||||||
|
let first: Promise<void> = Promise.resolve();
|
||||||
|
let second: Promise<void> = Promise.resolve();
|
||||||
|
act(() => {
|
||||||
|
first = result.current.setExcluded(entry(), true);
|
||||||
|
});
|
||||||
|
act(() => {
|
||||||
|
second = result.current.setExcluded(stats.entries[1] as TourActivityStatsEntry, true);
|
||||||
|
});
|
||||||
|
// The second answer comes first and carries both; the first, from before the second, only its own.
|
||||||
|
await act(async () => {
|
||||||
|
answers[1]?.(withExcluded(1, 2));
|
||||||
|
await second;
|
||||||
|
});
|
||||||
|
await act(async () => {
|
||||||
|
answers[0]?.(withExcluded(1));
|
||||||
|
await first;
|
||||||
|
});
|
||||||
|
expect(excludedOf(1)).toBe(true);
|
||||||
|
expect(excludedOf(2)).toBe(true);
|
||||||
|
|
||||||
|
// The other way round: the first comes first, without the second still on its way, which stays left out.
|
||||||
|
act(() => {
|
||||||
|
first = result.current.setExcluded(entry(), false);
|
||||||
|
});
|
||||||
|
act(() => {
|
||||||
|
second = result.current.setExcluded(stats.entries[1] as TourActivityStatsEntry, false);
|
||||||
|
});
|
||||||
|
await act(async () => {
|
||||||
|
answers[2]?.(withExcluded(2));
|
||||||
|
await first;
|
||||||
|
});
|
||||||
|
expect(excludedOf(1)).toBe(false);
|
||||||
|
expect(excludedOf(2)).toBe(false);
|
||||||
|
await act(async () => {
|
||||||
|
answers[3]?.(withExcluded());
|
||||||
|
await second;
|
||||||
|
});
|
||||||
|
expect(excludedOf(2)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STA2-HOOK-009: a read asked before an exclusion and answered after it does not undo it', async () => {
|
||||||
|
const { result } = renderHook(() => useTourActivityStats(true));
|
||||||
|
await waitFor(() => expect(result.current.status).toBe('ready'));
|
||||||
|
let read: (value: TourActivityStatsResponse) => void = () => undefined;
|
||||||
|
repo.get.mockReturnValue(new Promise((resolve) => (read = resolve)));
|
||||||
|
act(() => result.current.retry());
|
||||||
|
repo.setExcluded.mockResolvedValue({
|
||||||
|
...stats,
|
||||||
|
entries: stats.entries.map((item) => (item.place_id === 1 ? { ...item, excluded: true } : item)),
|
||||||
|
});
|
||||||
|
await act(async () => {
|
||||||
|
await result.current.setExcluded(entry(), true);
|
||||||
|
});
|
||||||
|
await act(async () => read(stats));
|
||||||
|
expect(result.current.status).toBe('ready');
|
||||||
|
expect(result.current.data?.entries.find((item) => item.place_id === 1)?.excluded).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
import {
|
||||||
|
summarizeTourActivities,
|
||||||
|
type TourActivityStatsEntry,
|
||||||
|
type TourActivityStatsResponse,
|
||||||
|
type TourActivitySummary,
|
||||||
|
} from '@trek/shared';
|
||||||
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
import { useTranslation } from '../../../i18n';
|
||||||
|
import { TourActivityStatsOfflineError, tourActivityStatsRepo } from '../../../repo/tourActivityStatsRepo';
|
||||||
|
import { localIsoDate } from '../../../utils/localDate';
|
||||||
|
import { useToast } from '../../shared/Toast';
|
||||||
|
import {
|
||||||
|
periodOptions,
|
||||||
|
periodRange,
|
||||||
|
typeOptions,
|
||||||
|
type ActivityPeriod,
|
||||||
|
type ActivityType,
|
||||||
|
} from './tourActivityStatsModel';
|
||||||
|
|
||||||
|
/** Where the read stands: not asked yet, on its way, there, refused offline, or failed. */
|
||||||
|
type ActivityStatsStatus = 'idle' | 'loading' | 'ready' | 'offline' | 'error';
|
||||||
|
|
||||||
|
export interface TourActivityStats {
|
||||||
|
status: ActivityStatsStatus;
|
||||||
|
data: TourActivityStatsResponse | null;
|
||||||
|
/** The sums of the chosen period and type; null until the first read is there. */
|
||||||
|
summary: TourActivitySummary | null;
|
||||||
|
period: ActivityPeriod;
|
||||||
|
setPeriod: (period: ActivityPeriod) => void;
|
||||||
|
periods: ActivityPeriod[];
|
||||||
|
type: ActivityType;
|
||||||
|
setType: (type: ActivityType) => void;
|
||||||
|
types: ActivityType[];
|
||||||
|
/** The tours whose exclusion is on its way to the server. */
|
||||||
|
pending: ReadonlySet<number>;
|
||||||
|
setExcluded: (entry: TourActivityStatsEntry, excluded: boolean) => Promise<void>;
|
||||||
|
retry: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the latest read came back with, and the attempt it answered. */
|
||||||
|
interface Answered {
|
||||||
|
attempt: number;
|
||||||
|
status: Exclude<ActivityStatsStatus, 'idle' | 'loading'>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every entry of the tour with the flag as asked, the rest as they were. */
|
||||||
|
function flagged(data: TourActivityStatsResponse, placeId: number, excluded: boolean): TourActivityStatsResponse {
|
||||||
|
return {
|
||||||
|
...data,
|
||||||
|
entries: data.entries.map((entry) => (entry.place_id === placeId ? { ...entry, excluded } : entry)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every entry with the flags of the exclusions still on their way laid over it, the way they show already. */
|
||||||
|
function withFlags(data: TourActivityStatsResponse, flags: ReadonlyMap<number, boolean>): TourActivityStatsResponse {
|
||||||
|
if (flags.size === 0) return data;
|
||||||
|
return {
|
||||||
|
...data,
|
||||||
|
entries: data.entries.map((entry) =>
|
||||||
|
flags.has(entry.place_id) ? { ...entry, excluded: flags.get(entry.place_id) === true } : entry
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* STA-02: the user's own tour activities in the Atlas. Read live when the tab
|
||||||
|
* is first shown (and again on retry), never cached on the device; narrowed by
|
||||||
|
* period and type here, summed by the shared summary the assistant uses too.
|
||||||
|
* Leaving a tour out shows at once and is undone with a message when the
|
||||||
|
* server refuses it; the plan of the tour never changes. Answers can come
|
||||||
|
* back in any order: only the answer to the latest read or write is taken
|
||||||
|
* whole, with the exclusions still on their way laid over it; an older one
|
||||||
|
* only confirms its own tour's flag, so it never puts back a state from
|
||||||
|
* before a newer change.
|
||||||
|
*/
|
||||||
|
export function useTourActivityStats(active: boolean): TourActivityStats {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const toast = useToast();
|
||||||
|
// The answer to the latest read and which attempt it answered: a retry is loading until its own answer is there.
|
||||||
|
const [answered, setAnswered] = useState<Answered | null>(null);
|
||||||
|
const [data, setData] = useState<TourActivityStatsResponse | null>(null);
|
||||||
|
const [period, setPeriod] = useState<ActivityPeriod>('all');
|
||||||
|
const [type, setType] = useState<ActivityType>('all');
|
||||||
|
const [pending, setPending] = useState<ReadonlySet<number>>(() => new Set());
|
||||||
|
const [attempt, setAttempt] = useState(0);
|
||||||
|
const today = localIsoDate();
|
||||||
|
// Raised by every read and every write, so an answer knows whether a newer request went out after it.
|
||||||
|
const latest = useRef(0);
|
||||||
|
// The exclusions on their way to the server, by tour: the flag the user asked for.
|
||||||
|
const inFlight = useRef(new Map<number, boolean>());
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!active) return;
|
||||||
|
const controller = new AbortController();
|
||||||
|
const asked = ++latest.current;
|
||||||
|
tourActivityStatsRepo.get(controller.signal).then(
|
||||||
|
(answer) => {
|
||||||
|
if (controller.signal.aborted) return;
|
||||||
|
if (asked === latest.current) setData(withFlags(answer, inFlight.current));
|
||||||
|
setAnswered({ attempt, status: 'ready' });
|
||||||
|
},
|
||||||
|
(err: unknown) => {
|
||||||
|
if (controller.signal.aborted) return;
|
||||||
|
setAnswered({ attempt, status: err instanceof TourActivityStatsOfflineError ? 'offline' : 'error' });
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return () => controller.abort();
|
||||||
|
}, [active, attempt]);
|
||||||
|
|
||||||
|
let status: ActivityStatsStatus = 'loading';
|
||||||
|
if (answered?.attempt === attempt) status = answered.status;
|
||||||
|
else if (!active && !answered) status = 'idle';
|
||||||
|
|
||||||
|
const summary = useMemo(() => {
|
||||||
|
if (!data) return null;
|
||||||
|
const range = periodRange(period, today);
|
||||||
|
return summarizeTourActivities(data.entries, { today, ...range, type: type === 'all' ? null : type });
|
||||||
|
}, [data, period, type, today]);
|
||||||
|
const periods = useMemo(() => periodOptions(data?.entries ?? [], today), [data, today]);
|
||||||
|
const types = useMemo(() => typeOptions(data?.entries ?? [], today), [data, today]);
|
||||||
|
|
||||||
|
const setExcluded = useCallback(
|
||||||
|
async (entry: TourActivityStatsEntry, excluded: boolean) => {
|
||||||
|
const placeId = entry.place_id;
|
||||||
|
const asked = ++latest.current;
|
||||||
|
inFlight.current.set(placeId, excluded);
|
||||||
|
setPending((current) => new Set(current).add(placeId));
|
||||||
|
setData((current) => (current ? flagged(current, placeId, excluded) : current));
|
||||||
|
try {
|
||||||
|
const answer = await tourActivityStatsRepo.setExcluded({ place_id: placeId, excluded });
|
||||||
|
inFlight.current.delete(placeId);
|
||||||
|
if (asked === latest.current) setData(withFlags(answer, inFlight.current));
|
||||||
|
else setData((current) => (current ? flagged(current, placeId, excluded) : current));
|
||||||
|
} catch {
|
||||||
|
inFlight.current.delete(placeId);
|
||||||
|
setData((current) => (current ? flagged(current, placeId, !excluded) : current));
|
||||||
|
toast.error(t('tours.stats.excludeFailed'));
|
||||||
|
} finally {
|
||||||
|
setPending((current) => {
|
||||||
|
const next = new Set(current);
|
||||||
|
next.delete(placeId);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[t, toast]
|
||||||
|
);
|
||||||
|
|
||||||
|
const retry = useCallback(() => setAttempt((count) => count + 1), []);
|
||||||
|
|
||||||
|
return {
|
||||||
|
status,
|
||||||
|
data,
|
||||||
|
summary,
|
||||||
|
period,
|
||||||
|
setPeriod,
|
||||||
|
periods,
|
||||||
|
type,
|
||||||
|
setType,
|
||||||
|
types,
|
||||||
|
pending,
|
||||||
|
setExcluded,
|
||||||
|
retry,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
// FE-COMP-BELL-001 to FE-COMP-BELL-020
|
// FE-COMP-BELL-001 to FE-COMP-BELL-021
|
||||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||||
import userEvent from '@testing-library/user-event';
|
import userEvent from '@testing-library/user-event';
|
||||||
import { vi } from 'vitest';
|
import { vi } from 'vitest';
|
||||||
@@ -238,4 +238,13 @@ describe('InAppNotificationBell', () => {
|
|||||||
// fetchNotifications should be called once per open (2 total)
|
// fetchNotifications should be called once per open (2 total)
|
||||||
expect(fetchNotifications).toHaveBeenCalledTimes(2);
|
expect(fetchNotifications).toHaveBeenCalledTimes(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('FE-COMP-BELL-021: unread badge is large enough that the count is not squeezed', () => {
|
||||||
|
seedStore(useInAppNotificationStore, { notifications: [], unreadCount: 150, isLoading: false });
|
||||||
|
render(<InAppNotificationBell />);
|
||||||
|
const badge = screen.getByTestId('notification-badge');
|
||||||
|
expect(badge).toHaveTextContent('99+');
|
||||||
|
expect(badge.style.height).toBe('20px');
|
||||||
|
expect(badge.style.minWidth).toBe('20px');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -52,13 +52,14 @@ export default function InAppNotificationBell(): React.ReactElement {
|
|||||||
<Bell className="w-4 h-4" />
|
<Bell className="w-4 h-4" />
|
||||||
{unreadCount > 0 && (
|
{unreadCount > 0 && (
|
||||||
<span
|
<span
|
||||||
className="absolute -top-0.5 -end-0.5 flex items-center justify-center rounded-full text-white font-bold"
|
data-testid="notification-badge"
|
||||||
|
className="absolute -top-1.5 -end-1.5 flex items-center justify-center rounded-full text-white font-bold tabular-nums ring-2 ring-surface-card"
|
||||||
style={{
|
style={{
|
||||||
background: '#ef4444',
|
background: '#ef4444',
|
||||||
fontSize: 'calc(9px * var(--fs-scale-caption, 1))',
|
fontSize: 'calc(10.5px * var(--fs-scale-caption, 1))',
|
||||||
minWidth: 14,
|
minWidth: 20,
|
||||||
height: 14,
|
height: 20,
|
||||||
padding: '0 3px',
|
padding: '0 5px',
|
||||||
lineHeight: 1,
|
lineHeight: 1,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
// FE-COMP-MAPLAYER-001 to FE-COMP-MAPLAYER-020
|
// FE-COMP-MAPLAYER-001 to FE-COMP-MAPLAYER-024
|
||||||
import React from 'react'
|
import React from 'react'
|
||||||
import { describe, it, expect, vi } from 'vitest'
|
import { describe, it, expect, vi } from 'vitest'
|
||||||
import { render, screen, fireEvent } from '../../../tests/helpers/render'
|
import { render, screen, fireEvent } from '../../../tests/helpers/render'
|
||||||
import { MapLayerSwitcher, TourMapLayerSwitcher, MAP_ROUND_CONTROL_SIZE } from './MapLayerSwitcher'
|
import { MapLayerSwitcher, TourMapLayerSwitcher, MAP_ROUND_CONTROL_SIZE } from './MapLayerSwitcher'
|
||||||
import type { FerrataMapLayer } from '../Ferratas/useFerrataMapLayer'
|
import type { FerrataMapLayer } from '../Ferratas/useFerrataMapLayer'
|
||||||
|
import type { ToggleableRasterOverlay } from './mapRasterOverlay'
|
||||||
|
|
||||||
describe('MapLayerSwitcher', () => {
|
describe('MapLayerSwitcher', () => {
|
||||||
it('FE-COMP-MAPLAYER-001: on the default layer, offers the switch to satellite', () => {
|
it('FE-COMP-MAPLAYER-001: on the default layer, offers the switch to satellite', () => {
|
||||||
@@ -235,3 +236,79 @@ describe('TourMapLayerSwitcher via ferrata switch', () => {
|
|||||||
expect(screen.getByRole('button', { name: 'Set points' })).toHaveClass('text-content-muted')
|
expect(screen.getByRole('button', { name: 'Set points' })).toHaveClass('text-content-muted')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const pisteOverlay = (overrides: Partial<ToggleableRasterOverlay> = {}): ToggleableRasterOverlay => ({
|
||||||
|
id: 'pistes',
|
||||||
|
url: 'https://tiles.opensnowmap.org/pistes/{z}/{x}/{y}.png',
|
||||||
|
attribution: 'OpenSnowMap',
|
||||||
|
minZoom: 9,
|
||||||
|
maxZoom: 18,
|
||||||
|
active: false,
|
||||||
|
status: 'off',
|
||||||
|
belowMinZoom: false,
|
||||||
|
onToggle: vi.fn(),
|
||||||
|
onTileError: vi.fn(),
|
||||||
|
onTileLoad: vi.fn(),
|
||||||
|
...overrides,
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('TourMapLayerSwitcher piste switch (SKI-01)', () => {
|
||||||
|
it('FE-COMP-MAPLAYER-021: the pistes switch sits on its icon alone, named by its tooltip, and offers no key while off', async () => {
|
||||||
|
const overlay = pisteOverlay()
|
||||||
|
render(<TourMapLayerSwitcher active="default" onChange={() => {}} ferrataLayer={ferrataLayer()} layers={{ overlays: [overlay] }} />)
|
||||||
|
const toggle = screen.getByRole('button', { name: 'Pistes, cross-country trails and lifts' })
|
||||||
|
expect(toggle).toHaveAttribute('aria-pressed', 'false')
|
||||||
|
expect(toggle.textContent).toBe('')
|
||||||
|
expect(screen.queryByTestId('piste-key-button')).toBeNull()
|
||||||
|
fireEvent.click(toggle)
|
||||||
|
expect(overlay.onToggle).toHaveBeenCalledTimes(1)
|
||||||
|
fireEvent.mouseEnter(toggle)
|
||||||
|
expect(await screen.findByRole('tooltip')).toHaveTextContent('Pistes, cross-country trails and lifts')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('FE-COMP-MAPLAYER-022: on, the switch is pressed in the accent and the key rides beside it in the same pill', () => {
|
||||||
|
render(<TourMapLayerSwitcher active="default" onChange={() => {}} layers={{ overlays: [pisteOverlay({ active: true, status: 'on' })] }} />)
|
||||||
|
const toggle = screen.getByRole('button', { name: 'Pistes, cross-country trails and lifts' })
|
||||||
|
expect(toggle).toHaveAttribute('aria-pressed', 'true')
|
||||||
|
expect(toggle).toHaveClass('bg-accent', 'text-accent-text')
|
||||||
|
const key = screen.getByTestId('piste-key-button')
|
||||||
|
expect(screen.getByRole('group')).toContainElement(key)
|
||||||
|
expect(key).toHaveAccessibleName('Piste key')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('FE-COMP-MAPLAYER-023: a piste source that stopped answering shows the warning badge, says so, and hides the key', async () => {
|
||||||
|
render(<TourMapLayerSwitcher active="default" onChange={() => {}} layers={{ overlays: [pisteOverlay({ active: true, status: 'down' })] }} />)
|
||||||
|
const toggle = screen.getByRole('button', { name: 'Pistes, cross-country trails and lifts' })
|
||||||
|
expect(toggle).toHaveAttribute('data-status', 'down')
|
||||||
|
expect(toggle).toHaveTextContent('!')
|
||||||
|
expect(screen.queryByTestId('piste-key-button')).toBeNull()
|
||||||
|
expect(screen.getByRole('status')).toHaveTextContent('Pistes are not loading. The map and your route still work.')
|
||||||
|
fireEvent.mouseEnter(toggle)
|
||||||
|
expect(await screen.findByRole('tooltip')).toHaveTextContent('Pistes are not loading.')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('FE-COMP-MAPLAYER-024: on further out than the pistes reach, the switch stays pressed in the soft accent and says to zoom in', async () => {
|
||||||
|
const { rerender } = render(
|
||||||
|
<TourMapLayerSwitcher active="default" onChange={() => {}} layers={{ overlays: [pisteOverlay({ active: true, status: 'on', belowMinZoom: true })] }} />
|
||||||
|
)
|
||||||
|
const toggle = screen.getByRole('button', { name: 'Pistes, cross-country trails and lifts' })
|
||||||
|
expect(toggle).toHaveAttribute('aria-pressed', 'true')
|
||||||
|
expect(toggle).toHaveAttribute('data-below-min-zoom', 'true')
|
||||||
|
expect(toggle).toHaveClass('bg-accent-soft', 'text-accent')
|
||||||
|
expect(screen.getByRole('status')).toHaveTextContent('Zoom in to see the pistes')
|
||||||
|
fireEvent.mouseEnter(toggle)
|
||||||
|
expect(await screen.findByRole('tooltip')).toHaveTextContent('Zoom in to see the pistes')
|
||||||
|
// The key stays at hand and opens with the same line on top.
|
||||||
|
fireEvent.click(screen.getByTestId('piste-key-button'))
|
||||||
|
expect(await screen.findByTestId('piste-key-zoom-in')).toHaveTextContent('Zoom in to see the pistes')
|
||||||
|
|
||||||
|
// A source that stopped answering says so instead, and close enough the switch is plainly on.
|
||||||
|
rerender(<TourMapLayerSwitcher active="default" onChange={() => {}} layers={{ overlays: [pisteOverlay({ active: true, status: 'down', belowMinZoom: true })] }} />)
|
||||||
|
expect(screen.getByRole('status')).toHaveTextContent('Pistes are not loading.')
|
||||||
|
rerender(<TourMapLayerSwitcher active="default" onChange={() => {}} layers={{ overlays: [pisteOverlay({ active: true, status: 'on' })] }} />)
|
||||||
|
const plain = screen.getByRole('button', { name: 'Pistes, cross-country trails and lifts' })
|
||||||
|
expect(plain).not.toHaveAttribute('data-below-min-zoom')
|
||||||
|
expect(plain).toHaveClass('bg-accent', 'text-accent-text')
|
||||||
|
expect(screen.getByRole('status')).toHaveTextContent('')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Anchor, Bike, Footprints, Loader2, Map as MapIcon, MapPinPlus, Mountain, Rotate3d, Satellite } from 'lucide-react'
|
import { Anchor, Bike, Footprints, Loader2, Map as MapIcon, MapPinPlus, Mountain, MountainSnow, Rotate3d, Satellite } from 'lucide-react'
|
||||||
import type { PaddleMapLayer } from '../Tours/paddle/paddleMapLayer'
|
import type { PaddleMapLayer } from '../Tours/paddle/paddleMapLayer'
|
||||||
import type { CSSProperties } from 'react'
|
import { PisteKeyButton } from '../Tours/winter/PisteKey'
|
||||||
|
import type { ComponentType, CSSProperties } from 'react'
|
||||||
import { useTranslation } from '../../i18n'
|
import { useTranslation } from '../../i18n'
|
||||||
import { FerrataLineIcon } from '../Ferratas/FerrataGlyph'
|
import { FerrataLineIcon } from '../Ferratas/FerrataGlyph'
|
||||||
import type { FerrataMapLayer } from '../Ferratas/useFerrataMapLayer'
|
import type { FerrataMapLayer } from '../Ferratas/useFerrataMapLayer'
|
||||||
@@ -193,17 +194,32 @@ function PlaceToolToggle({ tool }: { tool: MapPlaceTool }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** How each overlay the planner can offer is named and drawn on its switch. */
|
/** How an overlay the planner can offer is named and drawn on its switch. */
|
||||||
const OVERLAY_LOOK: Record<string, { Icon: typeof Anchor; labelKey: string; downKey: string }> = {
|
interface OverlayLook {
|
||||||
seamarks: { Icon: Anchor, labelKey: 'tours.map.seamarks', downKey: 'tours.map.seamarksDown' },
|
Icon: typeof Anchor
|
||||||
|
labelKey: string
|
||||||
|
downKey: string
|
||||||
|
/** On its icon alone, named by its tooltip, so the row stays short beside a type's other switches. */
|
||||||
|
iconOnly?: boolean
|
||||||
|
/** What the switch says while the map is further out than the overlay's first tiles. */
|
||||||
|
zoomInKey?: string
|
||||||
|
/** The overlay's key, beside its switch while the layer is on; told when nothing of it is drawn yet. */
|
||||||
|
Key?: ComponentType<{ belowMinZoom: boolean }>
|
||||||
|
}
|
||||||
|
|
||||||
|
const OVERLAY_LOOK: Record<string, OverlayLook> = {
|
||||||
|
seamarks: { Icon: Anchor, labelKey: 'tours.map.seamarks', downKey: 'tours.map.seamarksDown' },
|
||||||
|
// SKI-01: the row already holds the maps and 3D, so the pistes go by their icon.
|
||||||
|
pistes: {
|
||||||
|
Icon: MountainSnow,
|
||||||
|
labelKey: 'tours.map.pistes',
|
||||||
|
downKey: 'tours.map.pistesDown',
|
||||||
|
zoomInKey: 'tours.map.pistesZoomIn',
|
||||||
|
iconOnly: true,
|
||||||
|
Key: PisteKeyButton,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* The switch for a transparent overlay (the seamarks), the way the via
|
|
||||||
* ferrata switch looks: on in the accent, and in the warning tone with a badge
|
|
||||||
* once its source stopped answering, which the tooltip names. The map and the
|
|
||||||
* planning go on without it.
|
|
||||||
*/
|
|
||||||
/** The warning mark on a switch whose source stopped answering; the tooltip says what it means. */
|
/** The warning mark on a switch whose source stopped answering; the tooltip says what it means. */
|
||||||
function DownBadge() {
|
function DownBadge() {
|
||||||
return (
|
return (
|
||||||
@@ -213,6 +229,15 @@ function DownBadge() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The switch for a transparent overlay (the seamarks, the pistes), the way the via
|
||||||
|
* ferrata switch looks: on in the accent, and in the warning tone with a badge
|
||||||
|
* once its source stopped answering, which the tooltip names. The map and the
|
||||||
|
* planning go on without it. Switched on further out than its first tiles, it
|
||||||
|
* stays pressed in the soft accent and its tooltip says to zoom in, so an empty
|
||||||
|
* map does not read as broken. An overlay with a key shows the key's button
|
||||||
|
* beside the switch while it is on and answering.
|
||||||
|
*/
|
||||||
function OverlayToggle({ overlay, compact }: { overlay: ToggleableRasterOverlay; compact: boolean }) {
|
function OverlayToggle({ overlay, compact }: { overlay: ToggleableRasterOverlay; compact: boolean }) {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation()
|
||||||
const look = OVERLAY_LOOK[overlay.id]
|
const look = OVERLAY_LOOK[overlay.id]
|
||||||
@@ -220,9 +245,12 @@ function OverlayToggle({ overlay, compact }: { overlay: ToggleableRasterOverlay;
|
|||||||
const label = t(look.labelKey)
|
const label = t(look.labelKey)
|
||||||
const down = overlay.status === 'down'
|
const down = overlay.status === 'down'
|
||||||
const on = overlay.status !== 'off'
|
const on = overlay.status !== 'off'
|
||||||
|
const zoomIn = !down && overlay.belowMinZoom && look.zoomInKey ? t(look.zoomInKey) : null
|
||||||
|
const notice = down ? t(look.downKey) : zoomIn
|
||||||
|
const tone = zoomIn ? 'bg-accent-soft text-accent' : 'bg-accent text-accent-text'
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Tooltip label={down ? t(look.downKey) : label} placement="top">
|
<Tooltip label={notice ?? label} placement="top">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={overlay.onToggle}
|
onClick={overlay.onToggle}
|
||||||
@@ -230,15 +258,17 @@ function OverlayToggle({ overlay, compact }: { overlay: ToggleableRasterOverlay;
|
|||||||
aria-pressed={on}
|
aria-pressed={on}
|
||||||
data-testid={`map-overlay-${overlay.id}`}
|
data-testid={`map-overlay-${overlay.id}`}
|
||||||
data-status={overlay.status}
|
data-status={overlay.status}
|
||||||
className={on ? 'bg-accent text-accent-text' : 'text-content-muted'}
|
data-below-min-zoom={zoomIn ? true : undefined}
|
||||||
|
className={on ? tone : 'text-content-muted'}
|
||||||
style={segmentStyle(on)}
|
style={segmentStyle(on)}
|
||||||
>
|
>
|
||||||
<look.Icon size={15} strokeWidth={2} />
|
<look.Icon size={15} strokeWidth={2} />
|
||||||
{!compact && <span>{label}</span>}
|
{!compact && !look.iconOnly && <span>{label}</span>}
|
||||||
{down && <DownBadge />}
|
{down && <DownBadge />}
|
||||||
</button>
|
</button>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
<span role="status" aria-live="polite" className="sr-only">{down ? t(look.downKey) : ''}</span>
|
{look.Key && overlay.status === 'on' && <look.Key belowMinZoom={!!zoomIn} />}
|
||||||
|
<span role="status" aria-live="polite" className="sr-only">{notice ?? ''}</span>
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1141,10 +1141,11 @@ describe('MapView plugin route vias', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe('MapView map event wiring', () => {
|
describe('MapView map event wiring', () => {
|
||||||
it('FE-COMP-MAPVIEW-043: reports the viewport bbox once the map is ready and again on every move', () => {
|
it('FE-COMP-MAPVIEW-043: reports the viewport bbox and its zoom once the map is ready and again on every move', () => {
|
||||||
const onViewportChange = vi.fn()
|
const onViewportChange = vi.fn()
|
||||||
|
mapMock.getZoom.mockReturnValue(10)
|
||||||
render(<MapView onViewportChange={onViewportChange} />)
|
render(<MapView onViewportChange={onViewportChange} />)
|
||||||
expect(onViewportChange).toHaveBeenCalledWith({ south: 47, west: 1, north: 49, east: 3 })
|
expect(onViewportChange).toHaveBeenCalledWith({ south: 47, west: 1, north: 49, east: 3 }, 10)
|
||||||
|
|
||||||
const moveend = handlerFor('moveend')
|
const moveend = handlerFor('moveend')
|
||||||
const zoomend = handlerFor('zoomend')
|
const zoomend = handlerFor('zoomend')
|
||||||
|
|||||||
@@ -340,14 +340,14 @@ function PoiDropTarget({ onPoiDropOnRoute }: { onPoiDropOnRoute?: (osmId: string
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Emits the current viewport bbox on pan/zoom so the POI-explore pill can fetch
|
// Emits the current viewport bbox on pan/zoom so the POI-explore pill can fetch
|
||||||
// OSM places for the visible area.
|
// OSM places for the visible area, with the zoom an overlay's minimum is read against.
|
||||||
function ViewportController({ onViewportChange }: { onViewportChange?: (b: { south: number; west: number; north: number; east: number }) => void }) {
|
function ViewportController({ onViewportChange }: { onViewportChange?: MapViewProps['onViewportChange'] }) {
|
||||||
const map = useMap()
|
const map = useMap()
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!onViewportChange) return
|
if (!onViewportChange) return
|
||||||
const emit = () => {
|
const emit = () => {
|
||||||
const b = map.getBounds()
|
const b = map.getBounds()
|
||||||
onViewportChange({ south: b.getSouth(), west: b.getWest(), north: b.getNorth(), east: b.getEast() })
|
onViewportChange({ south: b.getSouth(), west: b.getWest(), north: b.getNorth(), east: b.getEast() }, map.getZoom())
|
||||||
}
|
}
|
||||||
map.whenReady(emit) // ensure the first bbox is captured once the map is laid out
|
map.whenReady(emit) // ensure the first bbox is captured once the map is laid out
|
||||||
map.on('moveend', emit)
|
map.on('moveend', emit)
|
||||||
|
|||||||
@@ -257,6 +257,7 @@ beforeEach(() => {
|
|||||||
glMap.querySourceFeatures.mockReturnValue([])
|
glMap.querySourceFeatures.mockReturnValue([])
|
||||||
glMap.getCanvas.mockImplementation(() => document.createElement('canvas'))
|
glMap.getCanvas.mockImplementation(() => document.createElement('canvas'))
|
||||||
glMap.getBearing.mockReturnValue(0)
|
glMap.getBearing.mockReturnValue(0)
|
||||||
|
glMap.getZoom.mockReturnValue(10)
|
||||||
glMap.queryTerrainElevation.mockReturnValue(null)
|
glMap.queryTerrainElevation.mockReturnValue(null)
|
||||||
// A busy style, a refused source and a custom layer list are each set by one test
|
// A busy style, a refused source and a custom layer list are each set by one test
|
||||||
// for the case it covers. Put back here, or every test after it would silently run
|
// for the case it covers. Put back here, or every test after it would silently run
|
||||||
@@ -1575,7 +1576,6 @@ describe('MapViewGL', () => {
|
|||||||
const list = calls[calls.length - 1][0]
|
const list = calls[calls.length - 1][0]
|
||||||
act(() => { list.querySelectorAll('button')[1].click() })
|
act(() => { list.querySelectorAll('button')[1].click() })
|
||||||
expect(onPoiClick).toHaveBeenCalledWith(other)
|
expect(onPoiClick).toHaveBeenCalledWith(other)
|
||||||
vi.mocked(glMap.getZoom).mockReturnValue(10)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const pinGlyph = (Icon: LucideIcon) => renderIconMarkup(React.createElement(Icon, { size: 13, color: 'white', strokeWidth: 2.5 }))
|
const pinGlyph = (Icon: LucideIcon) => renderIconMarkup(React.createElement(Icon, { size: 13, color: 'white', strokeWidth: 2.5 }))
|
||||||
@@ -2215,13 +2215,13 @@ describe('MapViewGL', () => {
|
|||||||
expect((window as any).__trek_map).toBeUndefined()
|
expect((window as any).__trek_map).toBeUndefined()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('FE-COMP-MAPVIEWGL-059: pan and zoom report the visible bbox for the POI explore pill', async () => {
|
it('FE-COMP-MAPVIEWGL-059: pan and zoom report the visible bbox and tile zoom for the POI explore pill', async () => {
|
||||||
const onViewportChange = vi.fn()
|
const onViewportChange = vi.fn()
|
||||||
render(<MapViewGL places={[]} fitKey={1} onViewportChange={onViewportChange} />)
|
render(<MapViewGL places={[]} fitKey={1} onViewportChange={onViewportChange} />)
|
||||||
await act(async () => {})
|
await act(async () => {})
|
||||||
|
|
||||||
act(() => { mapHandler('moveend')() })
|
act(() => { mapHandler('moveend')() })
|
||||||
expect(onViewportChange).toHaveBeenCalledWith({ south: 0, west: 0, north: 1, east: 1 })
|
expect(onViewportChange).toHaveBeenCalledWith({ south: 0, west: 0, north: 1, east: 1 }, 11)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('FE-COMP-MAPVIEWGL-060: a new POI or via set replaces the previous overlay markers', async () => {
|
it('FE-COMP-MAPVIEWGL-060: a new POI or via set replaces the previous overlay markers', async () => {
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import type mapboxgl from 'mapbox-gl'
|
|||||||
import { useSettingsStore } from '../../store/settingsStore'
|
import { useSettingsStore } from '../../store/settingsStore'
|
||||||
import { useTranslation } from '../../i18n/TranslationContext'
|
import { useTranslation } from '../../i18n/TranslationContext'
|
||||||
import { applyBaseLayer } from './glRasterLayers'
|
import { applyBaseLayer } from './glRasterLayers'
|
||||||
|
import { reportGlViewport } from './glViewport'
|
||||||
import { isTourLayerHit, useTourMapLayersGL } from './mapRasterOverlay'
|
import { isTourLayerHit, useTourMapLayersGL } from './mapRasterOverlay'
|
||||||
import { MapLayerSwitcher, TourMapLayerSwitcher, MAP_LAYER_SWITCHER_INSET, type BaseLayer, type TourBaseLayer } from './MapLayerSwitcher'
|
import { MapLayerSwitcher, TourMapLayerSwitcher, MAP_LAYER_SWITCHER_INSET, type BaseLayer, type TourBaseLayer } from './MapLayerSwitcher'
|
||||||
import { MapLockPill } from './MapLockPill'
|
import { MapLockPill } from './MapLockPill'
|
||||||
@@ -1432,12 +1433,8 @@ export function MapViewGL({
|
|||||||
if (isTourLayerHit(map, e.point)) return // a picked via ferrata or paddle obstacle opens its card instead
|
if (isTourLayerHit(map, e.point)) return // a picked via ferrata or paddle obstacle opens its card instead
|
||||||
onClickRefs.current.map?.({ latlng: { lat: e.lngLat.lat, lng: e.lngLat.lng } })
|
onClickRefs.current.map?.({ latlng: { lat: e.lngLat.lat, lng: e.lngLat.lng } })
|
||||||
})
|
})
|
||||||
// Emit the viewport bbox (pan/zoom + once on first idle) so the POI-explore
|
// Emit the viewport (pan/zoom + once on first idle) for the POI-explore pill.
|
||||||
// pill can fetch OSM places for the visible area.
|
const emitViewport = () => reportGlViewport(map, onViewportChangeRef.current)
|
||||||
const emitViewport = () => {
|
|
||||||
const b = map.getBounds()
|
|
||||||
onViewportChangeRef.current?.({ south: b.getSouth(), west: b.getWest(), north: b.getNorth(), east: b.getEast() })
|
|
||||||
}
|
|
||||||
map.on('moveend', emitViewport)
|
map.on('moveend', emitViewport)
|
||||||
map.once('idle', emitViewport)
|
map.once('idle', emitViewport)
|
||||||
// Clear the hover card (and the anchored POI popup) as soon as the camera
|
// Clear the hover card (and the anchored POI popup) as soon as the camera
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import L from 'leaflet';
|
|||||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { Marker, Tooltip, useMap } from 'react-leaflet';
|
import { Marker, Tooltip, useMap } from 'react-leaflet';
|
||||||
import { MAP_LABEL_BADGE_CLASS } from './mapHoverLabel';
|
import { MAP_LABEL_BADGE_CLASS } from './mapHoverLabel';
|
||||||
import { plannerPinShape, type PlannerPinPoint } from './plannerPinShape';
|
import { plannerPinBadge, plannerPinShape, type PlannerPinPoint } from './plannerPinShape';
|
||||||
import { wirePlannerWaypointDrag } from './plannerWaypointDrag';
|
import { wirePlannerWaypointDrag } from './plannerWaypointDrag';
|
||||||
|
|
||||||
/** The pin's inline style for a size and selection; the renderer owns the colour. */
|
/** The pin's inline style for a size and selection; the renderer owns the colour. */
|
||||||
@@ -20,7 +20,7 @@ function plannerWaypointIcon(
|
|||||||
className: 'tour-planner-waypoint-marker',
|
className: 'tour-planner-waypoint-marker',
|
||||||
iconSize: [size, size],
|
iconSize: [size, size],
|
||||||
iconAnchor: [size / 2, size / 2],
|
iconAnchor: [size / 2, size / 2],
|
||||||
html: `<span style="${pinCss(size, selected)};cursor:${draggable ? 'grab' : 'pointer'};touch-action:${draggable ? 'none' : 'auto'};user-select:none">${text}</span>`,
|
html: `<span style="${pinCss(size, selected)};cursor:${draggable ? 'grab' : 'pointer'};touch-action:${draggable ? 'none' : 'auto'};user-select:none">${text}</span>${plannerPinBadge(point)}`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,10 +46,10 @@ export default function PlannerWaypointMarker({
|
|||||||
handlersRef.current = { onClick, onMove };
|
handlersRef.current = { onClick, onMove };
|
||||||
}, [onClick, onMove]);
|
}, [onClick, onMove]);
|
||||||
const position = useMemo(() => [point.lat, point.lng] as [number, number], [point.lat, point.lng]);
|
const position = useMemo(() => [point.lat, point.lng] as [number, number], [point.lat, point.lng]);
|
||||||
const { label, shaping } = point;
|
const { label, shaping, stageEnd } = point;
|
||||||
const icon = useMemo(
|
const icon = useMemo(
|
||||||
() => plannerWaypointIcon(pinCss, { label, shaping }, index, selected, !!onMove),
|
() => plannerWaypointIcon(pinCss, { label, shaping, stageEnd }, index, selected, !!onMove),
|
||||||
[index, label, onMove, pinCss, selected, shaping]
|
[index, label, onMove, pinCss, selected, shaping, stageEnd]
|
||||||
);
|
);
|
||||||
const eventHandlers = useMemo(
|
const eventHandlers = useMemo(
|
||||||
() => ({
|
() => ({
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ function RasterOverlaysLeaflet({ overlays }: { overlays?: readonly MapRasterOver
|
|||||||
maxNativeZoom={overlay.maxZoom}
|
maxNativeZoom={overlay.maxZoom}
|
||||||
maxZoom={22}
|
maxZoom={22}
|
||||||
zIndex={OVERLAY_Z_INDEX}
|
zIndex={OVERLAY_Z_INDEX}
|
||||||
|
// The page's origin as the referer, which the overlays' operators ask for (OpenSnowMap names it).
|
||||||
|
referrerPolicy="strict-origin-when-cross-origin"
|
||||||
eventHandlers={{ tileerror: overlay.onTileError, tileload: overlay.onTileLoad }}
|
eventHandlers={{ tileerror: overlay.onTileError, tileload: overlay.onTileLoad }}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { describe, it, expect } from 'vitest'
|
import { describe, it, expect } from 'vitest'
|
||||||
import { buildDayRouteRuns, hotelBookendOf } from './dayRoutePlan'
|
import { buildDayRouteRuns, hotelBookendOf } from './dayRoutePlan'
|
||||||
import { projectDayItinerary } from './dayTourProjection'
|
import { projectDayItinerary, tourStageStopsByPlace } from './dayTourProjection'
|
||||||
import { resolveLegMode } from '../Planner/legMode'
|
import { resolveLegMode } from '../Planner/legMode'
|
||||||
import { planTripRoute, assembleTripRoute, emptyAnswers, summariseTripRoute } from './tripRouteGeometry'
|
import { planTripRoute, assembleTripRoute, emptyAnswers, summariseTripRoute } from './tripRouteGeometry'
|
||||||
import { buildAssignment, buildDay, buildPlace, buildReservation } from '../../../tests/helpers/factories'
|
import { buildAssignment, buildDay, buildPlace, buildReservation } from '../../../tests/helpers/factories'
|
||||||
@@ -437,6 +437,54 @@ describe('Tour day itinerary segments', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// MDT-02: a day holding one stage of a multi-day tour routes to that stage and draws its stretch.
|
||||||
|
describe('A stage of a multi-day tour on a day', () => {
|
||||||
|
const line: [number, number][] = [[48, 11], [48.01, 11], [48.02, 11], [48.03, 11], [48.04, 11]]
|
||||||
|
const stops = [
|
||||||
|
{ key: 'stop-start', lat: 48, lng: 11 },
|
||||||
|
{ key: 'stop-hut', lat: 48.02, lng: 11 },
|
||||||
|
{ key: 'stop-end', lat: 48.04, lng: 11 },
|
||||||
|
]
|
||||||
|
const hutToHut = (order: number, tour_stage_key: string | null) => {
|
||||||
|
const assignment = at(48, 11, order)
|
||||||
|
return { ...assignment, tour_place_id: assignment.place.id, tour_route_geometry: JSON.stringify(line), tour_stage_key }
|
||||||
|
}
|
||||||
|
|
||||||
|
it('FE-MAP-DRP-017: draws and routes to the stretch of the stage, the stops telling where it runs', () => {
|
||||||
|
const second = hutToHut(1, 'stop-hut')
|
||||||
|
const stageStops = new Map([[second.place.id, stops]])
|
||||||
|
expect(projectDayItinerary([second], true, [], stageStops)[0]).toMatchObject({
|
||||||
|
kind: 'tour', valid: true, start: { lat: 48.02, lng: 11 }, end: { lat: 48.04, lng: 11 }, geometry: line.slice(2),
|
||||||
|
})
|
||||||
|
const first = hutToHut(1, 'stop-start')
|
||||||
|
expect(projectDayItinerary([first], true, [], new Map([[first.place.id, stops]]))[0]).toMatchObject({
|
||||||
|
start: { lat: 48, lng: 11 }, end: { lat: 48.02, lng: 11 },
|
||||||
|
})
|
||||||
|
const runs = buildDayRouteRuns(1, {
|
||||||
|
...inputs({ assignments: { '1': [at(47.99, 11, 0), second, at(48.05, 11, 2)] } }),
|
||||||
|
toursEnabled: true, tourStageStops: stageStops,
|
||||||
|
})
|
||||||
|
expect(runs.map(run => run.map(point => [point.lat, point.lng]))).toEqual([[[47.99, 11], [48.02, 11]], [[48.04, 11], [48.05, 11]]])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('FE-MAP-DRP-018: keeps the whole tour where the stops do not tell the stage', () => {
|
||||||
|
const whole = hutToHut(1, null)
|
||||||
|
const unknown = hutToHut(1, 'stop-gone')
|
||||||
|
const last = hutToHut(1, 'stop-end')
|
||||||
|
for (const assignment of [whole, unknown, last]) {
|
||||||
|
expect(projectDayItinerary([assignment], true, [], new Map([[assignment.place.id, stops]]))[0]).toMatchObject({ geometry: line })
|
||||||
|
}
|
||||||
|
const noStops = hutToHut(1, 'stop-hut')
|
||||||
|
expect(projectDayItinerary([noStops], true)[0]).toMatchObject({ geometry: line })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('FE-MAP-DRP-019: reads the stage stops of the multi-day tours off the tour list, none for a day tour', () => {
|
||||||
|
const stages = tourStageStopsByPlace([{ place_id: 4, stage_stops: stops }, { place_id: 5, stage_stops: null }, { place_id: 6 }])
|
||||||
|
expect([...stages.keys()]).toEqual([4])
|
||||||
|
expect(stages.get(4)).toBe(stops)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
// #2600: an imported GPX/KML place sits at its track's first point, so routing it as a
|
// #2600: an imported GPX/KML place sits at its track's first point, so routing it as a
|
||||||
// plain stop drew a second road from the track start to the next stop, alongside the
|
// plain stop drew a second road from the track start to the next stop, alongside the
|
||||||
// track itself. Any assigned place with a track now leaves that stretch to the track.
|
// track itself. Any assigned place with a track now leaves that stretch to the track.
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { getTransportRouteEndpoints, getTransportForDay, getMergedItems, isCarri
|
|||||||
import { getDayBookendHotels, shouldDrawMorningLeg, shouldDrawEveningLeg, type CarrierEdge } from '../../utils/dayOrder'
|
import { getDayBookendHotels, shouldDrawMorningLeg, shouldDrawEveningLeg, type CarrierEdge } from '../../utils/dayOrder'
|
||||||
import { withinDriveRange } from '@trek/shared/roadtrip'
|
import { withinDriveRange } from '@trek/shared/roadtrip'
|
||||||
import type { Accommodation, AssignmentsMap, Day, Place, Reservation } from '../../types'
|
import type { Accommodation, AssignmentsMap, Day, Place, Reservation } from '../../types'
|
||||||
import { projectDayItinerary } from './dayTourProjection'
|
import { projectedById, type TourStageStops } from './dayTourProjection'
|
||||||
|
|
||||||
export const TRANSPORT_TYPES = ['flight', 'train', 'bus', 'car', 'taxi', 'bicycle', 'cruise', 'ferry', 'cable_car', 'transit', 'transport_other']
|
export const TRANSPORT_TYPES = ['flight', 'train', 'bus', 'car', 'taxi', 'bicycle', 'cruise', 'ferry', 'cable_car', 'transit', 'transport_other']
|
||||||
|
|
||||||
@@ -41,6 +41,8 @@ export interface DayRouteInputs {
|
|||||||
optimizeFromAccommodation: boolean | undefined
|
optimizeFromAccommodation: boolean | undefined
|
||||||
toursEnabled?: boolean
|
toursEnabled?: boolean
|
||||||
places?: Place[]
|
places?: Place[]
|
||||||
|
/** MDT-02: where the stages of the trip's multi-day tours run, so a day holding one routes to it. */
|
||||||
|
tourStageStops?: TourStageStops
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -83,7 +85,7 @@ export function buildDayRouteRuns(dayId: number, input: DayRouteInputs): DayRout
|
|||||||
days: allDays,
|
days: allDays,
|
||||||
})
|
})
|
||||||
const merged = getMergedItems({ dayAssignments: da, dayNotes: [], dayTransports, dayId })
|
const merged = getMergedItems({ dayAssignments: da, dayNotes: [], dayTransports, dayId })
|
||||||
const projected = new Map(projectDayItinerary(da, input.toursEnabled ?? false, input.places).map(item => [item.assignment.id, item]))
|
const projected = projectedById(da, input.toursEnabled ?? false, input.places, input.tourStageStops)
|
||||||
|
|
||||||
type Entry =
|
type Entry =
|
||||||
| { kind: 'place'; id: number; lat: number; lng: number; pos: number; time: string | null; mode: string | null; incoming: string | null }
|
| { kind: 'place'; id: number; lat: number; lng: number; pos: number; time: string | null; mode: string | null; incoming: string | null }
|
||||||
|
|||||||
@@ -1,5 +1,32 @@
|
|||||||
|
import type { TourListItem, TourStageStop } from '@trek/shared'
|
||||||
import { analyzeRouteGeometry } from '../../utils/routeGeometry'
|
import { analyzeRouteGeometry } from '../../utils/routeGeometry'
|
||||||
import type { Assignment, Place } from '../../types'
|
import type { Assignment, Place } from '../../types'
|
||||||
|
import { vertexIndicesOf } from '../Tours/stages/tourStages'
|
||||||
|
|
||||||
|
/** MDT-02: the stops each multi-day tour's stages run between, by the tour's place id. */
|
||||||
|
export type TourStageStops = ReadonlyMap<number, readonly TourStageStop[]>
|
||||||
|
|
||||||
|
/** The stage stops of the trip's multi-day tours, from the tour list; a day tour has none. */
|
||||||
|
export function tourStageStopsByPlace(tours: readonly Pick<TourListItem, 'place_id' | 'stage_stops'>[]): TourStageStops {
|
||||||
|
return new Map(tours.flatMap(tour => (tour.stage_stops ? [[tour.place_id, tour.stage_stops] as const] : [])))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* MDT-02: the stretch of a tour's line one stage runs, from the stop it starts
|
||||||
|
* at to the stop the next one starts at; null where the stops do not tell it
|
||||||
|
* (a stage the tour no longer has, a line that has not reached them yet).
|
||||||
|
*/
|
||||||
|
function stageStretch(
|
||||||
|
line: [number, number][],
|
||||||
|
stops: readonly TourStageStop[] | undefined,
|
||||||
|
stageKey: string | null | undefined,
|
||||||
|
): [number, number][] | null {
|
||||||
|
if (!stageKey || !stops || line.length < 2) return null
|
||||||
|
const index = stops.findIndex(stop => stop.key === stageKey)
|
||||||
|
if (index < 0 || index >= stops.length - 1) return null
|
||||||
|
const at = vertexIndicesOf(stops, line)
|
||||||
|
return at[index + 1] > at[index] ? line.slice(at[index], at[index + 1] + 1) : null
|
||||||
|
}
|
||||||
|
|
||||||
export type DayItineraryItem =
|
export type DayItineraryItem =
|
||||||
| { kind: 'stop'; assignment: Assignment }
|
| { kind: 'stop'; assignment: Assignment }
|
||||||
@@ -14,10 +41,17 @@ export type DayItineraryItem =
|
|||||||
valid: boolean
|
valid: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A day's stops with each tour projected onto its line: the day's route runs
|
||||||
|
* to where the tour starts and on from where it ends. A day holding one stage
|
||||||
|
* of a multi-day tour (MDT-02) runs to that stage's start and on from its end,
|
||||||
|
* and draws that stage's stretch, where `stageStops` tells them.
|
||||||
|
*/
|
||||||
export function projectDayItinerary(
|
export function projectDayItinerary(
|
||||||
assignments: Assignment[],
|
assignments: Assignment[],
|
||||||
toursEnabled: boolean,
|
toursEnabled: boolean,
|
||||||
places: readonly Place[] = [],
|
places: readonly Place[] = [],
|
||||||
|
stageStops?: TourStageStops,
|
||||||
): DayItineraryItem[] {
|
): DayItineraryItem[] {
|
||||||
const placesById = new Map(places.map(place => [place.id, place]))
|
const placesById = new Map(places.map(place => [place.id, place]))
|
||||||
return assignments.map(assignment => {
|
return assignments.map(assignment => {
|
||||||
@@ -37,7 +71,8 @@ export function projectDayItinerary(
|
|||||||
loop: start.lat === end.lat && start.lng === end.lng, valid: true } as const
|
loop: start.lat === end.lat && start.lng === end.lng, valid: true } as const
|
||||||
}
|
}
|
||||||
const analysis = analyzeRouteGeometry(currentPlace ? currentPlace.route_geometry : assignment.tour_route_geometry)
|
const analysis = analyzeRouteGeometry(currentPlace ? currentPlace.route_geometry : assignment.tour_route_geometry)
|
||||||
const geometry = analysis?.routeCoordinates ?? []
|
const whole = analysis?.routeCoordinates ?? []
|
||||||
|
const geometry = stageStretch(whole, stageStops?.get(placeId), assignment.tour_stage_key) ?? whole
|
||||||
const start = geometry.length >= 2
|
const start = geometry.length >= 2
|
||||||
? { lat: geometry[0][0], lng: geometry[0][1] }
|
? { lat: geometry[0][0], lng: geometry[0][1] }
|
||||||
: assignment.place?.lat != null && assignment.place?.lng != null
|
: assignment.place?.lat != null && assignment.place?.lng != null
|
||||||
@@ -51,3 +86,13 @@ export function projectDayItinerary(
|
|||||||
valid: !!end } as const
|
valid: !!end } as const
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The day's stops projected as `projectDayItinerary` does, by assignment id, for the route that runs through them. */
|
||||||
|
export function projectedById(
|
||||||
|
assignments: Assignment[],
|
||||||
|
toursEnabled: boolean,
|
||||||
|
places?: readonly Place[],
|
||||||
|
stageStops?: TourStageStops,
|
||||||
|
): Map<number, DayItineraryItem> {
|
||||||
|
return new Map(projectDayItinerary(assignments, toursEnabled, places, stageStops).map(item => [item.assignment.id, item]))
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, expect, it, vi } from 'vitest';
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
import { applyBaseLayer, tourRasterSourceId } from './glRasterLayers';
|
import { applyBaseLayer, rasterTileZoom, tourRasterSourceId } from './glRasterLayers';
|
||||||
|
|
||||||
/** Enough of a GL map for the base layers: sources, layers with their visibility, and the style's order. */
|
/** Enough of a GL map for the base layers: sources, layers with their visibility, and the style's order. */
|
||||||
function fakeMap(styleLayers: Array<{ id: string }> = [{ id: 'water' }, { id: 'trip-route' }]) {
|
function fakeMap(styleLayers: Array<{ id: string }> = [{ id: 'water' }, { id: 'trip-route' }]) {
|
||||||
@@ -53,3 +53,10 @@ describe('applyBaseLayer (MAP-01)', () => {
|
|||||||
expect(() => applyBaseLayer(map, 'hiking')).not.toThrow();
|
expect(() => applyBaseLayer(map, 'hiking')).not.toThrow();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('rasterTileZoom', () => {
|
||||||
|
it('puts a GL zoom on the 256 px tile scale one step further in, where a raster minimum is read', () => {
|
||||||
|
expect(rasterTileZoom(8)).toBe(9);
|
||||||
|
expect(rasterTileZoom(7.5)).toBe(8.5);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -27,6 +27,16 @@ const SATELLITE_LAYER_ID = 'trip-satellite-raster';
|
|||||||
// `trip-` layer, and anchoring the imagery there painted right over them.
|
// `trip-` layer, and anchoring the imagery there painted right over them.
|
||||||
export const OWN_LAYER_PREFIXES = ['trip-', 'trek-', 'route-alt-'];
|
export const OWN_LAYER_PREFIXES = ['trip-', 'trek-', 'route-alt-'];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A GL map's zoom on the 256 px tile scale that raster tile URLs, their
|
||||||
|
* min and max zoom, and Leaflet count in. The GL engines count on 512 px
|
||||||
|
* tiles, so the same view is one step further in on that scale, and a 256 px
|
||||||
|
* raster source is drawn from its tiles one level up.
|
||||||
|
*/
|
||||||
|
export function rasterTileZoom(glZoom: number): number {
|
||||||
|
return glZoom + 1;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Puts the imagery on the map, or takes it off again.
|
* Puts the imagery on the map, or takes it off again.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
import { reportGlViewport } from './glViewport';
|
||||||
|
|
||||||
|
/** A GL map showing the given box at the given zoom, or no box yet. */
|
||||||
|
function fakeMap(zoom: number, box: { south: number; west: number; north: number; east: number } | null) {
|
||||||
|
const bounds = box && {
|
||||||
|
getSouth: () => box.south,
|
||||||
|
getWest: () => box.west,
|
||||||
|
getNorth: () => box.north,
|
||||||
|
getEast: () => box.east,
|
||||||
|
};
|
||||||
|
return { getBounds: () => bounds, getZoom: () => zoom };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('reportGlViewport', () => {
|
||||||
|
it('reports the visible box with the zoom on the raster tile scale', () => {
|
||||||
|
const report = vi.fn();
|
||||||
|
reportGlViewport(fakeMap(10, { south: 47, west: 11, north: 48, east: 12 }), report);
|
||||||
|
// The GL engine counts on 512 px tiles; a raster tile's zoom is one step further in.
|
||||||
|
expect(report).toHaveBeenCalledWith({ south: 47, west: 11, north: 48, east: 12 }, 11);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('says nothing while the map has no bounds yet', () => {
|
||||||
|
const report = vi.fn();
|
||||||
|
reportGlViewport(fakeMap(10, null), report);
|
||||||
|
expect(report).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('asks nothing of the map when no one listens', () => {
|
||||||
|
const map = fakeMap(10, { south: 47, west: 11, north: 48, east: 12 });
|
||||||
|
const getZoom = vi.spyOn(map, 'getZoom');
|
||||||
|
reportGlViewport(map, undefined);
|
||||||
|
expect(getZoom).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { rasterTileZoom } from './glRasterLayers';
|
||||||
|
import type { MapViewProps } from './mapViewContract';
|
||||||
|
|
||||||
|
/** Enough of a GL map to say what it shows: its bounds and its zoom. */
|
||||||
|
interface ViewportSource {
|
||||||
|
getBounds(): { getSouth(): number; getWest(): number; getNorth(): number; getEast(): number } | null;
|
||||||
|
getZoom(): number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tells the page what a GL map shows, so the POI explore pill can fetch the
|
||||||
|
* OSM places of the visible area: its bounds, and its zoom on the raster tile
|
||||||
|
* scale Leaflet reports too, so both maps ask for the same places at the
|
||||||
|
* same view. A map without bounds yet says nothing.
|
||||||
|
*/
|
||||||
|
export function reportGlViewport(map: ViewportSource, report: MapViewProps['onViewportChange']): void {
|
||||||
|
const bounds = map.getBounds();
|
||||||
|
if (!report || !bounds) return;
|
||||||
|
const bbox = { south: bounds.getSouth(), west: bounds.getWest(), north: bounds.getNorth(), east: bounds.getEast() };
|
||||||
|
report(bbox, rasterTileZoom(map.getZoom()));
|
||||||
|
}
|
||||||
@@ -31,6 +31,8 @@ type RasterOverlayStatus = 'off' | 'on' | 'down';
|
|||||||
/** An overlay with its switch: whether it is on, and whether its source stopped answering. */
|
/** An overlay with its switch: whether it is on, and whether its source stopped answering. */
|
||||||
export interface ToggleableRasterOverlay extends MapRasterOverlay {
|
export interface ToggleableRasterOverlay extends MapRasterOverlay {
|
||||||
status: RasterOverlayStatus;
|
status: RasterOverlayStatus;
|
||||||
|
/** On, but the map is further out than its first tiles, so nothing of it is drawn yet. */
|
||||||
|
belowMinZoom: boolean;
|
||||||
onToggle: () => void;
|
onToggle: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -118,6 +118,8 @@ export interface MapViewProps {
|
|||||||
detail?: string;
|
detail?: string;
|
||||||
label?: string;
|
label?: string;
|
||||||
shaping?: boolean;
|
shaping?: boolean;
|
||||||
|
/** MDT-01: a stage of a multi-day tour ends here; the pin carries a moon at its corner. */
|
||||||
|
stageEnd?: boolean;
|
||||||
}>;
|
}>;
|
||||||
selectedPlannerWaypointId?: string | null;
|
selectedPlannerWaypointId?: string | null;
|
||||||
onPlannerWaypointClick?: (id: string) => void;
|
onPlannerWaypointClick?: (id: string) => void;
|
||||||
@@ -180,7 +182,11 @@ export interface MapViewProps {
|
|||||||
roadtripVias?: Record<number, RoadtripVia[]>;
|
roadtripVias?: Record<number, RoadtripVia[]>;
|
||||||
onMoveVia?: (dayId: number, id: number, lat: number, lng: number) => void;
|
onMoveVia?: (dayId: number, id: number, lat: number, lng: number) => void;
|
||||||
onRemoveVia?: (dayId: number, id: number) => void;
|
onRemoveVia?: (dayId: number, id: number) => void;
|
||||||
onViewportChange?: (bbox: { south: number; west: number; north: number; east: number }) => void;
|
/**
|
||||||
|
* The visible area after every move, and the zoom on the 256 px tile scale
|
||||||
|
* raster tile URLs count in (a GL map's own zoom is one step lower there).
|
||||||
|
*/
|
||||||
|
onViewportChange?: (bbox: { south: number; west: number; north: number; east: number }, zoom: number) => void;
|
||||||
/**
|
/**
|
||||||
* The raster tile URL template. Only the Leaflet renderer draws raster tiles;
|
* The raster tile URL template. Only the Leaflet renderer draws raster tiles;
|
||||||
* the GL renderer draws the style of the chosen provider and ignores it.
|
* the GL renderer draws the style of the chosen provider and ignores it.
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
// FE-PLANNER-PIN-001: a stop is a numbered pin, a shaping point a small dot without a number (P2A-03).
|
// FE-PLANNER-PIN-001: a stop is a numbered pin, a shaping point a small dot without a number (P2A-03).
|
||||||
|
// FE-PLANNER-PIN-002: the stop where a stage of a multi-day tour ends carries the moon at its corner (MDT-01).
|
||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { plannerPinShape } from './plannerPinShape';
|
import { plannerPinBadge, plannerPinShape } from './plannerPinShape';
|
||||||
|
|
||||||
describe('plannerPinShape', () => {
|
describe('plannerPinShape', () => {
|
||||||
it('FE-PLANNER-PIN-001: numbers a stop by its label or its place, and leaves a shaping point blank and small', () => {
|
it('FE-PLANNER-PIN-001: numbers a stop by its label or its place, and leaves a shaping point blank and small', () => {
|
||||||
@@ -9,4 +10,13 @@ describe('plannerPinShape', () => {
|
|||||||
expect(plannerPinShape({ shaping: true, label: '9' }, 1, false)).toEqual({ size: 14, text: '' });
|
expect(plannerPinShape({ shaping: true, label: '9' }, 1, false)).toEqual({ size: 14, text: '' });
|
||||||
expect(plannerPinShape({ shaping: true }, 1, true)).toEqual({ size: 18, text: '' });
|
expect(plannerPinShape({ shaping: true }, 1, true)).toEqual({ size: 18, text: '' });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('FE-PLANNER-PIN-002: marks a stage end with the moon at the corner, and nothing else', () => {
|
||||||
|
const badge = plannerPinBadge({ stageEnd: true, label: '3' });
|
||||||
|
expect(badge).toContain('data-stage-end="true"');
|
||||||
|
expect(badge).toContain('<svg');
|
||||||
|
expect(badge).toContain('inset-inline-end');
|
||||||
|
expect(plannerPinBadge({ label: '3' })).toBe('');
|
||||||
|
expect(plannerPinBadge({ stageEnd: true, shaping: true })).toBe('');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,8 +1,14 @@
|
|||||||
|
import { Moon } from 'lucide-react';
|
||||||
|
import { createElement } from 'react';
|
||||||
|
import { renderIconMarkup } from '../../utils/iconMarkup';
|
||||||
|
|
||||||
/** What a planner pin shows: its stop number, or (P2A-03) nothing on a shaping point, which only steers the route. */
|
/** What a planner pin shows: its stop number, or (P2A-03) nothing on a shaping point, which only steers the route. */
|
||||||
export interface PlannerPinPoint {
|
export interface PlannerPinPoint {
|
||||||
/** The stop number to print; shaping points do not count, so stops keep their numbers. */
|
/** The stop number to print; shaping points do not count, so stops keep their numbers. */
|
||||||
label?: string;
|
label?: string;
|
||||||
shaping?: boolean;
|
shaping?: boolean;
|
||||||
|
/** MDT-01: a stage of a multi-day tour ends at this stop. */
|
||||||
|
stageEnd?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A stop is a numbered pin; a shaping point a small dot of the same colour, without a number. */
|
/** A stop is a numbered pin; a shaping point a small dot of the same colour, without a number. */
|
||||||
@@ -14,3 +20,15 @@ export function plannerPinShape(
|
|||||||
if (point.shaping) return { size: selected ? 18 : 14, text: '' };
|
if (point.shaping) return { size: selected ? 18 : 14, text: '' };
|
||||||
return { size: selected ? 30 : 26, text: point.label ?? String(index + 1) };
|
return { size: selected ? 30 : 26, text: point.label ?? String(index + 1) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const MOON = renderIconMarkup(createElement(Moon, { size: 9, strokeWidth: 2.6, 'aria-hidden': true }));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* MDT-01: the moon at the corner of a pin where a stage ends, the night
|
||||||
|
* between two days of the tour, as the planner's list marks the stop's number.
|
||||||
|
* Laid over the pin, so it needs no room of its own and moves with it.
|
||||||
|
*/
|
||||||
|
export function plannerPinBadge(point: PlannerPinPoint): string {
|
||||||
|
if (!point.stageEnd || point.shaping) return '';
|
||||||
|
return `<span data-stage-end="true" aria-hidden="true" style="position:absolute;bottom:-4px;inset-inline-end:-4px;display:grid;place-items:center;width:15px;height:15px;border-radius:9999px;background:var(--bg-card);color:var(--text-primary);box-shadow:var(--shadow-sm);pointer-events:none">${MOON}</span>`;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Utensils, Coffee, Wine, BedDouble, Camera, Landmark, Trees, Ticket, Fuel, Zap, ParkingSquare, Tent, Binoculars, Mountain, Warehouse, Droplet, Toilet, Sandwich, Anchor, Sailboat, Wrench, type LucideIcon } from 'lucide-react'
|
import { Utensils, Coffee, Wine, BedDouble, Camera, Landmark, Trees, Ticket, Fuel, Zap, ParkingSquare, Tent, Binoculars, Mountain, Warehouse, Droplet, Toilet, Sandwich, Anchor, Sailboat, Wrench, Store, type LucideIcon } from 'lucide-react'
|
||||||
import type { TourPoiCategory } from '@trek/shared'
|
import type { TourPoiCategory } from '@trek/shared'
|
||||||
import { parsePluginPoiCategoryKey, type PluginPoiDetail } from '@trek/shared'
|
import { parsePluginPoiCategoryKey, type PluginPoiDetail } from '@trek/shared'
|
||||||
// The road-trip kinds take their colour from the one place that defines it, so the
|
// The road-trip kinds take their colour from the one place that defines it, so the
|
||||||
@@ -62,6 +62,12 @@ export const TOUR_POI_LOOKS: Record<TourPoiCategory, PoiCategory> = {
|
|||||||
slipway: { key: 'slipway', labelKey: 'tours.poi.cat.slipway', Icon: Anchor, color: coreColor('museum') },
|
slipway: { key: 'slipway', labelKey: 'tours.poi.cat.slipway', Icon: Anchor, color: coreColor('museum') },
|
||||||
boat_rental: { key: 'boat_rental', labelKey: 'tours.poi.cat.boat_rental', Icon: Sailboat, color: coreColor('cafe') },
|
boat_rental: { key: 'boat_rental', labelKey: 'tours.poi.cat.boat_rental', Icon: Sailboat, color: coreColor('cafe') },
|
||||||
bike_repair: { key: 'bike_repair', labelKey: 'tours.poi.cat.bike_repair', Icon: Wrench, color: coreColor('activity') },
|
bike_repair: { key: 'bike_repair', labelKey: 'tours.poi.cat.bike_repair', Icon: Wrench, color: coreColor('activity') },
|
||||||
|
// CW-05: a city walk's own, each in the colour of the explore category it comes from.
|
||||||
|
museum: { key: 'museum', labelKey: 'tours.poi.cat.museum', Icon: Landmark, color: coreColor('museum') },
|
||||||
|
park: { key: 'park', labelKey: 'tours.poi.cat.park', Icon: Trees, color: coreColor('nature') },
|
||||||
|
cafe: { key: 'cafe', labelKey: 'tours.poi.cat.cafe', Icon: Coffee, color: coreColor('cafe') },
|
||||||
|
restaurant: { key: 'restaurant', labelKey: 'tours.poi.cat.restaurant', Icon: Utensils, color: coreColor('restaurant') },
|
||||||
|
market: { key: 'market', labelKey: 'tours.poi.cat.market', Icon: Store, color: coreColor('shopping') },
|
||||||
}
|
}
|
||||||
|
|
||||||
// A Map rather than an object, so a category named after an Object.prototype member
|
// A Map rather than an object, so a category named after an Object.prototype member
|
||||||
|
|||||||
@@ -107,6 +107,7 @@ export function planTripRoute(input: TripRouteInputs, profile: RouteProfileKey):
|
|||||||
(input.assignments[String(day.id)] ?? []).filter(assignment => assignment.accommodation_id == null),
|
(input.assignments[String(day.id)] ?? []).filter(assignment => assignment.accommodation_id == null),
|
||||||
input.toursEnabled ?? false,
|
input.toursEnabled ?? false,
|
||||||
input.places,
|
input.places,
|
||||||
|
input.tourStageStops,
|
||||||
).flatMap(item => item.kind === 'tour' && item.geometry.length >= 2 ? [item.geometry] : []),
|
).flatMap(item => item.kind === 'tour' && item.geometry.length >= 2 ? [item.geometry] : []),
|
||||||
}))
|
}))
|
||||||
.filter(entry => entry.runs.length > 0 || entry.tourLines.length > 0)
|
.filter(entry => entry.runs.length > 0 || entry.tourLines.length > 0)
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
// FE-PLANNER-PIN-GL-001: the GL map's planner pins carry the moon where a stage of a multi-day tour ends (MDT-01).
|
||||||
|
import { renderHook } from '@testing-library/react';
|
||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
import { usePlannerWaypointMarkersGL } from './usePlannerWaypointMarkersGL';
|
||||||
|
|
||||||
|
describe('usePlannerWaypointMarkersGL', () => {
|
||||||
|
it('FE-PLANNER-PIN-GL-001: puts the moon on the pin of a stage end only, numbered as the list numbers it', () => {
|
||||||
|
const container = document.createElement('div');
|
||||||
|
const map = { getContainer: () => container, unproject: () => ({ lat: 0, lng: 0 }) };
|
||||||
|
const attached: HTMLElement[] = [];
|
||||||
|
renderHook(() =>
|
||||||
|
usePlannerWaypointMarkersGL({
|
||||||
|
mapRef: { current: map },
|
||||||
|
mapReady: true,
|
||||||
|
pinsRef: { current: [] },
|
||||||
|
attachPin: (el) => {
|
||||||
|
attached.push(el);
|
||||||
|
return { remove: vi.fn(), setLngLat: vi.fn() };
|
||||||
|
},
|
||||||
|
pinCss: () => 'display:flex',
|
||||||
|
plannerWaypoints: [
|
||||||
|
{ id: 'a', lat: 47, lng: 11, label: '1' },
|
||||||
|
{ id: 'b', lat: 47.1, lng: 11, label: '2', stageEnd: true },
|
||||||
|
],
|
||||||
|
selectedPlannerWaypointId: null,
|
||||||
|
onPlannerWaypointClick: vi.fn(),
|
||||||
|
onPlannerWaypointMove: undefined,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
expect(attached).toHaveLength(2);
|
||||||
|
expect(attached[0].querySelector('[data-stage-end]')).toBeNull();
|
||||||
|
expect(attached[1].querySelector('[data-stage-end]')).not.toBeNull();
|
||||||
|
expect(attached[1].textContent).toBe('2');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -2,7 +2,7 @@ import { useEffect, useLayoutEffect, useRef } from 'react';
|
|||||||
|
|
||||||
import { bindPinHoverLabel, mapHoverLabel } from './mapHoverLabel';
|
import { bindPinHoverLabel, mapHoverLabel } from './mapHoverLabel';
|
||||||
import type { MapViewProps } from './mapViewContract';
|
import type { MapViewProps } from './mapViewContract';
|
||||||
import { plannerPinShape } from './plannerPinShape';
|
import { plannerPinBadge, plannerPinShape } from './plannerPinShape';
|
||||||
import { wirePlannerWaypointDrag } from './plannerWaypointDrag';
|
import { wirePlannerWaypointDrag } from './plannerWaypointDrag';
|
||||||
|
|
||||||
/** The slice of the GL map the waypoint pins need: its box and screen-to-ground lookup. */
|
/** The slice of the GL map the waypoint pins need: its box and screen-to-ground lookup. */
|
||||||
@@ -79,6 +79,9 @@ export function usePlannerWaypointMarkersGL<Pin extends PlannerWaypointPin>({
|
|||||||
const name = point.name ?? `Waypoint ${index + 1}`;
|
const name = point.name ?? `Waypoint ${index + 1}`;
|
||||||
el.setAttribute('aria-label', name);
|
el.setAttribute('aria-label', name);
|
||||||
el.style.cssText = `${pinCss(size, selected)};cursor:pointer;padding:0`;
|
el.style.cssText = `${pinCss(size, selected)};cursor:pointer;padding:0`;
|
||||||
|
// MDT-01: the moon where a stage ends; the pin is positioned, so the badge sits at its corner.
|
||||||
|
const badge = plannerPinBadge(point);
|
||||||
|
if (badge) el.insertAdjacentHTML('beforeend', badge);
|
||||||
const swallow = (event: Event) => event.stopPropagation();
|
const swallow = (event: Event) => event.stopPropagation();
|
||||||
const select = (event: Event) => {
|
const select = (event: Event) => {
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { useSettingsStore } from '../../store/settingsStore'
|
|||||||
import { useAddonStore } from '../../store/addonStore'
|
import { useAddonStore } from '../../store/addonStore'
|
||||||
import type { RoadtripVia } from '@trek/shared'
|
import type { RoadtripVia } from '@trek/shared'
|
||||||
import type { Accommodation, AssignmentsMap, Day, Place, Reservation } from '../../types'
|
import type { Accommodation, AssignmentsMap, Day, Place, Reservation } from '../../types'
|
||||||
|
import type { TourStageStops } from './dayTourProjection'
|
||||||
|
|
||||||
export type { TripOverviewDay, TripRouteSummary } from './tripRouteGeometry'
|
export type { TripOverviewDay, TripRouteSummary } from './tripRouteGeometry'
|
||||||
|
|
||||||
@@ -46,6 +47,8 @@ export function useTripRouteOverview(
|
|||||||
enabled: boolean,
|
enabled: boolean,
|
||||||
places: Place[] = EMPTY_PLACES,
|
places: Place[] = EMPTY_PLACES,
|
||||||
vias?: TripRouteVias,
|
vias?: TripRouteVias,
|
||||||
|
/** MDT-02: where the stages of the trip's multi-day tours run, so a day holding one draws that stage. */
|
||||||
|
tourStageStops?: TourStageStops,
|
||||||
): TripRouteOverview {
|
): TripRouteOverview {
|
||||||
const optimizeFromAccommodation = useSettingsStore(s => s.settings.optimize_from_accommodation)
|
const optimizeFromAccommodation = useSettingsStore(s => s.settings.optimize_from_accommodation)
|
||||||
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
|
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
|
||||||
@@ -66,9 +69,9 @@ export function useTripRouteOverview(
|
|||||||
const viasByDay = vias?.viasByDay
|
const viasByDay = vias?.viasByDay
|
||||||
const plan = useMemo(
|
const plan = useMemo(
|
||||||
() => (enabled
|
() => (enabled
|
||||||
? planTripRoute({ days, assignments, reservations, accommodations, optimizeFromAccommodation, toursEnabled, places, storedAssignments, viasByDay }, profile)
|
? planTripRoute({ days, assignments, reservations, accommodations, optimizeFromAccommodation, toursEnabled, places, storedAssignments, viasByDay, tourStageStops }, profile)
|
||||||
: []),
|
: []),
|
||||||
[enabled, days, assignments, reservations, accommodations, optimizeFromAccommodation, profile, toursEnabled, places, storedAssignments, viasByDay],
|
[enabled, days, assignments, reservations, accommodations, optimizeFromAccommodation, profile, toursEnabled, places, storedAssignments, viasByDay, tourStageStops],
|
||||||
)
|
)
|
||||||
|
|
||||||
// Only geometry and mode decide whether legs have to be fetched again: renaming a
|
// Only geometry and mode decide whether legs have to be fetched again: renaming a
|
||||||
|
|||||||
@@ -519,6 +519,23 @@ describe('valhallaAlternates', () => {
|
|||||||
expect(bodies[1]).not.toHaveProperty('alternates')
|
expect(bodies[1]).not.toHaveProperty('alternates')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('VALHALLA-ALT-005: a section of a hike is offered ways on foot under its own limit and preferences (RTE-02)', async () => {
|
||||||
|
const bodies: Record<string, unknown>[] = []
|
||||||
|
server.use(http.post(FOSSGIS_VALHALLA, async ({ request }) => {
|
||||||
|
bodies.push(await request.json() as Record<string, unknown>)
|
||||||
|
return HttpResponse.json(withAlternates([answer({ time: 12_000 })]))
|
||||||
|
}))
|
||||||
|
|
||||||
|
const ways = await valhallaAlternates(HAMBURG, BERLIN, 'walking', [], 3, undefined, { max_hiking_difficulty: 4, use_hills: 0.2 })
|
||||||
|
|
||||||
|
expect(ways).toHaveLength(2)
|
||||||
|
expect(bodies[0]).toMatchObject({
|
||||||
|
alternates: 3,
|
||||||
|
costing: 'pedestrian',
|
||||||
|
costing_options: { pedestrian: { max_hiking_difficulty: 4, use_hills: 0.2 } },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
it('VALHALLA-ALT-004: a refusal is asked once more, then is no answer; an instance with its own OSRM asks nothing', async () => {
|
it('VALHALLA-ALT-004: a refusal is asked once more, then is no answer; an instance with its own OSRM asks nothing', async () => {
|
||||||
let calls = 0
|
let calls = 0
|
||||||
server.use(http.post(FOSSGIS_VALHALLA, () => { calls++; return new HttpResponse(null, { status: 429 }) }))
|
server.use(http.post(FOSSGIS_VALHALLA, () => { calls++; return new HttpResponse(null, { status: 429 }) }))
|
||||||
@@ -551,6 +568,21 @@ describe('valhallaTraceAttributes (BIK-01)', () => {
|
|||||||
expect(bodies[0].shape).toEqual(SHAPE_POINTS.map(([lat, lon]) => ({ lat, lon })))
|
expect(bodies[0].shape).toEqual(SHAPE_POINTS.map(([lat, lon]) => ({ lat, lon })))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('VALHALLA-TRACE-005: a run is matched on foot without a hiking limit, and every line is asked its hiking grades (RUN-02)', async () => {
|
||||||
|
const bodies: Record<string, unknown>[] = []
|
||||||
|
server.use(http.post(TRACE, async ({ request }) => {
|
||||||
|
bodies.push(await request.json() as Record<string, unknown>)
|
||||||
|
return HttpResponse.json({ shape: SHAPE, edges: [] })
|
||||||
|
}))
|
||||||
|
await valhallaTraceAttributes(SHAPE_POINTS, undefined, 'run')
|
||||||
|
expect(bodies[0]).toMatchObject({
|
||||||
|
costing: 'pedestrian',
|
||||||
|
costing_options: { pedestrian: { max_hiking_difficulty: 6 } },
|
||||||
|
shape_match: 'map_snap',
|
||||||
|
})
|
||||||
|
expect((bodies[0].filters as { attributes: string[] }).attributes).toContain('edge.sac_scale')
|
||||||
|
})
|
||||||
|
|
||||||
it('VALHALLA-TRACE-002: a long line is thinned evenly to what one request carries, its ends kept', async () => {
|
it('VALHALLA-TRACE-002: a long line is thinned evenly to what one request carries, its ends kept', async () => {
|
||||||
let shape: unknown[] = []
|
let shape: unknown[] = []
|
||||||
server.use(http.post(TRACE, async ({ request }) => {
|
server.use(http.post(TRACE, async ({ request }) => {
|
||||||
@@ -574,6 +606,21 @@ describe('valhallaTraceAttributes (BIK-01)', () => {
|
|||||||
await expect(valhallaTraceAttributes(SHAPE_POINTS)).resolves.toBeNull()
|
await expect(valhallaTraceAttributes(SHAPE_POINTS)).resolves.toBeNull()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('VALHALLA-TRACE-006: a hike is matched on foot with every grade of path open, never by its routing limit (MAP-03)', async () => {
|
||||||
|
const bodies: Record<string, unknown>[] = []
|
||||||
|
server.use(http.post(TRACE, async ({ request }) => {
|
||||||
|
bodies.push(await request.json() as Record<string, unknown>)
|
||||||
|
return HttpResponse.json({ shape: SHAPE, edges: [] })
|
||||||
|
}))
|
||||||
|
await valhallaTraceAttributes(SHAPE_POINTS, undefined, 'foot')
|
||||||
|
expect(bodies[0]).toMatchObject({
|
||||||
|
costing: 'pedestrian',
|
||||||
|
costing_options: { pedestrian: { max_hiking_difficulty: 6 } },
|
||||||
|
shape_match: 'map_snap',
|
||||||
|
})
|
||||||
|
expect(JSON.stringify(bodies[0])).not.toContain('sac_scale')
|
||||||
|
})
|
||||||
|
|
||||||
it('VALHALLA-TRACE-004: a caller gone before its turn asks nothing', async () => {
|
it('VALHALLA-TRACE-004: a caller gone before its turn asks nothing', async () => {
|
||||||
let asked = false
|
let asked = false
|
||||||
server.use(http.post(TRACE, () => { asked = true; return HttpResponse.json({}) }))
|
server.use(http.post(TRACE, () => { asked = true; return HttpResponse.json({}) }))
|
||||||
|
|||||||
@@ -368,14 +368,48 @@ const TRACE_MAX_POINTS = 4000
|
|||||||
const TRACE_TIMEOUT_MS = 30_000
|
const TRACE_TIMEOUT_MS = 30_000
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* BIK-01: how the router describes the ways under a line (`trace_attributes`):
|
* How a line is matched to the ways under it: as a mountain bike rides, the
|
||||||
* the surface, the use and road class, the cycle lane and the OpenStreetMap way
|
* bicycle costing that refuses the fewest ways, so a road bike's route and a
|
||||||
* of every edge, with the line as matched. The edges are matched as a mountain
|
* gravel one are described alike; or on foot with every grade of path open,
|
||||||
* bike would ride them, the costing that refuses the fewest ways, so a road
|
* since a hike's line (MAP-03) may run on a T6 ridge the matcher must not
|
||||||
* bike's route and a gravel one are described alike. Null for every failure:
|
* refuse, and steps and mountain paths a run takes (RUN-02) stay on the line
|
||||||
* the description is an addition beside a route that already exists.
|
* (matched as a bike, a trail run over steps was described as the street
|
||||||
|
* beside them). Matching is no routing: the limit a hike was planned with
|
||||||
|
* plays no part. A hike and a run are matched alike; they differ in whether
|
||||||
|
* the router's own hiking grade is asked for.
|
||||||
*/
|
*/
|
||||||
export async function valhallaTraceAttributes(line: readonly [number, number][], signal?: AbortSignal): Promise<unknown> {
|
const TRACE_COSTING = {
|
||||||
|
bike: { costing: 'bicycle', costing_options: { bicycle: { bicycle_type: 'Mountain' } } },
|
||||||
|
foot: { costing: 'pedestrian', costing_options: { pedestrian: { max_hiking_difficulty: 6 } } },
|
||||||
|
run: { costing: 'pedestrian', costing_options: { pedestrian: { max_hiking_difficulty: 6 } } },
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export type TraceMatching = keyof typeof TRACE_COSTING
|
||||||
|
|
||||||
|
const TRACE_ATTRIBUTES = ['shape', 'edge.surface', 'edge.use', 'edge.road_class', 'edge.cycle_lane', 'edge.length',
|
||||||
|
'edge.way_id', 'edge.begin_shape_index', 'edge.end_shape_index']
|
||||||
|
|
||||||
|
/** The router's hiking grade is asked along a bike tour's and a run's line, never a hike's (MAP-03 reads OpenStreetMap). */
|
||||||
|
function traceAttributesFor(matching: TraceMatching): string[] {
|
||||||
|
return matching === 'foot' ? TRACE_ATTRIBUTES : [...TRACE_ATTRIBUTES, 'edge.sac_scale']
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* BIK-01, RUN-02 and MAP-03: how the router describes the ways under a line
|
||||||
|
* (`trace_attributes`): the surface, the use and road class, the cycle lane,
|
||||||
|
* the OpenStreetMap way of every edge and, but for a hike, the router's
|
||||||
|
* hiking grade (`sac_scale`, 0 where the way has none), with the line as
|
||||||
|
* matched. A run's grade shares (RUN-02) read the router's grade; the grade a
|
||||||
|
* hike shows (MAP-03) comes from OpenStreetMap itself, since the router's
|
||||||
|
* reading may be normalised or derived, so it is not asked for there. Null for
|
||||||
|
* every failure: the description is an addition beside a route that already
|
||||||
|
* exists.
|
||||||
|
*/
|
||||||
|
export async function valhallaTraceAttributes(
|
||||||
|
line: readonly [number, number][],
|
||||||
|
signal?: AbortSignal,
|
||||||
|
matching: TraceMatching = 'bike'
|
||||||
|
): Promise<unknown> {
|
||||||
const base = valhallaBase()
|
const base = valhallaBase()
|
||||||
if (!base || line.length < 2) return null
|
if (!base || line.length < 2) return null
|
||||||
const step = Math.max(1, Math.ceil(line.length / TRACE_MAX_POINTS))
|
const step = Math.max(1, Math.ceil(line.length / TRACE_MAX_POINTS))
|
||||||
@@ -389,12 +423,10 @@ export async function valhallaTraceAttributes(line: readonly [number, number][],
|
|||||||
headers: { 'Content-Type': 'application/json', 'X-Client-Id': 'trek' },
|
headers: { 'Content-Type': 'application/json', 'X-Client-Id': 'trek' },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
shape,
|
shape,
|
||||||
costing: 'bicycle',
|
...TRACE_COSTING[matching],
|
||||||
costing_options: { bicycle: { bicycle_type: 'Mountain' } },
|
|
||||||
shape_match: 'map_snap',
|
shape_match: 'map_snap',
|
||||||
filters: {
|
filters: {
|
||||||
attributes: ['shape', 'edge.surface', 'edge.use', 'edge.road_class', 'edge.cycle_lane', 'edge.length', 'edge.way_id',
|
attributes: traceAttributesFor(matching),
|
||||||
'edge.begin_shape_index', 'edge.end_shape_index'],
|
|
||||||
action: 'include',
|
action: 'include',
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
@@ -428,6 +460,8 @@ async function requestRun(
|
|||||||
* quickest road beside a day Valhalla had routed was offered as the faster way, and
|
* quickest road beside a day Valhalla had routed was offered as the faster way, and
|
||||||
* taking it changed nothing. Valhalla answers `alternates` between exactly two locations,
|
* taking it changed nothing. Valhalla answers `alternates` between exactly two locations,
|
||||||
* which is all one leg is, and weighs every one of them the way it weighed the day.
|
* which is all one leg is, and weighs every one of them the way it weighed the day.
|
||||||
|
* `costingOptions` carries the rest of how that day was weighed, such as a hike's limit
|
||||||
|
* and preferences (RTE-02), so a section of a tour is offered ways under its own rules.
|
||||||
*/
|
*/
|
||||||
export async function valhallaAlternates(
|
export async function valhallaAlternates(
|
||||||
from: Waypoint,
|
from: Waypoint,
|
||||||
@@ -436,10 +470,11 @@ export async function valhallaAlternates(
|
|||||||
avoid: readonly AvoidClass[],
|
avoid: readonly AvoidClass[],
|
||||||
count: number,
|
count: number,
|
||||||
signal?: AbortSignal,
|
signal?: AbortSignal,
|
||||||
|
costingOptions: Readonly<CostingOptions> = {},
|
||||||
): Promise<ValhallaLeg[] | null> {
|
): Promise<ValhallaLeg[] | null> {
|
||||||
const base = valhallaBase()
|
const base = valhallaBase()
|
||||||
if (!base || notValhalla.has(base)) return null
|
if (!base || notValhalla.has(base)) return null
|
||||||
const body = { ...routeBody([from, to], profile, avoid), ...(count > 0 ? { alternates: count } : {}) }
|
const body = { ...routeBody([from, to], profile, avoid, costingOptions), ...(count > 0 ? { alternates: count } : {}) }
|
||||||
return askWithRetry(base, async () => {
|
return askWithRetry(base, async () => {
|
||||||
const data = await postRoute(base, body, signal)
|
const data = await postRoute(base, body, signal)
|
||||||
return data === null ? null : alternatesFrom(data)
|
return data === null ? null : alternatesFrom(data)
|
||||||
|
|||||||
@@ -15,8 +15,9 @@ export const KAT_COLORS = [
|
|||||||
export const BAG_COLORS = ['#6366f1', '#ec4899', '#f97316', '#10b981', '#06b6d4', '#8b5cf6', '#ef4444', '#f59e0b', '#3b82f6', '#84cc16', '#d946ef', '#14b8a6', '#f43f5e', '#a855f7', '#eab308', '#64748b']
|
export const BAG_COLORS = ['#6366f1', '#ec4899', '#f97316', '#10b981', '#06b6d4', '#8b5cf6', '#ef4444', '#f59e0b', '#3b82f6', '#84cc16', '#d946ef', '#14b8a6', '#f43f5e', '#a855f7', '#eab308', '#64748b']
|
||||||
|
|
||||||
// A category's first item is seeded with this sentinel because the server
|
// A category's first item is seeded with this sentinel because the server
|
||||||
// rejects empty names. Treat it as a placeholder in the UI.
|
// rejects empty names. Treat it as a placeholder in the UI. Shared, because a
|
||||||
export const PACKING_PLACEHOLDER_NAME = '...'
|
// tour's packing link (P2D-XD-01) leaves it out the same way.
|
||||||
|
export { PACKING_PLACEHOLDER_NAME } from '@trek/shared'
|
||||||
|
|
||||||
/** What the import's file picker offers: CSV rows, plain text, or a Markdown list (#875). */
|
/** What the import's file picker offers: CSV rows, plain text, or a Markdown list (#875). */
|
||||||
export const PACKING_IMPORT_ACCEPT = '.csv,.txt,.md,.markdown,text/markdown'
|
export const PACKING_IMPORT_ACCEPT = '.csv,.txt,.md,.markdown,text/markdown'
|
||||||
|
|||||||
@@ -6,9 +6,13 @@ import '../../styles/fadeEnd.css';
|
|||||||
import type { Category, Place } from '../../types';
|
import type { Category, Place } from '../../types';
|
||||||
import { formatTime } from '../../utils/formatters';
|
import { formatTime } from '../../utils/formatters';
|
||||||
import { fs } from '../shared/DialogShell';
|
import { fs } from '../shared/DialogShell';
|
||||||
|
import { stageNumberOf } from '../Tours/stages/stageNames';
|
||||||
|
import { TourStageDayPills } from '../Tours/stages/TourStageDayPills';
|
||||||
import { TourDayRowPills } from '../Tours/TourDayRowFacts';
|
import { TourDayRowPills } from '../Tours/TourDayRowFacts';
|
||||||
|
import { TourDayTimeText } from '../Tours/TourDayTimeParts';
|
||||||
import { movingTimeLabel } from '../Tours/tourFacts';
|
import { movingTimeLabel } from '../Tours/tourFacts';
|
||||||
import { formatPlannedTourDuration, type TourPlannedTimes } from '../Tours/tourPresentation';
|
import { formatPlannedTourDuration, plannedTotalText, type TourPlannedTimes } from '../Tours/tourPresentation';
|
||||||
|
import { WalkProgressPill } from '../Tours/walk/WalkStations';
|
||||||
import { TimePill } from './planParts';
|
import { TimePill } from './planParts';
|
||||||
|
|
||||||
type DayRowTourTimes = TourPlannedTimes & { tour?: TourListItem };
|
type DayRowTourTimes = TourPlannedTimes & { tour?: TourListItem };
|
||||||
@@ -19,6 +23,10 @@ interface DayPlanPlaceSublineProps {
|
|||||||
tourTimes: DayRowTourTimes | undefined;
|
tourTimes: DayRowTourTimes | undefined;
|
||||||
isTourPlace: boolean;
|
isTourPlace: boolean;
|
||||||
timeFormat: string;
|
timeFormat: string;
|
||||||
|
/** CW-03: the row's day assignment, which a city walk's progress belongs to. */
|
||||||
|
assignmentId?: number;
|
||||||
|
/** MDT-02: the stage of a multi-day tour the day holds, by its starting stop's key; absent for the whole tour. */
|
||||||
|
tourStageKey?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function hasPlannedTimes(tourTimes: DayRowTourTimes | undefined): boolean {
|
function hasPlannedTimes(tourTimes: DayRowTourTimes | undefined): boolean {
|
||||||
@@ -57,9 +65,9 @@ function PlannedTourPills({ tourTimes }: { tourTimes: DayRowTourTimes }) {
|
|||||||
<TimePill>
|
<TimePill>
|
||||||
<span
|
<span
|
||||||
data-testid="trip-plan-tour-planned-duration"
|
data-testid="trip-plan-tour-planned-duration"
|
||||||
aria-label={`${t('tours.planner.plannedTotalDuration')}: ${formatPlannedTourDuration(tourTimes.plannedTotalMinutes)}${manual ? `, ${t('tours.planner.plannedTotalManual')}` : ''}`}
|
aria-label={`${t('tours.planner.plannedTotalDuration')}: ${plannedTotalText(tourTimes, t)}${manual ? `, ${t('tours.planner.plannedTotalManual')}` : ''}`}
|
||||||
>
|
>
|
||||||
{t('tours.planner.plannedShort')}: {formatPlannedTourDuration(tourTimes.plannedTotalMinutes)}
|
{t('tours.planner.plannedShort')}: {plannedTotalText(tourTimes, t, true)}
|
||||||
{manual ? ` · ${t('tours.planner.plannedTotalManual')}` : ''}
|
{manual ? ` · ${t('tours.planner.plannedTotalManual')}` : ''}
|
||||||
</span>
|
</span>
|
||||||
</TimePill>
|
</TimePill>
|
||||||
@@ -68,6 +76,12 @@ function PlannedTourPills({ tourTimes }: { tourTimes: DayRowTourTimes }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The tour's own pills, or a stage's where the day holds one stage of a multi-day tour (MDT-02).
|
||||||
|
function DayRowTourPills({ tour, stageKey }: { tour: TourListItem; stageKey?: string | null }) {
|
||||||
|
if (stageKey && stageNumberOf(tour, stageKey) !== null) return <TourStageDayPills tour={tour} stageKey={stageKey} />;
|
||||||
|
return <TourDayRowPills tour={tour} />;
|
||||||
|
}
|
||||||
|
|
||||||
// Description line, one line like every stop's.
|
// Description line, one line like every stop's.
|
||||||
function SublineDescription({ text, isTourPlace }: { text: string; isTourPlace: boolean }) {
|
function SublineDescription({ text, isTourPlace }: { text: string; isTourPlace: boolean }) {
|
||||||
return (
|
return (
|
||||||
@@ -90,7 +104,15 @@ function SublineDescription({ text, isTourPlace }: { text: string; isTourPlace:
|
|||||||
|
|
||||||
// Second line of a place row in the day plan: time, tour facts or planned
|
// Second line of a place row in the day plan: time, tour facts or planned
|
||||||
// tour durations, then the clamped description.
|
// tour durations, then the clamped description.
|
||||||
export function DayPlanPlaceSubline({ place, cat, tourTimes, isTourPlace, timeFormat }: DayPlanPlaceSublineProps) {
|
export function DayPlanPlaceSubline({
|
||||||
|
place,
|
||||||
|
cat,
|
||||||
|
tourTimes,
|
||||||
|
isTourPlace,
|
||||||
|
timeFormat,
|
||||||
|
assignmentId,
|
||||||
|
tourStageKey,
|
||||||
|
}: DayPlanPlaceSublineProps) {
|
||||||
const { locale } = useTranslation();
|
const { locale } = useTranslation();
|
||||||
const dayRowTour = tourTimes?.tour;
|
const dayRowTour = tourTimes?.tour;
|
||||||
const description = place.description || place.address || cat?.name;
|
const description = place.description || place.address || cat?.name;
|
||||||
@@ -99,13 +121,27 @@ export function DayPlanPlaceSubline({ place, cat, tourTimes, isTourPlace, timeFo
|
|||||||
// One line like the row's name: when the hover controls come out, the description
|
// One line like the row's name: when the hover controls come out, the description
|
||||||
// gives way and the pills keep their place instead of wrapping onto a second line.
|
// gives way and the pills keep their place instead of wrapping onto a second line.
|
||||||
<div className="trek-fade-end mt-0.5 flex min-w-0 flex-nowrap items-center gap-1.5 overflow-hidden">
|
<div className="trek-fade-end mt-0.5 flex min-w-0 flex-nowrap items-center gap-1.5 overflow-hidden">
|
||||||
{place.place_time && (
|
{place.place_time && dayRowTour && (
|
||||||
|
// TIME-02: a tour's end, typed or worked out from its start and its time.
|
||||||
|
<TimePill quiet>
|
||||||
|
<TourDayTimeText
|
||||||
|
entry={{ start: place.place_time, end: place.end_time, stageKey: tourStageKey }}
|
||||||
|
tour={dayRowTour}
|
||||||
|
/>
|
||||||
|
</TimePill>
|
||||||
|
)}
|
||||||
|
{place.place_time && !dayRowTour && (
|
||||||
<TimePill quiet>
|
<TimePill quiet>
|
||||||
{formatTime(place.place_time, locale, timeFormat)}
|
{formatTime(place.place_time, locale, timeFormat)}
|
||||||
{place.end_time ? ` – ${formatTime(place.end_time, locale, timeFormat)}` : ''}
|
{place.end_time ? ` – ${formatTime(place.end_time, locale, timeFormat)}` : ''}
|
||||||
</TimePill>
|
</TimePill>
|
||||||
)}
|
)}
|
||||||
{dayRowTour ? <TourDayRowPills tour={dayRowTour} /> : tourTimes && <PlannedTourPills tourTimes={tourTimes} />}
|
{dayRowTour ? (
|
||||||
|
<DayRowTourPills tour={dayRowTour} stageKey={tourStageKey} />
|
||||||
|
) : (
|
||||||
|
tourTimes && <PlannedTourPills tourTimes={tourTimes} />
|
||||||
|
)}
|
||||||
|
{dayRowTour && <WalkProgressPill tour={dayRowTour} assignmentId={assignmentId} />}
|
||||||
{description && <SublineDescription text={description} isTourPlace={isTourPlace} />}
|
{description && <SublineDescription text={description} isTourPlace={isTourPlace} />}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,16 +1,28 @@
|
|||||||
// RS-01 / RC-01: how a Tour stop reads in the day plan while the Tours addon is on,
|
// RS-01 / RC-01: how a Tour stop reads in the day plan while the Tours addon is on,
|
||||||
// and that it falls back to the plain Place row when it is off. The mocks are the
|
// and that it falls back to the plain Place row when it is off. The mocks are the
|
||||||
// ones DayPlanSidebar.test.tsx renders the sidebar with.
|
// ones DayPlanSidebar.test.tsx renders the sidebar with.
|
||||||
|
// CW-08: public transit between two city walks from the day plan's connector.
|
||||||
|
import userEvent from '@testing-library/user-event';
|
||||||
|
import type { TourListItem } from '@trek/shared';
|
||||||
import { http, HttpResponse } from 'msw';
|
import { http, HttpResponse } from 'msw';
|
||||||
import { buildAssignment, buildDay, buildPlace, buildTrip, buildUser } from '../../../tests/helpers/factories';
|
import {
|
||||||
|
buildAssignment,
|
||||||
|
buildDay,
|
||||||
|
buildPlace,
|
||||||
|
buildReservation,
|
||||||
|
buildTrip,
|
||||||
|
buildUser,
|
||||||
|
} from '../../../tests/helpers/factories';
|
||||||
import { server } from '../../../tests/helpers/msw/server';
|
import { server } from '../../../tests/helpers/msw/server';
|
||||||
import { render, screen } from '../../../tests/helpers/render';
|
import { render, screen, waitFor, within } from '../../../tests/helpers/render';
|
||||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||||
import { clearExchangeRateCache } from '../../hooks/useExchangeRates';
|
import { clearExchangeRateCache } from '../../hooks/useExchangeRates';
|
||||||
import { useAddonStore } from '../../store/addonStore';
|
import { useAddonStore } from '../../store/addonStore';
|
||||||
import { useAuthStore } from '../../store/authStore';
|
import { useAuthStore } from '../../store/authStore';
|
||||||
import { useSettingsStore } from '../../store/settingsStore';
|
import { useSettingsStore } from '../../store/settingsStore';
|
||||||
import { useTripStore } from '../../store/tripStore';
|
import { useTripStore } from '../../store/tripStore';
|
||||||
|
import type { Reservation } from '../../types';
|
||||||
|
import { tourPlannedTimes } from '../Tours/tourPresentation';
|
||||||
import DayPlanSidebar from './DayPlanSidebar';
|
import DayPlanSidebar from './DayPlanSidebar';
|
||||||
// ── Hoisted mock state (accessible in vi.mock factories) ────────────────────
|
// ── Hoisted mock state (accessible in vi.mock factories) ────────────────────
|
||||||
const mockDayNotesState = vi.hoisted(() => ({
|
const mockDayNotesState = vi.hoisted(() => ({
|
||||||
@@ -56,12 +68,14 @@ vi.mock('../Map/RouteCalculator', () => ({
|
|||||||
generateGoogleMapsUrl: vi.fn().mockReturnValue('https://maps.google.com/...'),
|
generateGoogleMapsUrl: vi.fn().mockReturnValue('https://maps.google.com/...'),
|
||||||
generateCoMapsUrl: vi.fn().mockReturnValue('https://comaps.at/...'),
|
generateCoMapsUrl: vi.fn().mockReturnValue('https://comaps.at/...'),
|
||||||
optimizeRoute: vi.fn().mockImplementation((places) => places),
|
optimizeRoute: vi.fn().mockImplementation((places) => places),
|
||||||
// One leg per waypoint gap; the connector between two stops reads distanceText.
|
// One leg per waypoint gap, carrying its two ends as the real one does; the connector between two stops reads distanceText.
|
||||||
calculateRouteWithLegs: vi.fn().mockImplementation((waypoints) =>
|
calculateRouteWithLegs: vi.fn().mockImplementation((waypoints: { lat: number; lng: number }[] = []) =>
|
||||||
Promise.resolve({
|
Promise.resolve({
|
||||||
distanceText: '2 km',
|
distanceText: '2 km',
|
||||||
durationText: '10 min',
|
durationText: '10 min',
|
||||||
legs: Array.from({ length: Math.max(0, (waypoints?.length ?? 0) - 1) }, () => ({
|
legs: waypoints.slice(1).map((to, index) => ({
|
||||||
|
from: [waypoints[index]?.lat, waypoints[index]?.lng],
|
||||||
|
to: [to.lat, to.lng],
|
||||||
distanceText: '2 km',
|
distanceText: '2 km',
|
||||||
durationText: '10 min',
|
durationText: '10 min',
|
||||||
drivingText: '10 min',
|
drivingText: '10 min',
|
||||||
@@ -71,6 +85,13 @@ vi.mock('../Map/RouteCalculator', () => ({
|
|||||||
),
|
),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
// CW-08: a walk's stops are read for the names of a transit leg's two ends.
|
||||||
|
const mockTourDetail = vi.hoisted(() => vi.fn());
|
||||||
|
vi.mock('../../repo/tourRepo', async (importOriginal) => {
|
||||||
|
const actual = await importOriginal<typeof import('../../repo/tourRepo')>();
|
||||||
|
return { ...actual, tourRepo: { ...actual.tourRepo, detail: mockTourDetail } };
|
||||||
|
});
|
||||||
|
|
||||||
// PlaceAvatar needs IntersectionObserver
|
// PlaceAvatar needs IntersectionObserver
|
||||||
class MockIO {
|
class MockIO {
|
||||||
observe = vi.fn();
|
observe = vi.fn();
|
||||||
@@ -160,7 +181,15 @@ describe('DayPlanSidebar', () => {
|
|||||||
const place = buildPlace({ id: 45, name: 'Ridge walk', description, tour_place_id: 45 });
|
const place = buildPlace({ id: 45, name: 'Ridge walk', description, tour_place_id: 45 });
|
||||||
const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' });
|
const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' });
|
||||||
const assignment = buildAssignment({ id: 101, day_id: 10, order_index: 0, place });
|
const assignment = buildAssignment({ id: 101, day_id: 10, order_index: 0, place });
|
||||||
const times = { walkingMinutes: 60, breakMinutes: 35, plannedTotalMinutes: 95, manuallyOverridden: false };
|
const times = {
|
||||||
|
walkingMinutes: 60,
|
||||||
|
breakMinutes: 35,
|
||||||
|
plannedTotalMinutes: 95,
|
||||||
|
manuallyOverridden: false,
|
||||||
|
walk: null,
|
||||||
|
atLeast: false,
|
||||||
|
estimate: null,
|
||||||
|
};
|
||||||
const props = makeDefaultProps({
|
const props = makeDefaultProps({
|
||||||
days: [day],
|
days: [day],
|
||||||
places: [place],
|
places: [place],
|
||||||
@@ -189,6 +218,22 @@ describe('DayPlanSidebar', () => {
|
|||||||
);
|
);
|
||||||
expect(screen.getByTestId('trip-plan-tour-planned-duration')).toHaveTextContent('Manual override');
|
expect(screen.getByTestId('trip-plan-tour-planned-duration')).toHaveTextContent('Manual override');
|
||||||
|
|
||||||
|
// CW-02: a city walk whose stay is not entered yet plans at least its known total.
|
||||||
|
view.rerender(
|
||||||
|
<DayPlanSidebar
|
||||||
|
{...{
|
||||||
|
...props,
|
||||||
|
plannedTourDurations: new Map([
|
||||||
|
[place.id, { ...times, breakMinutes: null, plannedTotalMinutes: 135, atLeast: true }],
|
||||||
|
]),
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
const walkTotal = screen.getByTestId('trip-plan-tour-planned-duration');
|
||||||
|
expect(walkTotal).toHaveTextContent('Planned: ≥ 2 h 15 min');
|
||||||
|
expect(walkTotal).toHaveAccessibleName('Planned total duration: at least 2 h 15 min');
|
||||||
|
expect(screen.queryByTestId('trip-plan-tour-breaks')).not.toBeInTheDocument();
|
||||||
|
|
||||||
useAddonStore.setState({ addons: [{ id: 'tours', name: 'Tours', type: 'trip', icon: '', enabled: false }] });
|
useAddonStore.setState({ addons: [{ id: 'tours', name: 'Tours', type: 'trip', icon: '', enabled: false }] });
|
||||||
view.rerender(<DayPlanSidebar {...props} />);
|
view.rerender(<DayPlanSidebar {...props} />);
|
||||||
expect(view.container.querySelector('[data-testid="trip-plan-tour-description"]')).toBeNull();
|
expect(view.container.querySelector('[data-testid="trip-plan-tour-description"]')).toBeNull();
|
||||||
@@ -278,7 +323,10 @@ describe('DayPlanSidebar', () => {
|
|||||||
render(<DayPlanSidebar {...props} />);
|
render(<DayPlanSidebar {...props} />);
|
||||||
|
|
||||||
expect(screen.getByTestId('plan-tour-icon').querySelector('.lucide-mountain')).toBeTruthy();
|
expect(screen.getByTestId('plan-tour-icon').querySelector('.lucide-mountain')).toBeTruthy();
|
||||||
expect(screen.queryByTestId('trip-plan-tour-time')).not.toBeInTheDocument();
|
// TIME-01: without a time of its own the import shows its estimate, worked out from its measures.
|
||||||
|
const time = screen.getByTestId('trip-plan-tour-time');
|
||||||
|
expect(time).toHaveTextContent('≈ 2 h 21 min');
|
||||||
|
expect(time).toHaveAccessibleName(expect.stringContaining('Estimated time: 2 h 21 min'));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('RC-01: a tour row offers no booking, a tour is not booked', () => {
|
it('RC-01: a tour row offers no booking, a tour is not booked', () => {
|
||||||
@@ -305,3 +353,235 @@ describe('DayPlanSidebar', () => {
|
|||||||
expect(screen.getAllByRole('button', { name: 'Add booking' })).toHaveLength(1);
|
expect(screen.getAllByRole('button', { name: 'Add booking' })).toHaveLength(1);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// CW-08: the old town walk ends at the bridge, the harbour walk starts at the fish market.
|
||||||
|
const TOURS_ON = [{ id: 'tours', name: 'Tours', type: 'trip', icon: '', enabled: true }];
|
||||||
|
const oldTown = buildPlace({
|
||||||
|
id: 51,
|
||||||
|
name: 'Old town',
|
||||||
|
tour_place_id: 51,
|
||||||
|
lat: 52.52,
|
||||||
|
lng: 13.4,
|
||||||
|
route_geometry: '[[52.52,13.4],[52.515,13.41],[52.51,13.42]]',
|
||||||
|
});
|
||||||
|
const harbour = buildPlace({
|
||||||
|
id: 52,
|
||||||
|
name: 'Harbour',
|
||||||
|
tour_place_id: 52,
|
||||||
|
lat: 52.5,
|
||||||
|
lng: 13.45,
|
||||||
|
route_geometry: '[[52.5,13.45],[52.49,13.46]]',
|
||||||
|
});
|
||||||
|
const cafe = buildPlace({ id: 53, name: 'Corner cafe', lat: 52.48, lng: 13.47 });
|
||||||
|
|
||||||
|
function walkTour(place: { id: number; name: string }, overrides: Partial<TourListItem> = {}): TourListItem {
|
||||||
|
return {
|
||||||
|
place_id: place.id,
|
||||||
|
name: place.name,
|
||||||
|
tour_type: 'walk',
|
||||||
|
distance: 3,
|
||||||
|
elevation_gain: null,
|
||||||
|
elevation_loss: null,
|
||||||
|
duration: 90,
|
||||||
|
break_additional_minutes: null,
|
||||||
|
planned_duration_minutes: null,
|
||||||
|
difficulty: null,
|
||||||
|
wanderer_ref: null,
|
||||||
|
match_confidence: 1,
|
||||||
|
max_hiking_difficulty: null,
|
||||||
|
planned: true,
|
||||||
|
caution: false,
|
||||||
|
station_count: 2,
|
||||||
|
station_stay_minutes: 45,
|
||||||
|
station_stays_unknown: 0,
|
||||||
|
...overrides,
|
||||||
|
} as TourListItem;
|
||||||
|
}
|
||||||
|
|
||||||
|
function walkDayProps(extra: {
|
||||||
|
reservations?: Reservation[];
|
||||||
|
withCafe?: boolean;
|
||||||
|
onPlanTransitLeg?: () => void;
|
||||||
|
firstWalk?: Partial<TourListItem>;
|
||||||
|
}) {
|
||||||
|
const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' });
|
||||||
|
const assignments = {
|
||||||
|
'10': [
|
||||||
|
buildAssignment({
|
||||||
|
id: 201,
|
||||||
|
day_id: 10,
|
||||||
|
order_index: 0,
|
||||||
|
tour_place_id: 51,
|
||||||
|
place: { ...oldTown, place_time: '10:00' },
|
||||||
|
}),
|
||||||
|
buildAssignment({
|
||||||
|
id: 202,
|
||||||
|
day_id: 10,
|
||||||
|
order_index: 1,
|
||||||
|
tour_place_id: 52,
|
||||||
|
place: { ...harbour, place_time: '13:00' },
|
||||||
|
}),
|
||||||
|
...(extra.withCafe ? [buildAssignment({ id: 203, day_id: 10, order_index: 2, place: cafe })] : []),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const tours = [walkTour(oldTown, extra.firstWalk), walkTour(harbour)];
|
||||||
|
return makeDefaultProps({
|
||||||
|
days: [day],
|
||||||
|
places: [oldTown, harbour, cafe],
|
||||||
|
assignments,
|
||||||
|
selectedDayId: 10,
|
||||||
|
routeShown: true,
|
||||||
|
tourPlaceIds: new Set([51, 52]),
|
||||||
|
plannedTourDurations: new Map(tours.map((tour) => [tour.place_id, { ...tourPlannedTimes(tour), tour }])),
|
||||||
|
reservations: extra.reservations ?? [],
|
||||||
|
onPlanTransitLeg: extra.onPlanTransitLeg,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A journey saved from the old town walk's end to the harbour walk's start, arriving at `arrives`. */
|
||||||
|
function savedJourney(arrives: string): Reservation {
|
||||||
|
return {
|
||||||
|
...buildReservation({
|
||||||
|
id: 300,
|
||||||
|
type: 'transit',
|
||||||
|
title: 'Old bridge → Fish market',
|
||||||
|
reservation_time: '2025-06-01T12:20',
|
||||||
|
reservation_end_time: `2025-06-01T${arrives}`,
|
||||||
|
day_id: 10,
|
||||||
|
}),
|
||||||
|
endpoints: [
|
||||||
|
{
|
||||||
|
role: 'from',
|
||||||
|
sequence: 0,
|
||||||
|
name: 'Old bridge',
|
||||||
|
lat: 52.51,
|
||||||
|
lng: 13.42,
|
||||||
|
local_date: '2025-06-01',
|
||||||
|
local_time: '12:20',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
role: 'to',
|
||||||
|
sequence: 1,
|
||||||
|
name: 'Fish market',
|
||||||
|
lat: 52.5,
|
||||||
|
lng: 13.45,
|
||||||
|
local_date: '2025-06-01',
|
||||||
|
local_time: arrives,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
metadata: {
|
||||||
|
transit: {
|
||||||
|
provider: 'transitous',
|
||||||
|
duration: 1800,
|
||||||
|
transfers: 0,
|
||||||
|
legs: [{ mode: 'TRAM', line: 'M1', duration: 1500 }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as unknown as Reservation;
|
||||||
|
}
|
||||||
|
|
||||||
|
function contextMenu() {
|
||||||
|
return within(document.querySelector('[style*="z-index: 999999"]') as HTMLElement);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('DayPlanSidebar, public transit between two city walks (CW-08)', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
useAddonStore.setState({ addons: TOURS_ON });
|
||||||
|
mockTourDetail.mockImplementation((_tripId: number, placeId: number) =>
|
||||||
|
Promise.resolve({
|
||||||
|
tour: walkTour(placeId === 51 ? oldTown : harbour),
|
||||||
|
waypoints:
|
||||||
|
placeId === 51
|
||||||
|
? [
|
||||||
|
{ lat: 52.52, lng: 13.4, role: 'start', sequence: 0, key: 'a1', name: 'Town hall', stay_minutes: 30 },
|
||||||
|
{ lat: 52.51, lng: 13.42, role: 'end', sequence: 1, key: 'a2', name: 'Old bridge', stay_minutes: 15 },
|
||||||
|
]
|
||||||
|
: [
|
||||||
|
{ lat: 52.5, lng: 13.45, role: 'start', sequence: 0, key: 'b1', name: 'Fish market' },
|
||||||
|
{ lat: 52.49, lng: 13.46, role: 'end', sequence: 1, key: 'b2', name: 'Lighthouse' },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('CW-08: the connector between two walks opens the search from the last stop to the first, when the first walk ends', async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
const onPlanTransitLeg = vi.fn();
|
||||||
|
render(<DayPlanSidebar {...walkDayProps({ onPlanTransitLeg })} />);
|
||||||
|
|
||||||
|
await user.click(await screen.findByLabelText('Change travel mode'));
|
||||||
|
await user.click(contextMenu().getByRole('button', { name: 'Public transit' }));
|
||||||
|
|
||||||
|
// The walk's end at 10:00 plus 90 min walking and 45 min of stays; nothing is saved.
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(onPlanTransitLeg).toHaveBeenCalledWith({
|
||||||
|
dayId: 10,
|
||||||
|
from: { name: 'Old bridge', lat: 52.51, lng: 13.42 },
|
||||||
|
to: { name: 'Fish market', lat: 52.5, lng: 13.45 },
|
||||||
|
time: '12:15',
|
||||||
|
walk: {
|
||||||
|
dayId: 10,
|
||||||
|
fromWalk: 'Old town',
|
||||||
|
toWalk: 'Harbour',
|
||||||
|
ends: '12:15',
|
||||||
|
endsNextDay: false,
|
||||||
|
endsAtLeast: false,
|
||||||
|
nextStarts: '13:00',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
);
|
||||||
|
expect(mockTourDetail).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('CW-08: a leg from a walk to a place keeps the search as for any leg, and reads no stops', async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
const onPlanTransitLeg = vi.fn();
|
||||||
|
render(<DayPlanSidebar {...walkDayProps({ onPlanTransitLeg, withCafe: true })} />);
|
||||||
|
|
||||||
|
const connectors = await screen.findAllByLabelText('Change travel mode');
|
||||||
|
expect(connectors).toHaveLength(2);
|
||||||
|
await user.click(connectors[1]);
|
||||||
|
await user.click(contextMenu().getByRole('button', { name: 'Public transit' }));
|
||||||
|
|
||||||
|
expect(onPlanTransitLeg).toHaveBeenCalledWith({
|
||||||
|
dayId: 10,
|
||||||
|
from: { name: '', lat: 52.49, lng: 13.46 },
|
||||||
|
to: { name: 'Corner cafe', lat: 52.48, lng: 13.47 },
|
||||||
|
time: null,
|
||||||
|
});
|
||||||
|
expect(mockTourDetail).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('CW-08: a journey saved at the walks’ ends adds no walk of nothing on either side of it', async () => {
|
||||||
|
render(<DayPlanSidebar {...walkDayProps({ withCafe: true, reservations: [savedJourney('12:50')] })} />);
|
||||||
|
|
||||||
|
// The only leg left is the one from the harbour walk to the cafe; the journey covers the rest.
|
||||||
|
await screen.findByLabelText('Change travel mode');
|
||||||
|
expect(screen.getAllByLabelText('Change travel mode')).toHaveLength(1);
|
||||||
|
expect(screen.queryByTestId('transit-walk-late')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('CW-08: a saved journey that now arrives after the next walk starts says so, and changes nothing', () => {
|
||||||
|
const onPlanTransitLeg = vi.fn();
|
||||||
|
render(<DayPlanSidebar {...walkDayProps({ onPlanTransitLeg, reservations: [savedJourney('13:10')] })} />);
|
||||||
|
|
||||||
|
expect(screen.getByTestId('transit-walk-late')).toHaveTextContent('Arrives after Harbour starts at 13:00');
|
||||||
|
expect(onPlanTransitLeg).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('TIME-02-017: a tour with a start shows its end worked out from its time, and nothing runs over', () => {
|
||||||
|
render(<DayPlanSidebar {...walkDayProps({})} />);
|
||||||
|
|
||||||
|
const ends = screen.getAllByTestId('tour-day-end-worked-out');
|
||||||
|
expect(ends[0]).toHaveTextContent('12:15');
|
||||||
|
expect(ends[0]).toHaveAccessibleName('Ends at 12:15, worked out from the start and the tour time of 2 h 15 min');
|
||||||
|
expect(screen.queryByTestId('tour-day-overrun')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('TIME-02-018: an end that runs past the start of the next timed item is said under the tour, nothing moved', () => {
|
||||||
|
render(<DayPlanSidebar {...walkDayProps({ firstWalk: { planned_duration_minutes: 240 } })} />);
|
||||||
|
|
||||||
|
expect(screen.getAllByTestId('tour-day-end-worked-out')[0]).toHaveTextContent('14:00');
|
||||||
|
expect(screen.getByTestId('tour-day-overrun')).toHaveTextContent('Ends at 14:00, after Harbour starts at 13:00');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -8,8 +8,11 @@ import React, { useState, useEffect, useLayoutEffect, useRef, useMemo, useCallba
|
|||||||
import { avatarSrc } from '../../utils/avatarSrc'
|
import { avatarSrc } from '../../utils/avatarSrc'
|
||||||
import { safeHttpUrl } from '../../utils/safeUrl'
|
import { safeHttpUrl } from '../../utils/safeUrl'
|
||||||
import { ChevronDown, ChevronRight, ChevronUp, Compass, RotateCcw, ExternalLink, Pencil, GripVertical, Ticket, Plus, FileText, Trash2, Car, Lock, Hotel, Eraser, Route as RouteIcon, RouteOff, Bookmark, StickyNote, TramFront, Zap, MapPin, Globe } from 'lucide-react'
|
import { ChevronDown, ChevronRight, ChevronUp, Compass, RotateCcw, ExternalLink, Pencil, GripVertical, Ticket, Plus, FileText, Trash2, Car, Lock, Hotel, Eraser, Route as RouteIcon, RouteOff, Bookmark, StickyNote, TramFront, Zap, MapPin, Globe } from 'lucide-react'
|
||||||
import { type PickedPlace } from './TransitSearchPanel'
|
import type { PlannedTransitLeg } from './transitLeg'
|
||||||
import { buildTransitLeg, buildTransitNameIndex } from './transitLeg'
|
import { useTransitLegPlanner } from './useTransitLegPlanner'
|
||||||
|
import { WalkLateLine } from '../Tours/walk/WalkTransitNote'
|
||||||
|
import { TourOverrunLine } from '../Tours/TourDayTimeParts'
|
||||||
|
import { dayItemOverrun } from '../Tours/tourDayTime'
|
||||||
import { optimizeRoute, generateGoogleMapsUrl, generateCoMapsUrl } from '../Map/RouteCalculator'
|
import { optimizeRoute, generateGoogleMapsUrl, generateCoMapsUrl } from '../Map/RouteCalculator'
|
||||||
import { dayViaLookup, type ViasByDay } from '../../utils/dayRouteVias'
|
import { dayViaLookup, type ViasByDay } from '../../utils/dayRouteVias'
|
||||||
import { routeLeg, type LegEnd } from '../Map/dayRouteLeg'
|
import { routeLeg, type LegEnd } from '../Map/dayRouteLeg'
|
||||||
@@ -36,10 +39,6 @@ import { NEUTRAL_TINT, fs } from '../shared/DialogShell'
|
|||||||
import { BarButton, MoreButton, SoftPill, TimePill, tintOf } from './planParts'
|
import { BarButton, MoreButton, SoftPill, TimePill, tintOf } from './planParts'
|
||||||
import './dayPlanRows.css'
|
import './dayPlanRows.css'
|
||||||
|
|
||||||
/** The round white button a row carries on its right (a route on the map, a journey's legs). */
|
|
||||||
const ROW_ROUND = 'grid flex-none place-items-center rounded-full bg-surface-card shadow-sm transition-colors'
|
|
||||||
/** The white face every control of a day's route bar shares, so the row reads as one set. */
|
|
||||||
const ROUTE_TOOL = 'bg-surface-card shadow-sm ring-1 ring-edge-faint'
|
|
||||||
import { TypeTile } from './bookings/bookingParts'
|
import { TypeTile } from './bookings/bookingParts'
|
||||||
import { typeInfo } from './bookings/bookingsModel'
|
import { typeInfo } from './bookings/bookingsModel'
|
||||||
import { dayHeadStays } from './dayHeadStays'
|
import { dayHeadStays } from './dayHeadStays'
|
||||||
@@ -68,7 +67,8 @@ import { RouteConnector, HotelRouteConnector } from './DayPlanSidebarRouteConnec
|
|||||||
import { resolveLegMode } from './legMode'
|
import { resolveLegMode } from './legMode'
|
||||||
import { useLegModeActions } from './useLegModeActions'
|
import { useLegModeActions } from './useLegModeActions'
|
||||||
import { dayExportStops, fillAroundLocked } from './dayRoute'
|
import { dayExportStops, fillAroundLocked } from './dayRoute'
|
||||||
import { projectDayItinerary } from '../Map/dayTourProjection'
|
import { projectDayItinerary, projectedById, type TourStageStops } from '../Map/dayTourProjection'
|
||||||
|
import type { DayRoutePoint } from '../Map/dayRoutePlan'
|
||||||
import { usePluginDaySchedule, usePluginDayTints, dayTintBackground, dayTinted, PluginDayScheduleRow, formatScheduleMinutes } from '../Plugins/PluginDaySchedule'
|
import { usePluginDaySchedule, usePluginDayTints, dayTintBackground, dayTinted, PluginDayScheduleRow, formatScheduleMinutes } from '../Plugins/PluginDaySchedule'
|
||||||
import { MobileAddPlaceButton } from './DayPlanSidebarMobileAddPlaceButton'
|
import { MobileAddPlaceButton } from './DayPlanSidebarMobileAddPlaceButton'
|
||||||
import { DayPlanSidebarToolbar } from './DayPlanSidebarToolbar'
|
import { DayPlanSidebarToolbar } from './DayPlanSidebarToolbar'
|
||||||
@@ -85,6 +85,7 @@ import type { TourPlannedTimes } from '../Tours/tourPresentation'
|
|||||||
import type { TourListItem } from '@trek/shared'
|
import type { TourListItem } from '@trek/shared'
|
||||||
import { TourDayRowAvatar } from '../Tours/TourDayRowFacts'
|
import { TourDayRowAvatar } from '../Tours/TourDayRowFacts'
|
||||||
import { DayPlanPlaceSubline } from './DayPlanPlaceSubline'
|
import { DayPlanPlaceSubline } from './DayPlanPlaceSubline'
|
||||||
|
import { DAY_HEAD_DROP, DAY_HEAD_HOVER, DAY_HEAD_SELECTED, LOCK_OVERLAY, LOCK_OVERLAY_HOVER, LOCKED_ROW, ROUTE_TOOL, ROW_ROUND } from './dayPlanSurfaces'
|
||||||
|
|
||||||
export interface DayPlanSidebarProps {
|
export interface DayPlanSidebarProps {
|
||||||
tripId: number
|
tripId: number
|
||||||
@@ -93,6 +94,8 @@ export interface DayPlanSidebarProps {
|
|||||||
places: Place[]
|
places: Place[]
|
||||||
tourPlaceIds?: ReadonlySet<number>
|
tourPlaceIds?: ReadonlySet<number>
|
||||||
plannedTourDurations?: ReadonlyMap<number, TourPlannedTimes & { tour?: TourListItem }>
|
plannedTourDurations?: ReadonlyMap<number, TourPlannedTimes & { tour?: TourListItem }>
|
||||||
|
/** MDT-02: where the stages of the trip's multi-day tours run, so a day holding one routes to that stage. */
|
||||||
|
tourStageStops?: TourStageStops
|
||||||
categories: Category[]
|
categories: Category[]
|
||||||
assignments: AssignmentsMap
|
assignments: AssignmentsMap
|
||||||
selectedDayId: number | null
|
selectedDayId: number | null
|
||||||
@@ -161,8 +164,9 @@ export interface DayPlanSidebarProps {
|
|||||||
* Opens the public-transit search pre-filled for a single leg (#1281 follow-up):
|
* Opens the public-transit search pre-filled for a single leg (#1281 follow-up):
|
||||||
* the leg's origin and destination endpoints plus the origin's departure time,
|
* the leg's origin and destination endpoints plus the origin's departure time,
|
||||||
* so "public transport" becomes an option on any connector, not just the day header.
|
* so "public transport" becomes an option on any connector, not just the day header.
|
||||||
|
* Between two city walks it carries what the search says of them (CW-08).
|
||||||
*/
|
*/
|
||||||
onPlanTransitLeg?: (leg: { dayId: number; from: PickedPlace; to: PickedPlace; time: string | null }) => void
|
onPlanTransitLeg?: (leg: PlannedTransitLeg) => void
|
||||||
/** Opens the journey view for a saved transit entry (#1065). */
|
/** Opens the journey view for a saved transit entry (#1065). */
|
||||||
onOpenTransit?: (reservation: Reservation) => void
|
onOpenTransit?: (reservation: Reservation) => void
|
||||||
onEditTransport?: (reservation: Reservation) => void
|
onEditTransport?: (reservation: Reservation) => void
|
||||||
@@ -187,16 +191,6 @@ export interface DayPlanSidebarProps {
|
|||||||
* days (places, transports, notes). Returns everything the timeline view renders
|
* days (places, transports, notes). Returns everything the timeline view renders
|
||||||
* from, keeping DayPlanSidebar a thin shell over one large day list.
|
* from, keeping DayPlanSidebar a thin shell over one large day list.
|
||||||
*/
|
*/
|
||||||
// The day head's tones: hovered, open, and a drop landing on it. Mixed from the
|
|
||||||
// accent so they follow the user's scheme in both themes.
|
|
||||||
const DAY_HEAD_HOVER = 'color-mix(in srgb, var(--accent) 10%, transparent)'
|
|
||||||
const DAY_HEAD_SELECTED = 'color-mix(in srgb, var(--accent) 12%, transparent)'
|
|
||||||
const DAY_HEAD_DROP = 'color-mix(in srgb, var(--accent) 9%, transparent)'
|
|
||||||
// A stop pinned in place: a whisper of the danger tone on the row, a stronger one over its avatar.
|
|
||||||
const LOCKED_ROW = 'color-mix(in srgb, var(--danger) 7%, transparent)'
|
|
||||||
const LOCK_OVERLAY = 'color-mix(in srgb, var(--danger) 62%, transparent)'
|
|
||||||
const LOCK_OVERLAY_HOVER = 'color-mix(in srgb, var(--danger) 42%, transparent)'
|
|
||||||
|
|
||||||
function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
||||||
const {
|
const {
|
||||||
tripId,
|
tripId,
|
||||||
@@ -619,12 +613,12 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
|||||||
// legs to draw. Side-effect free, so the async loop below only does OSRM I/O.
|
// legs to draw. Side-effect free, so the async loop below only does OSRM I/O.
|
||||||
const planDay = (dayId: number) => {
|
const planDay = (dayId: number) => {
|
||||||
const merged = mergedItemsMap[dayId] || []
|
const merged = mergedItemsMap[dayId] || []
|
||||||
const projected = new Map(projectDayItinerary(assignments[String(dayId)] || [], toursEnabled, places).map(item => [item.assignment.id, item]))
|
const projected = projectedById(assignments[String(dayId)] || [], toursEnabled, places, props.tourStageStops)
|
||||||
// Each run point carries the ORIGIN assignment's per-segment travel mode
|
// Each run point carries the ORIGIN assignment's per-segment travel mode
|
||||||
// (#1281): the leg from this point to the next is routed with `mode` (null =
|
// (#1281): the leg from this point to the next is routed with `mode` (null =
|
||||||
// inherit the day default). Transport endpoints carry no mode → day default.
|
// inherit the day default). Transport endpoints carry no mode → day default.
|
||||||
const runs: { id: number; lat: number; lng: number; isPlace: boolean; leg_transport_mode?: string | null; incoming_leg_transport_mode?: string | null; assignmentId?: number }[][] = []
|
const runs: (DayRoutePoint & { id: number })[][] = []
|
||||||
let cur: { id: number; lat: number; lng: number; isPlace: boolean; leg_transport_mode?: string | null; incoming_leg_transport_mode?: string | null; assignmentId?: number }[] = []
|
let cur: (DayRoutePoint & { id: number })[] = []
|
||||||
// A run is only a real drive when it holds an actual place. Two back-to-back
|
// A run is only a real drive when it holds an actual place. Two back-to-back
|
||||||
// transports (e.g. two flights on one day) would otherwise pair the first's
|
// transports (e.g. two flights on one day) would otherwise pair the first's
|
||||||
// arrival with the second's departure into a phantom airport→airport leg — the
|
// arrival with the second's departure into a phantom airport→airport leg — the
|
||||||
@@ -789,6 +783,8 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
|||||||
for (let i = 0; i < run.length - 1; i++) {
|
for (let i = 0; i < run.length - 1; i++) {
|
||||||
const from = run[i]
|
const from = run[i]
|
||||||
const to = run[i + 1]
|
const to = run[i + 1]
|
||||||
|
// A booking whose station is the stop itself leaves a leg that goes nowhere, as on the phone (CW-08).
|
||||||
|
if ((!from.isPlace || !to.isPlace) && from.lat === to.lat && from.lng === to.lng) continue
|
||||||
const mode = resolveLegMode(from, to, dfMode)
|
const mode = resolveLegMode(from, to, dfMode)
|
||||||
tasks.push(async () => {
|
tasks.push(async () => {
|
||||||
const seg = await legBetween(from, to, dayId, mode)
|
const seg = await legBetween(from, to, dayId, mode)
|
||||||
@@ -836,7 +832,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
|||||||
// routeDayIds is memoized from the same inputs as routeDayKey below, so keying the
|
// routeDayIds is memoized from the same inputs as routeDayKey below, so keying the
|
||||||
// effect on the string is equivalent while staying stable across unrelated renders.
|
// effect on the string is equivalent while staying stable across unrelated renders.
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [routeDayKey, routeProfile, mergedItemsMap, accommodations, days, optimizeFromAccommodation, distanceUnit, toursEnabled, places, roadtripViasByDay])
|
}, [routeDayKey, routeProfile, mergedItemsMap, accommodations, days, optimizeFromAccommodation, distanceUnit, toursEnabled, places, roadtripViasByDay, props.tourStageStops])
|
||||||
|
|
||||||
const openAddNote = (dayId, e) => {
|
const openAddNote = (dayId, e) => {
|
||||||
e?.stopPropagation()
|
e?.stopPropagation()
|
||||||
@@ -1405,26 +1401,20 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Coordinates back to names for the transit search, over every located place,
|
// The extra connector-menu entry (#1281 follow-up): public transit for this leg while a handler is wired (day has
|
||||||
// hotel and booking endpoint on the trip (see transitLeg.ts).
|
// dates); between two city walks from the end of the one it leaves, `originId`, as two can end at one spot (CW-08).
|
||||||
const transitNameIndex = useMemo(
|
const tourOfPlace = (placeId: number) => props.plannedTourDurations?.get(placeId)?.tour
|
||||||
() => buildTransitNameIndex(assignments, accommodations, reservations),
|
const transitLegs = useTransitLegPlanner({ tripId, assignments, accommodations, reservations, places, toursEnabled,
|
||||||
[assignments, accommodations, reservations],
|
onPlan: onPlanTransitLeg, tourOf: tourOfPlace })
|
||||||
)
|
const transitLegPlanner = (dayId: number, seg?: RouteSegment, originId?: number) => {
|
||||||
|
const leg = transitLegs.legFor(dayId, seg)
|
||||||
// The extra connector-menu entry (#1281 follow-up): search public transit for this
|
return leg ? () => transitLegs.plan(dayId, leg, originId) : undefined
|
||||||
// leg instead of drawing a road route. Only when a handler is wired (day has dates).
|
|
||||||
const transitLegPlanner = (dayId: number, seg?: RouteSegment) => {
|
|
||||||
if (!onPlanTransitLeg) return undefined
|
|
||||||
const leg = buildTransitLeg(seg, dayId, transitNameIndex, assignments, reservations)
|
|
||||||
if (!leg) return undefined
|
|
||||||
return () => onPlanTransitLeg({ dayId, from: leg.from, to: leg.to, time: leg.time })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Open the mode menu at the clicked connector: every route profile, the optional
|
// Open the mode menu at the clicked connector: every route profile, the optional
|
||||||
// "public transport" entry, plus a "use day default" entry that clears the override.
|
// "public transport" entry, plus a "use day default" entry that clears the override.
|
||||||
const openLegModeMenu = (e: React.MouseEvent, assignmentId: number, dayId: number, seg?: RouteSegment) => {
|
const openLegModeMenu = (e: React.MouseEvent, assignmentId: number, dayId: number, seg?: RouteSegment) => {
|
||||||
ctxMenu.open(e, legModeMenu(mode => setLegMode(assignmentId, dayId, mode), transitLegPlanner(dayId, seg)))
|
ctxMenu.open(e, legModeMenu(m => setLegMode(assignmentId, dayId, m), transitLegPlanner(dayId, seg, assignmentId)))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set the mode of the leg ENTERING this stop (a booking arrival or the morning
|
// Set the mode of the leg ENTERING this stop (a booking arrival or the morning
|
||||||
@@ -2033,7 +2023,9 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
|||||||
</Tooltip>
|
</Tooltip>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<DayPlanPlaceSubline place={place} cat={cat} tourTimes={tourTimes} isTourPlace={!!isTourPlace} timeFormat={timeFormat} />
|
<DayPlanPlaceSubline place={place} cat={cat} tourTimes={tourTimes} isTourPlace={!!isTourPlace} timeFormat={timeFormat} assignmentId={assignment.id} tourStageKey={assignment.tour_stage_key} />
|
||||||
|
{/* TIME-02: the tour's end runs past the start of the day's next timed item. */}
|
||||||
|
{dayRowTour && <TourOverrunLine overrun={dayItemOverrun(merged, idx, day.id, tourOfPlace)} />}
|
||||||
{assignment.notes && (
|
{assignment.notes && (
|
||||||
// Day-specific note on this stop (#2163) — one muted
|
// Day-specific note on this stop (#2163) — one muted
|
||||||
// caption line so the timeline shows the note exists
|
// caption line so the timeline shows the note exists
|
||||||
@@ -2359,6 +2351,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
|||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
})()}
|
})()}
|
||||||
|
<WalkLateLine late={transitLegs.lateBefore(day, res, merged.slice(idx + 1))} />
|
||||||
</div>
|
</div>
|
||||||
{transitMeta && (() => {
|
{transitMeta && (() => {
|
||||||
const expanded = expandedTransitIds.has(res.id)
|
const expanded = expandedTransitIds.has(res.id)
|
||||||
|
|||||||
@@ -11,47 +11,19 @@ import { usePermissionsStore } from '../../store/permissionsStore';
|
|||||||
import { usePluginStore } from '../../store/pluginStore';
|
import { usePluginStore } from '../../store/pluginStore';
|
||||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||||
import { buildUser, buildTrip, buildPlace, buildCategory, buildAssignment } from '../../../tests/helpers/factories';
|
import { buildUser, buildTrip, buildPlace, buildCategory, buildAssignment } from '../../../tests/helpers/factories';
|
||||||
|
import { placeFormProps, seedPlaceFormStores } from '../../../tests/helpers/placeFormSetup';
|
||||||
import PlaceFormModal from './PlaceFormModal';
|
import PlaceFormModal from './PlaceFormModal';
|
||||||
|
|
||||||
// Mock CustomTimePicker so we get a simple text input instead of the portal-heavy UI.
|
// CustomTimePicker as a plain text input, see TimePickerStub.
|
||||||
// The aria props land on the input, as the real picker spreads them onto its own.
|
vi.mock('../shared/CustomTimePicker', async () => ({
|
||||||
vi.mock('../shared/CustomTimePicker', () => ({
|
default: (await import('../../../tests/helpers/placeForm')).TimePickerStub,
|
||||||
default: ({ value, onChange, placeholder, ...aria }: {
|
|
||||||
value: string
|
|
||||||
onChange: (v: string) => void
|
|
||||||
placeholder?: string
|
|
||||||
'aria-label'?: string
|
|
||||||
'aria-describedby'?: string
|
|
||||||
'aria-invalid'?: boolean
|
|
||||||
}) => (
|
|
||||||
<input
|
|
||||||
{...aria}
|
|
||||||
data-testid="time-picker"
|
|
||||||
type="text"
|
|
||||||
value={value}
|
|
||||||
onChange={e => onChange(e.target.value)}
|
|
||||||
placeholder={placeholder ?? '00:00'}
|
|
||||||
/>
|
|
||||||
),
|
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const defaultProps = {
|
const defaultProps = placeFormProps;
|
||||||
isOpen: true,
|
|
||||||
onClose: vi.fn(),
|
|
||||||
onSave: vi.fn(),
|
|
||||||
place: null,
|
|
||||||
prefillCoords: null,
|
|
||||||
tripId: 1,
|
|
||||||
categories: [],
|
|
||||||
onCategoryCreated: vi.fn(),
|
|
||||||
assignmentId: null,
|
|
||||||
dayAssignments: [],
|
|
||||||
};
|
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
resetAllStores();
|
resetAllStores();
|
||||||
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true, hasMapsKey: false });
|
seedPlaceFormStores();
|
||||||
seedStore(useTripStore, { trip: buildTrip({ id: 1 }) });
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('PlaceFormModal', () => {
|
describe('PlaceFormModal', () => {
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
// FE-PLANNER-PLACEFORM-125: the place form of a tour (TIME-02)
|
||||||
|
import type { TourListItem } from '@trek/shared';
|
||||||
|
|
||||||
|
import { buildAssignment, buildPlace } from '../../../tests/helpers/factories';
|
||||||
|
import { placeFormProps, seedPlaceFormStores } from '../../../tests/helpers/placeFormSetup';
|
||||||
|
import { render, screen } from '../../../tests/helpers/render';
|
||||||
|
import { resetAllStores } from '../../../tests/helpers/store';
|
||||||
|
import PlaceFormModal from './PlaceFormModal';
|
||||||
|
|
||||||
|
// CustomTimePicker as a plain text input, see TimePickerStub.
|
||||||
|
vi.mock('../shared/CustomTimePicker', async () => ({
|
||||||
|
default: (await import('../../../tests/helpers/placeForm')).TimePickerStub,
|
||||||
|
}));
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
resetAllStores();
|
||||||
|
seedPlaceFormStores();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('PlaceFormModal for a tour', () => {
|
||||||
|
it('FE-PLANNER-PLACEFORM-125: a tour with a start and no end says below its times the end it works out to (TIME-02)', () => {
|
||||||
|
const place = buildPlace({ id: 7, name: 'Ridge', place_time: '09:00', end_time: null });
|
||||||
|
const assignment = buildAssignment({ id: 42, day_id: 3, place });
|
||||||
|
const tour: TourListItem = {
|
||||||
|
place_id: 7,
|
||||||
|
name: 'Ridge',
|
||||||
|
tour_type: 'hike',
|
||||||
|
distance: 8,
|
||||||
|
elevation_gain: 300,
|
||||||
|
elevation_loss: 300,
|
||||||
|
duration: 150,
|
||||||
|
planned_duration_minutes: null,
|
||||||
|
break_additional_minutes: 30,
|
||||||
|
difficulty: null,
|
||||||
|
wanderer_ref: null,
|
||||||
|
match_confidence: 1,
|
||||||
|
max_hiking_difficulty: 2,
|
||||||
|
planned: true,
|
||||||
|
caution: false,
|
||||||
|
};
|
||||||
|
const { unmount } = render(
|
||||||
|
<PlaceFormModal {...placeFormProps} place={place} assignmentId={42} dayAssignments={[assignment]} tour={tour} />
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId('tour-day-end-hint')).toHaveTextContent(
|
||||||
|
'Left empty, the end is worked out: 12:00, the start plus the tour time of 3 h.'
|
||||||
|
);
|
||||||
|
unmount();
|
||||||
|
render(<PlaceFormModal {...placeFormProps} place={place} assignmentId={42} dayAssignments={[assignment]} />);
|
||||||
|
expect(screen.queryByTestId('tour-day-end-hint')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useState, useEffect, useRef, useMemo, useCallback, useId, type ReactNode } from 'react'
|
import { useState, useEffect, useRef, useMemo, useCallback, useId, type ReactNode } from 'react'
|
||||||
import type { RoadtripStopType } from '@trek/shared'
|
import type { RoadtripStopType, TourListItem } from '@trek/shared'
|
||||||
import NoteFormatToolbar from '../shared/NoteFormatToolbar'
|
import NoteFormatToolbar from '../shared/NoteFormatToolbar'
|
||||||
import { useAuthStore } from '../../store/authStore'
|
import { useAuthStore } from '../../store/authStore'
|
||||||
import { useAddonStore } from '../../store/addonStore'
|
import { useAddonStore } from '../../store/addonStore'
|
||||||
@@ -10,15 +10,14 @@ import CollectionPicker from '../Collections/CollectionPicker'
|
|||||||
import PlaceDetailsColumn from './PlaceDetailsColumn'
|
import PlaceDetailsColumn from './PlaceDetailsColumn'
|
||||||
import { useToast } from '../shared/Toast'
|
import { useToast } from '../shared/Toast'
|
||||||
import { Tooltip } from '../shared/Tooltip'
|
import { Tooltip } from '../shared/Tooltip'
|
||||||
import { Search, Paperclip, X, AlertTriangle, Loader2, Plus, RotateCcw, MapPin, Navigation, LocateFixed, PencilLine } from 'lucide-react'
|
import { Search, Paperclip, X, Loader2, Plus, RotateCcw, MapPin, Navigation, LocateFixed, PencilLine } from 'lucide-react'
|
||||||
import { useTranslation } from '../../i18n'
|
import { useTranslation } from '../../i18n'
|
||||||
import CustomTimePicker from '../shared/CustomTimePicker'
|
|
||||||
import { PlaceContactFields } from './PlaceContactFields'
|
import { PlaceContactFields } from './PlaceContactFields'
|
||||||
import { weekFromPeriods } from './placeHours'
|
import { weekFromPeriods } from './placeHours'
|
||||||
import type { PlaceOpeningHours } from '@trek/shared'
|
import type { PlaceOpeningHours } from '@trek/shared'
|
||||||
import {
|
import {
|
||||||
DEFAULT_FORM, endsBeforeStart, findDuplicatePlace, formPin, mergeResult, parseCoordinatePair, placeEditForm, placeFormPayload,
|
DEFAULT_FORM, endsBeforeStart, findDuplicatePlace, formPin, mergeResult, parseCoordinatePair, placeEditForm, placeFormPayload,
|
||||||
prefillForm, timeCollisions, type PlaceFormData,
|
prefillForm, type PlaceFormData,
|
||||||
} from './PlaceFormModal.helpers'
|
} from './PlaceFormModal.helpers'
|
||||||
import { useNewCategory, usePlaceForm } from './usePlaceForm'
|
import { useNewCategory, usePlaceForm } from './usePlaceForm'
|
||||||
import { usePlaceSearch } from './usePlaceSearch'
|
import { usePlaceSearch } from './usePlaceSearch'
|
||||||
@@ -43,6 +42,7 @@ import {
|
|||||||
import { EditorField, GRID_2, INPUT, LABEL, PANEL, PillSelect, TEXTAREA } from '../shared/dialogParts'
|
import { EditorField, GRID_2, INPUT, LABEL, PANEL, PillSelect, TEXTAREA } from '../shared/dialogParts'
|
||||||
import { SoftPill, tintOf } from './planParts'
|
import { SoftPill, tintOf } from './planParts'
|
||||||
import { WHITE_BUTTON } from './placeDialogParts'
|
import { WHITE_BUTTON } from './placeDialogParts'
|
||||||
|
import { TimeSection } from './PlaceFormTimeSection'
|
||||||
|
|
||||||
// The submit payload mirrors the form, but lat/lng are parsed to numbers and
|
// The submit payload mirrors the form, but lat/lng are parsed to numbers and
|
||||||
// category_id is normalised, plus any files chosen before the place existed.
|
// category_id is normalised, plus any files chosen before the place existed.
|
||||||
@@ -85,6 +85,8 @@ interface PlaceFormModalProps {
|
|||||||
serviceStop?: ServiceStopMode | null
|
serviceStop?: ServiceStopMode | null
|
||||||
/** Road trip mode is on, where a visit's End is when the drive leaves it. */
|
/** Road trip mode is on, where a visit's End is when the drive leaves it. */
|
||||||
roadtripActive?: boolean
|
roadtripActive?: boolean
|
||||||
|
/** TIME-02: the tour this place is, whose end the time fields work out from its start; absent for a plain place. */
|
||||||
|
tour?: TourListItem | null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -469,7 +471,6 @@ const STACK = 'flex flex-col gap-5'
|
|||||||
const FORM_COLUMN = 'flex min-w-0 flex-1 flex-col gap-4'
|
const FORM_COLUMN = 'flex min-w-0 flex-1 flex-col gap-4'
|
||||||
/** A row of the typed-ahead list or of the search results. */
|
/** A row of the typed-ahead list or of the search results. */
|
||||||
const PICK_ROW = 'flex w-full items-center gap-2 rounded-[8px] px-2.5 py-2 text-start'
|
const PICK_ROW = 'flex w-full items-center gap-2 rounded-[8px] px-2.5 py-2 text-start'
|
||||||
const WARNING_BANNER = 'flex items-start gap-1.5 rounded-[10px] bg-warning-soft px-2.5 py-1.5 text-warning'
|
|
||||||
/** The small accent square beside a field that runs its action, sized by the row it sits in. */
|
/** The small accent square beside a field that runs its action, sized by the row it sits in. */
|
||||||
const SIDE_BUTTON = 'grid w-[38px] flex-none place-items-center rounded-[10px] transition-colors disabled:cursor-default disabled:opacity-60'
|
const SIDE_BUTTON = 'grid w-[38px] flex-none place-items-center rounded-[10px] transition-colors disabled:cursor-default disabled:opacity-60'
|
||||||
/**
|
/**
|
||||||
@@ -843,6 +844,7 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
|
|||||||
dayAssignments={S.dayAssignments}
|
dayAssignments={S.dayAssignments}
|
||||||
hasTimeError={hasTimeError}
|
hasTimeError={hasTimeError}
|
||||||
endIsLeave={!!props.roadtripActive}
|
endIsLeave={!!props.roadtripActive}
|
||||||
|
tour={props.tour}
|
||||||
t={t}
|
t={t}
|
||||||
/>
|
/>
|
||||||
<EditorField label={t('places.assignmentNotes')} htmlFor={`${fieldId}-day-notes`}>
|
<EditorField label={t('places.assignmentNotes')} htmlFor={`${fieldId}-day-notes`}>
|
||||||
@@ -1156,61 +1158,3 @@ function PendingFiles({ files, fileRef, onAdd, onRemove, t }: {
|
|||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TimeSectionProps {
|
|
||||||
form: PlaceFormData
|
|
||||||
handleChange: (field: string, value: string) => void
|
|
||||||
assignmentId: number | null
|
|
||||||
dayAssignments: Assignment[]
|
|
||||||
hasTimeError: boolean
|
|
||||||
/** On a road trip the End is when the drive leaves, which the field says. In Days it
|
|
||||||
* stays the plain label it has always been: nothing is scheduled off it there. */
|
|
||||||
endIsLeave: boolean
|
|
||||||
t: Translate
|
|
||||||
}
|
|
||||||
|
|
||||||
function TimeSection({ form, handleChange, assignmentId, dayAssignments, hasTimeError, endIsLeave, t }: TimeSectionProps) {
|
|
||||||
const collisions = useMemo(
|
|
||||||
() => timeCollisions(assignmentId, dayAssignments, form.place_time, form.end_time),
|
|
||||||
[assignmentId, dayAssignments, form.place_time, form.end_time],
|
|
||||||
)
|
|
||||||
const errorId = useId()
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex flex-col gap-2">
|
|
||||||
<div className={GRID_2}>
|
|
||||||
<EditorField label={t('places.startTime')}>
|
|
||||||
<CustomTimePicker
|
|
||||||
value={form.place_time}
|
|
||||||
onChange={v => handleChange('place_time', v)}
|
|
||||||
aria-label={t('places.startTime')}
|
|
||||||
/>
|
|
||||||
</EditorField>
|
|
||||||
<EditorField label={t('places.endTime')} hint={endIsLeave ? t('roadtrip.stop.endIsLeave') : undefined}>
|
|
||||||
<CustomTimePicker
|
|
||||||
value={form.end_time}
|
|
||||||
onChange={v => handleChange('end_time', v)}
|
|
||||||
aria-label={t('places.endTime')}
|
|
||||||
aria-invalid={hasTimeError}
|
|
||||||
aria-describedby={hasTimeError ? errorId : undefined}
|
|
||||||
/>
|
|
||||||
</EditorField>
|
|
||||||
</div>
|
|
||||||
{hasTimeError && (
|
|
||||||
<div id={errorId} className={WARNING_BANNER} style={fs(12, 'body')}>
|
|
||||||
<AlertTriangle size={13} className="mt-0.5 shrink-0" aria-hidden="true" />
|
|
||||||
{t('places.endTimeBeforeStart')}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{collisions.length > 0 && (
|
|
||||||
<div className={WARNING_BANNER} style={fs(12, 'body')}>
|
|
||||||
<AlertTriangle size={13} className="mt-0.5 shrink-0" aria-hidden="true" />
|
|
||||||
<span>
|
|
||||||
{t('places.timeCollision')}{' '}
|
|
||||||
{collisions.map(a => a.place?.name).filter(Boolean).join(', ')}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import type { TourListItem } from '@trek/shared';
|
||||||
|
import { AlertTriangle } from 'lucide-react';
|
||||||
|
import { useId, useMemo } from 'react';
|
||||||
|
|
||||||
|
import type { Assignment } from '../../types';
|
||||||
|
import CustomTimePicker from '../shared/CustomTimePicker';
|
||||||
|
import { EditorField, GRID_2 } from '../shared/dialogParts';
|
||||||
|
import { fs } from '../shared/DialogShell';
|
||||||
|
import { TourEndHint } from '../Tours/TourDayTimeParts';
|
||||||
|
import { timeCollisions, type PlaceFormData } from './PlaceFormModal.helpers';
|
||||||
|
|
||||||
|
type Translate = (key: string, params?: Record<string, string | number>) => string;
|
||||||
|
|
||||||
|
const WARNING_BANNER = 'flex items-start gap-1.5 rounded-[10px] bg-warning-soft px-2.5 py-1.5 text-warning';
|
||||||
|
|
||||||
|
interface TimeSectionProps {
|
||||||
|
form: PlaceFormData;
|
||||||
|
handleChange: (field: string, value: string) => void;
|
||||||
|
assignmentId: number | null;
|
||||||
|
dayAssignments: Assignment[];
|
||||||
|
hasTimeError: boolean;
|
||||||
|
/** On a road trip the End is when the drive leaves, which the field says. In Days it
|
||||||
|
* stays the plain label it has always been: nothing is scheduled off it there. */
|
||||||
|
endIsLeave: boolean;
|
||||||
|
/** TIME-02: the tour this place is, whose end the time fields work out from its start. */
|
||||||
|
tour?: TourListItem | null;
|
||||||
|
t: Translate;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The place form's start and end time, with the warnings about them and a tour's worked-out end. */
|
||||||
|
export function TimeSection({
|
||||||
|
form,
|
||||||
|
handleChange,
|
||||||
|
assignmentId,
|
||||||
|
dayAssignments,
|
||||||
|
hasTimeError,
|
||||||
|
endIsLeave,
|
||||||
|
tour,
|
||||||
|
t,
|
||||||
|
}: TimeSectionProps) {
|
||||||
|
const collisions = useMemo(
|
||||||
|
() => timeCollisions(assignmentId, dayAssignments, form.place_time, form.end_time),
|
||||||
|
[assignmentId, dayAssignments, form.place_time, form.end_time]
|
||||||
|
);
|
||||||
|
const errorId = useId();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<div className={GRID_2}>
|
||||||
|
<EditorField label={t('places.startTime')}>
|
||||||
|
<CustomTimePicker
|
||||||
|
value={form.place_time}
|
||||||
|
onChange={(v) => handleChange('place_time', v)}
|
||||||
|
aria-label={t('places.startTime')}
|
||||||
|
/>
|
||||||
|
</EditorField>
|
||||||
|
<EditorField label={t('places.endTime')} hint={endIsLeave ? t('roadtrip.stop.endIsLeave') : undefined}>
|
||||||
|
<CustomTimePicker
|
||||||
|
value={form.end_time}
|
||||||
|
onChange={(v) => handleChange('end_time', v)}
|
||||||
|
aria-label={t('places.endTime')}
|
||||||
|
aria-invalid={hasTimeError}
|
||||||
|
aria-describedby={hasTimeError ? errorId : undefined}
|
||||||
|
/>
|
||||||
|
</EditorField>
|
||||||
|
</div>
|
||||||
|
<TourEndHint
|
||||||
|
start={form.place_time}
|
||||||
|
end={form.end_time}
|
||||||
|
assignment={dayAssignments.find((a) => a.id === assignmentId)}
|
||||||
|
tour={tour}
|
||||||
|
/>
|
||||||
|
{hasTimeError && (
|
||||||
|
<div id={errorId} className={WARNING_BANNER} style={fs(12, 'body')}>
|
||||||
|
<AlertTriangle size={13} className="mt-0.5 shrink-0" aria-hidden="true" />
|
||||||
|
{t('places.endTimeBeforeStart')}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{collisions.length > 0 && (
|
||||||
|
<div className={WARNING_BANNER} style={fs(12, 'body')}>
|
||||||
|
<AlertTriangle size={13} className="mt-0.5 shrink-0" aria-hidden="true" />
|
||||||
|
<span>
|
||||||
|
{t('places.timeCollision')}{' '}
|
||||||
|
{collisions
|
||||||
|
.map((a) => a.place?.name)
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(', ')}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -14,6 +14,8 @@ import { useTripStore } from '../../store/tripStore'
|
|||||||
import { isCarrierTransport } from '../../utils/dayMerge'
|
import { isCarrierTransport } from '../../utils/dayMerge'
|
||||||
import type { TransitProvider } from '@trek/shared'
|
import type { TransitProvider } from '@trek/shared'
|
||||||
import { useIsPhone } from '../../mobile/useIsPhone'
|
import { useIsPhone } from '../../mobile/useIsPhone'
|
||||||
|
import { WalkLateLine, WalkTransitNote } from '../Tours/walk/WalkTransitNote'
|
||||||
|
import { lateForWalk, type WalkLate, type WalkTransitContext } from '../Tours/walk/walkTransit'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Public transit route search (#1065), backed by Transitous (MOTIS) through the
|
* Public transit route search (#1065), backed by Transitous (MOTIS) through the
|
||||||
@@ -314,7 +316,7 @@ function LineBadge({ leg }: { leg: TransitLeg }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function ItineraryCard({ it, tzFrom, tzTo, is12h, expanded, onToggle, onAdd, adding, t }: {
|
function ItineraryCard({ it, tzFrom, tzTo, is12h, expanded, onToggle, onAdd, adding, late, t }: {
|
||||||
it: TransitItinerary
|
it: TransitItinerary
|
||||||
tzFrom: string
|
tzFrom: string
|
||||||
tzTo: string
|
tzTo: string
|
||||||
@@ -323,6 +325,8 @@ function ItineraryCard({ it, tzFrom, tzTo, is12h, expanded, onToggle, onAdd, add
|
|||||||
onToggle: () => void
|
onToggle: () => void
|
||||||
onAdd: () => void
|
onAdd: () => void
|
||||||
adding: boolean
|
adding: boolean
|
||||||
|
/** CW-08: the next city walk this connection arrives too late for. */
|
||||||
|
late: WalkLate | null
|
||||||
t: (k: string, p?: Record<string, string | number>) => string
|
t: (k: string, p?: Record<string, string | number>) => string
|
||||||
}) {
|
}) {
|
||||||
const transitLegs = it.legs.filter(l => l.mode !== 'WALK')
|
const transitLegs = it.legs.filter(l => l.mode !== 'WALK')
|
||||||
@@ -352,6 +356,7 @@ function ItineraryCard({ it, tzFrom, tzTo, is12h, expanded, onToggle, onAdd, add
|
|||||||
</React.Fragment>
|
</React.Fragment>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
<WalkLateLine late={late} />
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{expanded && (
|
{expanded && (
|
||||||
@@ -460,9 +465,11 @@ interface TransitSearchPanelProps {
|
|||||||
initialTo?: PickedPlace | null
|
initialTo?: PickedPlace | null
|
||||||
/** Pre-seed the departure time ('HH:mm') — used when planning a specific leg. */
|
/** Pre-seed the departure time ('HH:mm') — used when planning a specific leg. */
|
||||||
initialTime?: string | null
|
initialTime?: string | null
|
||||||
|
/** CW-08: the two city walks the leg runs between; said only while the search is for their day. */
|
||||||
|
walk?: WalkTransitContext | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function TransitSearchPanel({ day, days, places, accommodations = [], onAdd, initialFrom = null, initialTo = null, initialTime = null }: TransitSearchPanelProps) {
|
export default function TransitSearchPanel({ day, days, places, accommodations = [], onAdd, initialFrom = null, initialTo = null, initialTime = null, walk = null }: TransitSearchPanelProps) {
|
||||||
const { t, language } = useTranslation()
|
const { t, language } = useTranslation()
|
||||||
const toast = useToast()
|
const toast = useToast()
|
||||||
const is12h = useSettingsStore(s => s.settings.time_format) === '12h'
|
const is12h = useSettingsStore(s => s.settings.time_format) === '12h'
|
||||||
@@ -470,7 +477,9 @@ export default function TransitSearchPanel({ day, days, places, accommodations =
|
|||||||
|
|
||||||
const [from, setFrom] = useState<PickedPlace | null>(initialFrom)
|
const [from, setFrom] = useState<PickedPlace | null>(initialFrom)
|
||||||
const [to, setTo] = useState<PickedPlace | null>(initialTo)
|
const [to, setTo] = useState<PickedPlace | null>(initialTo)
|
||||||
const [time, setTime] = useState(initialTime || '09:00')
|
const walkHere = walk?.dayId === day.id ? walk : null
|
||||||
|
// Between two walks the time is when the first one ends, never one made up: unknown, it is chosen.
|
||||||
|
const [time, setTime] = useState(initialTime || (walkHere ? '' : '09:00'))
|
||||||
const [arriveBy, setArriveBy] = useState(false)
|
const [arriveBy, setArriveBy] = useState(false)
|
||||||
const [activeModes, setActiveModes] = useState<Set<string>>(() => new Set(MODE_GROUPS.map(m => m.key)))
|
const [activeModes, setActiveModes] = useState<Set<string>>(() => new Set(MODE_GROUPS.map(m => m.key)))
|
||||||
const [pref, setPref] = useState<'best' | 'transfers' | 'walking'>('best')
|
const [pref, setPref] = useState<'best' | 'transfers' | 'walking'>('best')
|
||||||
@@ -629,6 +638,7 @@ export default function TransitSearchPanel({ day, days, places, accommodations =
|
|||||||
|
|
||||||
const tzFrom = from ? tzAt(from.lat, from.lng) : 'UTC'
|
const tzFrom = from ? tzAt(from.lat, from.lng) : 'UTC'
|
||||||
const tzTo = to ? tzAt(to.lat, to.lng) : tzFrom
|
const tzTo = to ? tzAt(to.lat, to.lng) : tzFrom
|
||||||
|
const canSearch = !!from && !!to && !!time && !loading
|
||||||
|
|
||||||
const segBtn = (active: boolean): React.CSSProperties => ({
|
const segBtn = (active: boolean): React.CSSProperties => ({
|
||||||
padding: isMobile ? '6px 5px' : '6px 11px', fontSize: isMobile ? 'calc(11px * var(--fs-scale-body, 1))' : 'calc(12px * var(--fs-scale-body, 1))', borderRadius: 7, fontWeight: 500,
|
padding: isMobile ? '6px 5px' : '6px 11px', fontSize: isMobile ? 'calc(11px * var(--fs-scale-body, 1))' : 'calc(12px * var(--fs-scale-body, 1))', borderRadius: 7, fontWeight: 500,
|
||||||
@@ -639,6 +649,7 @@ export default function TransitSearchPanel({ day, days, places, accommodations =
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 16, fontFamily: 'var(--font-system)' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 16, fontFamily: 'var(--font-system)' }}>
|
||||||
|
<WalkTransitNote walk={walkHere} />
|
||||||
{/* from / to — stacked tight on mobile, swap button on desktop only */}
|
{/* from / to — stacked tight on mobile, swap button on desktop only */}
|
||||||
<div style={{ display: 'flex', flexDirection: isMobile ? 'column' : 'row', gap: 8, alignItems: isMobile ? 'stretch' : 'flex-end' }}>
|
<div style={{ display: 'flex', flexDirection: isMobile ? 'column' : 'row', gap: 8, alignItems: isMobile ? 'stretch' : 'flex-end' }}>
|
||||||
<StopPicker label={t('transit.from')} value={from} onPick={setFrom} quickPicks={quickPicks} near={near} placeholder={t('transit.searchStop')} />
|
<StopPicker label={t('transit.from')} value={from} onPick={setFrom} quickPicks={quickPicks} near={near} placeholder={t('transit.searchStop')} />
|
||||||
@@ -707,9 +718,9 @@ export default function TransitSearchPanel({ day, days, places, accommodations =
|
|||||||
</div>
|
</div>
|
||||||
<button type="button"
|
<button type="button"
|
||||||
onClick={search}
|
onClick={search}
|
||||||
disabled={!from || !to || loading}
|
disabled={!canSearch}
|
||||||
className="bg-accent text-accent-text"
|
className="bg-accent text-accent-text"
|
||||||
style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6, border: 'none', borderRadius: 10, padding: '9px 18px', fontWeight: 600, fontSize: 'calc(13px * var(--fs-scale-body, 1))', cursor: (!from || !to || loading) ? 'default' : 'pointer', fontFamily: 'inherit', opacity: (!from || !to || loading) ? 0.55 : 1, flexShrink: 0, width: isMobile ? '100%' : undefined }}
|
style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6, border: 'none', borderRadius: 10, padding: '9px 18px', fontWeight: 600, fontSize: 'calc(13px * var(--fs-scale-body, 1))', cursor: canSearch ? 'pointer' : 'default', fontFamily: 'inherit', opacity: canSearch ? 1 : 0.55, flexShrink: 0, width: isMobile ? '100%' : undefined }}
|
||||||
>
|
>
|
||||||
<Search size={14} strokeWidth={2.2} />
|
<Search size={14} strokeWidth={2.2} />
|
||||||
{loading ? t('transit.searching') : t('transit.search')}
|
{loading ? t('transit.searching') : t('transit.search')}
|
||||||
@@ -743,6 +754,7 @@ export default function TransitSearchPanel({ day, days, places, accommodations =
|
|||||||
onToggle={() => setExpandedIdx(expandedIdx === idx ? null : idx)}
|
onToggle={() => setExpandedIdx(expandedIdx === idx ? null : idx)}
|
||||||
onAdd={() => addItinerary(it, idx)}
|
onAdd={() => addItinerary(it, idx)}
|
||||||
adding={addingIdx === idx}
|
adding={addingIdx === idx}
|
||||||
|
late={lateForWalk(walkHere, day.date ?? null, { date: dateYMDInTz(it.endTime, tzTo), time: timeHHmmInTz(it.endTime, tzTo) })}
|
||||||
t={t}
|
t={t}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -0,0 +1,181 @@
|
|||||||
|
// CW-08: the transit search between two city walks, opened from the day plan's
|
||||||
|
// connector with the first walk's end and the next one's start. The mocks are the
|
||||||
|
// ones TransitSearchPanel.test.tsx renders the panel with.
|
||||||
|
import userEvent from '@testing-library/user-event';
|
||||||
|
import { buildDay, buildPlace, buildUser } from '../../../tests/helpers/factories';
|
||||||
|
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||||
|
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||||
|
import { useAuthStore } from '../../store/authStore';
|
||||||
|
import { useSettingsStore } from '../../store/settingsStore';
|
||||||
|
import type { WalkTransitContext } from '../Tours/walk/walkTransit';
|
||||||
|
import TransitSearchPanel from './TransitSearchPanel';
|
||||||
|
|
||||||
|
const { transitApiMock } = vi.hoisted(() => ({ transitApiMock: { geocode: vi.fn(), plan: vi.fn() } }));
|
||||||
|
|
||||||
|
vi.mock('../../api/client', async (importOriginal) => {
|
||||||
|
const actual = (await importOriginal()) as object;
|
||||||
|
return { ...actual, transitApi: transitApiMock };
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.mock('../shared/Toast', () => ({ useToast: () => ({ error: vi.fn(), success: vi.fn() }) }));
|
||||||
|
|
||||||
|
const day = buildDay({ id: 10, trip_id: 1, date: '2025-06-01', title: 'Berlin Day' });
|
||||||
|
const OLD_BRIDGE = { name: 'Old bridge', lat: 52.51, lng: 13.42 };
|
||||||
|
const FISH_MARKET = { name: 'Fish market', lat: 52.5, lng: 13.45 };
|
||||||
|
const WALK: WalkTransitContext = {
|
||||||
|
dayId: 10,
|
||||||
|
fromWalk: 'Old town',
|
||||||
|
toWalk: 'Harbour',
|
||||||
|
ends: '12:15',
|
||||||
|
endsNextDay: false,
|
||||||
|
endsAtLeast: false,
|
||||||
|
nextStarts: '13:00',
|
||||||
|
};
|
||||||
|
|
||||||
|
// Berlin, summer time (UTC+2): a tram that departs 12:20 and arrives at `arrives` (UTC).
|
||||||
|
function itinerary(arrives: string) {
|
||||||
|
const at = (time: string) => ({ lat: 52.505, lng: 13.43, time, scheduledTime: null, track: null });
|
||||||
|
return {
|
||||||
|
startTime: '2025-06-01T10:20:00Z',
|
||||||
|
endTime: `2025-06-01T${arrives}:00Z`,
|
||||||
|
duration: 1800,
|
||||||
|
transfers: 0,
|
||||||
|
walkSeconds: 240,
|
||||||
|
legs: [
|
||||||
|
{
|
||||||
|
mode: 'TRAM',
|
||||||
|
from: { ...at('2025-06-01T10:20:00Z'), name: 'START' },
|
||||||
|
to: { ...at(`2025-06-01T${arrives}:00Z`), name: 'END' },
|
||||||
|
duration: 1800,
|
||||||
|
distance: null,
|
||||||
|
headsign: 'Harbour',
|
||||||
|
line: 'M1',
|
||||||
|
lineColor: null,
|
||||||
|
lineTextColor: null,
|
||||||
|
agency: 'BVG',
|
||||||
|
intermediateStops: 4,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderPanel(walk: WalkTransitContext | null, initialTime: string | null = walk?.ends ?? null) {
|
||||||
|
const onAdd = vi.fn().mockResolvedValue({});
|
||||||
|
render(
|
||||||
|
<TransitSearchPanel
|
||||||
|
day={day}
|
||||||
|
days={[day]}
|
||||||
|
places={[buildPlace({ id: 1, name: 'Old town', lat: 52.52, lng: 13.4 })]}
|
||||||
|
onAdd={onAdd}
|
||||||
|
initialFrom={OLD_BRIDGE}
|
||||||
|
initialTo={FISH_MARKET}
|
||||||
|
initialTime={initialTime}
|
||||||
|
walk={walk}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
return { onAdd };
|
||||||
|
}
|
||||||
|
|
||||||
|
const timeField = () => screen.getByPlaceholderText('00:00') as HTMLInputElement;
|
||||||
|
const searchButton = () => screen.getByRole('button', { name: /^Search$/ });
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
resetAllStores();
|
||||||
|
vi.clearAllMocks();
|
||||||
|
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });
|
||||||
|
seedStore(useSettingsStore, { settings: { time_format: '24h' } } as never);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('TransitSearchPanel between two city walks (CW-08)', () => {
|
||||||
|
it('says when the first walk ends and the next starts, and departs from the last stop then', async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
transitApiMock.plan.mockResolvedValueOnce({ itineraries: [] });
|
||||||
|
renderPanel(WALK);
|
||||||
|
|
||||||
|
expect(screen.getByTestId('transit-walk-end')).toHaveTextContent('Old town ends at about 12:15.');
|
||||||
|
expect(screen.getByTestId('transit-walk-next')).toHaveTextContent('Harbour starts at 13:00.');
|
||||||
|
const [from, to] = screen.getAllByPlaceholderText('Search stop or station…') as HTMLInputElement[];
|
||||||
|
expect(from?.value).toBe('Old bridge');
|
||||||
|
expect(to?.value).toBe('Fish market');
|
||||||
|
expect(timeField().value).toBe('12:15');
|
||||||
|
|
||||||
|
await user.click(searchButton());
|
||||||
|
await waitFor(() => expect(transitApiMock.plan).toHaveBeenCalled());
|
||||||
|
// 12:15 in Berlin (UTC+2), from the walk's end and to the next one's start.
|
||||||
|
expect(transitApiMock.plan.mock.calls[0]?.[0]).toMatchObject({
|
||||||
|
from: '52.51,13.42',
|
||||||
|
to: '52.5,13.45',
|
||||||
|
time: '2025-06-01T10:15:00.000Z',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('marks a connection that arrives after the next walk starts, and only that one', async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
transitApiMock.plan.mockResolvedValueOnce({ itineraries: [itinerary('11:10'), itinerary('10:50')] });
|
||||||
|
renderPanel(WALK);
|
||||||
|
|
||||||
|
await user.click(searchButton());
|
||||||
|
await screen.findByText(/12:20\D+13:10/);
|
||||||
|
const late = screen.getAllByTestId('transit-walk-late');
|
||||||
|
expect(late).toHaveLength(1);
|
||||||
|
expect(late[0]).toHaveTextContent('Arrives after Harbour starts at 13:00');
|
||||||
|
expect(screen.getByText(/12:20\D+13:10/).closest('button')).toContainElement(late[0] ?? null);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('says an end that leaves a time out is the earliest', () => {
|
||||||
|
renderPanel({ ...WALK, endsAtLeast: true });
|
||||||
|
expect(screen.getByTestId('transit-walk-end')).toHaveTextContent(
|
||||||
|
'Old town ends at 12:15 at the earliest; not all of its times are known yet.'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('says a walk that ends after midnight does so, and makes up no time on this day', () => {
|
||||||
|
renderPanel({ ...WALK, ends: null, endsNextDay: true, endsAtLeast: true });
|
||||||
|
expect(screen.getByTestId('transit-walk-end')).toHaveTextContent(
|
||||||
|
'Old town only ends after midnight, so choose a departure time.'
|
||||||
|
);
|
||||||
|
expect(timeField().value).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('makes up no time without an end, and waits for one to be chosen', async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
transitApiMock.plan.mockResolvedValueOnce({ itineraries: [] });
|
||||||
|
renderPanel({ ...WALK, ends: null, nextStarts: null });
|
||||||
|
|
||||||
|
expect(screen.getByTestId('transit-walk-end')).toHaveTextContent(
|
||||||
|
'When Old town ends is not known yet, so choose a departure time.'
|
||||||
|
);
|
||||||
|
expect(screen.queryByTestId('transit-walk-next')).not.toBeInTheDocument();
|
||||||
|
expect(timeField().value).toBe('');
|
||||||
|
expect(searchButton()).toBeDisabled();
|
||||||
|
|
||||||
|
await user.type(timeField(), '1230');
|
||||||
|
await user.tab();
|
||||||
|
expect(searchButton()).toBeEnabled();
|
||||||
|
await user.click(searchButton());
|
||||||
|
await waitFor(() => expect(transitApiMock.plan).toHaveBeenCalled());
|
||||||
|
expect(transitApiMock.plan.mock.calls[0]?.[0]).toMatchObject({ time: '2025-06-01T10:30:00.000Z' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('on another day than the walks, speaks of them no more and departs at the usual time', () => {
|
||||||
|
renderPanel({ ...WALK, dayId: 11 }, null);
|
||||||
|
expect(screen.queryByTestId('transit-walk-end')).not.toBeInTheDocument();
|
||||||
|
expect(timeField().value).toBe('09:00');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('adds a connection only once it is opened and taken, between the two stops', async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
transitApiMock.plan.mockResolvedValueOnce({ itineraries: [itinerary('10:50')] });
|
||||||
|
const { onAdd } = renderPanel(WALK);
|
||||||
|
|
||||||
|
await user.click(searchButton());
|
||||||
|
await user.click(await screen.findByText(/12:20\D+12:50/));
|
||||||
|
expect(onAdd).not.toHaveBeenCalled();
|
||||||
|
await user.click(await screen.findByRole('button', { name: 'Add to day' }));
|
||||||
|
|
||||||
|
await waitFor(() => expect(onAdd).toHaveBeenCalledTimes(1));
|
||||||
|
const payload = onAdd.mock.calls[0]?.[0];
|
||||||
|
expect(payload).toMatchObject({ type: 'transit', title: 'Old bridge → Fish market', day_id: 10 });
|
||||||
|
expect(payload.endpoints.map((point: { name: string }) => point.name)).toEqual(['Old bridge', 'Fish market']);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -519,6 +519,15 @@ describe('TransportModal', () => {
|
|||||||
expect(screen.getAllByPlaceholderText('Search stop or station…')).toHaveLength(2);
|
expect(screen.getAllByPlaceholderText('Search stop or station…')).toHaveLength(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('FE-PLANNER-TRANSMODAL-023b: a leg between two city walks opens the search with what it says of them (CW-08)', () => {
|
||||||
|
const days = [{ id: 10, trip_id: 1, day_number: 1, date: '2025-06-01', title: 'Day 1' }] as Day[];
|
||||||
|
const walk = { dayId: 10, fromWalk: 'Old town', toWalk: 'Harbour', ends: '12:15', endsNextDay: false, endsAtLeast: false, nextStarts: '13:00' };
|
||||||
|
const transitPrefill = { from: { name: 'Old bridge', lat: 52.51, lng: 13.42 }, to: { name: 'Fish market', lat: 52.5, lng: 13.45 }, time: '12:15', walk };
|
||||||
|
render(<TransportModal {...defaultProps} days={days} selectedDayId={10} initialAutomated transitPrefill={transitPrefill} places={[]} accommodations={[]} />);
|
||||||
|
expect(screen.getByTestId('transit-walk-end')).toHaveTextContent('Old town ends at about 12:15.');
|
||||||
|
expect(screen.getByTestId('transit-walk-next')).toHaveTextContent('Harbour starts at 13:00.');
|
||||||
|
});
|
||||||
|
|
||||||
it('FE-PLANNER-TRANSMODAL-028: automated quick picks only offer the chosen day\'s places (#1460)', async () => {
|
it('FE-PLANNER-TRANSMODAL-028: automated quick picks only offer the chosen day\'s places (#1460)', async () => {
|
||||||
const days = [
|
const days = [
|
||||||
buildDay({ id: 10, date: '2025-06-01' }),
|
buildDay({ id: 10, date: '2025-06-01' }),
|
||||||
|
|||||||
@@ -19,7 +19,8 @@ import { TravelerPicker } from './TravelerPicker'
|
|||||||
import type { TripMember } from '../Budget/BudgetPanelMemberChips'
|
import type { TripMember } from '../Budget/BudgetPanelMemberChips'
|
||||||
import type { BookingExpenseRequest } from './BookingCostsSection.types'
|
import type { BookingExpenseRequest } from './BookingCostsSection.types'
|
||||||
import type { BookingReviewDraft } from './parsedItemToDraft'
|
import type { BookingReviewDraft } from './parsedItemToDraft'
|
||||||
import TransitSearchPanel, { type PickedPlace } from './TransitSearchPanel'
|
import TransitSearchPanel from './TransitSearchPanel'
|
||||||
|
import type { TransitPrefill } from './transitLeg'
|
||||||
import { BookingDialogHeader, StatusPill } from './bookings/BookingDialogShell'
|
import { BookingDialogHeader, StatusPill } from './bookings/BookingDialogShell'
|
||||||
import { DialogShell, DialogSection, DialogFooter, FooterSpacer, DialogButton, DeleteButton } from '../shared/DialogShell'
|
import { DialogShell, DialogSection, DialogFooter, FooterSpacer, DialogButton, DeleteButton } from '../shared/DialogShell'
|
||||||
import { INPUT, READONLY_BOX, GRID_2, GRID_3, PANEL, SEARCH_ON_PANEL, EditorField, Segmented, PillSelect, AddRowButton } from '../shared/dialogParts'
|
import { INPUT, READONLY_BOX, GRID_2, GRID_3, PANEL, SEARCH_ON_PANEL, EditorField, Segmented, PillSelect, AddRowButton } from '../shared/dialogParts'
|
||||||
@@ -70,7 +71,7 @@ interface TransportModalProps {
|
|||||||
/** Transit search needs real dates to depart on, so the Automated mode is hidden on a dateless trip. */
|
/** Transit search needs real dates to depart on, so the Automated mode is hidden on a dateless trip. */
|
||||||
tripHasDates?: boolean
|
tripHasDates?: boolean
|
||||||
/** Pre-seed the transit search — used by "change route" and by per-leg planning. */
|
/** Pre-seed the transit search — used by "change route" and by per-leg planning. */
|
||||||
transitPrefill?: { from?: PickedPlace | null; to?: PickedPlace | null; time?: string | null } | null
|
transitPrefill?: TransitPrefill | null
|
||||||
/** Trip members + guests, for the traveler picker (#1517). */
|
/** Trip members + guests, for the traveler picker (#1517). */
|
||||||
tripMembers?: TripMember[]
|
tripMembers?: TripMember[]
|
||||||
}
|
}
|
||||||
@@ -304,6 +305,7 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, sel
|
|||||||
initialFrom={transitPrefill?.from ?? null}
|
initialFrom={transitPrefill?.from ?? null}
|
||||||
initialTo={transitPrefill?.to ?? null}
|
initialTo={transitPrefill?.to ?? null}
|
||||||
initialTime={transitPrefill?.time ?? null}
|
initialTime={transitPrefill?.time ?? null}
|
||||||
|
walk={transitPrefill?.walk ?? null}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
/*
|
||||||
|
* The surfaces the day plan draws its rows and day heads on: the class strings
|
||||||
|
* of the white controls a row and a route bar carry, and the colour mixes a day
|
||||||
|
* head and a pinned stop take. Mixed from the scheme's tokens, so they follow
|
||||||
|
* the user's accent and both themes.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** The round white button a row carries on its right (a route on the map, a journey's legs). */
|
||||||
|
export const ROW_ROUND = 'grid flex-none place-items-center rounded-full bg-surface-card shadow-sm transition-colors';
|
||||||
|
/** The white face every control of a day's route bar shares, so the row reads as one set. */
|
||||||
|
export const ROUTE_TOOL = 'bg-surface-card shadow-sm ring-1 ring-edge-faint';
|
||||||
|
|
||||||
|
// The day head's tones: hovered, open, and a drop landing on it. Mixed from the
|
||||||
|
// accent so they follow the user's scheme in both themes.
|
||||||
|
export const DAY_HEAD_HOVER = 'color-mix(in srgb, var(--accent) 10%, transparent)';
|
||||||
|
export const DAY_HEAD_SELECTED = 'color-mix(in srgb, var(--accent) 12%, transparent)';
|
||||||
|
export const DAY_HEAD_DROP = 'color-mix(in srgb, var(--accent) 9%, transparent)';
|
||||||
|
// A stop pinned in place: a whisper of the danger tone on the row, a stronger one over its avatar.
|
||||||
|
export const LOCKED_ROW = 'color-mix(in srgb, var(--danger) 7%, transparent)';
|
||||||
|
export const LOCK_OVERLAY = 'color-mix(in srgb, var(--danger) 62%, transparent)';
|
||||||
|
export const LOCK_OVERLAY_HOVER = 'color-mix(in srgb, var(--danger) 42%, transparent)';
|
||||||
@@ -83,14 +83,12 @@ export function stayFormFrom<P>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The places a stay can be at (no GPX tracks, but always the one already picked),
|
* The places a stay can be at (no GPX tracks or tours, but always the one already picked),
|
||||||
* narrowed to a category when one is chosen.
|
* narrowed to a category when one is chosen.
|
||||||
*/
|
*/
|
||||||
export function stayPlaceChoices<P extends { id: number; route_geometry?: string | null; category_id?: number | null }>(
|
export function stayPlaceChoices<
|
||||||
places: P[],
|
P extends { id: number; route_geometry?: string | null; tour_place_id?: number | null; category_id?: number | null },
|
||||||
placeId: number | string | null | undefined,
|
>(places: P[], placeId: number | string | null | undefined, categoryId: number | null): P[] {
|
||||||
categoryId: number | null
|
|
||||||
): P[] {
|
|
||||||
const offered = stayPlaces<P>(places, placeId);
|
const offered = stayPlaces<P>(places, placeId);
|
||||||
return categoryId != null ? offered.filter((p) => p.category_id === categoryId) : offered;
|
return categoryId != null ? offered.filter((p) => p.category_id === categoryId) : offered;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'
|
|||||||
import { buildTransitLeg, buildTransitNameIndex } from './transitLeg'
|
import { buildTransitLeg, buildTransitNameIndex } from './transitLeg'
|
||||||
import type { Accommodation, Assignment, Reservation, RouteSegment } from '../../types'
|
import type { Accommodation, Assignment, Reservation, RouteSegment } from '../../types'
|
||||||
|
|
||||||
// FE-PLANNER-TRANSITLEG-001 to FE-PLANNER-TRANSITLEG-006
|
// FE-PLANNER-TRANSITLEG-001 to FE-PLANNER-TRANSITLEG-007
|
||||||
|
|
||||||
const visit = (id: number, dayId: number, name: string, lat: number, lng: number, placeTime?: string) =>
|
const visit = (id: number, dayId: number, name: string, lat: number, lng: number, placeTime?: string) =>
|
||||||
({ id, day_id: dayId, place: { id, name, lat, lng, place_time: placeTime ?? null } }) as unknown as Assignment
|
({ id, day_id: dayId, place: { id, name, lat, lng, place_time: placeTime ?? null } }) as unknown as Assignment
|
||||||
@@ -69,4 +69,11 @@ describe('buildTransitLeg', () => {
|
|||||||
expect(buildTransitLeg(undefined, 1, names, assignments, [])).toBeNull()
|
expect(buildTransitLeg(undefined, 1, names, assignments, [])).toBeNull()
|
||||||
expect(buildTransitLeg({ from: [1, 1] } as unknown as RouteSegment, 1, names, assignments, [])).toBeNull()
|
expect(buildTransitLeg({ from: [1, 1] } as unknown as RouteSegment, 1, names, assignments, [])).toBeNull()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('FE-PLANNER-TRANSITLEG-007: a leg leaving a loop tour does not depart when the tour starts (CW-08)', () => {
|
||||||
|
// A tour's place sits at its start; a loop ends there too, but its time is when it starts.
|
||||||
|
const loop = { ...visit(31, 3, 'Old town loop', 52.52, 13.4, '10:00'), tour_place_id: 31 } as Assignment
|
||||||
|
const tours = { '3': [loop, visit(32, 3, 'Harbour', 52.5, 13.45)] }
|
||||||
|
expect(buildTransitLeg(seg([52.52, 13.4], [52.5, 13.45]), 3, buildTransitNameIndex(tours, [], []), tours, [])?.time).toBeNull()
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { Accommodation, Assignment, Reservation, RouteSegment } from '../../types'
|
import type { Accommodation, Assignment, Reservation, RouteSegment } from '../../types'
|
||||||
|
import type { WalkTransitContext } from '../Tours/walk/walkTransit'
|
||||||
import type { PickedPlace } from './TransitSearchPanel'
|
import type { PickedPlace } from './TransitSearchPanel'
|
||||||
|
|
||||||
/** What the transit search is opened with for one leg of a day. */
|
/** What the transit search is opened with for one leg of a day. */
|
||||||
@@ -8,6 +9,20 @@ export interface TransitLeg {
|
|||||||
time: string | null
|
time: string | null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A leg as a view hands it on to open the search: its day and, between two city walks, what it says of them (CW-08). */
|
||||||
|
export interface PlannedTransitLeg extends TransitLeg {
|
||||||
|
dayId: number
|
||||||
|
walk?: WalkTransitContext
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the search is seeded with: a leg, or the ends of a journey whose route is changed. */
|
||||||
|
export interface TransitPrefill {
|
||||||
|
from?: PickedPlace | null
|
||||||
|
to?: PickedPlace | null
|
||||||
|
time?: string | null
|
||||||
|
walk?: WalkTransitContext | null
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A connector's endpoints carry only coordinates (RouteSegment.from/to, both
|
* A connector's endpoints carry only coordinates (RouteSegment.from/to, both
|
||||||
* [lat, lng]); resolve them back to the NAMES the transit search shows by indexing
|
* [lat, lng]); resolve them back to the NAMES the transit search shows by indexing
|
||||||
@@ -48,7 +63,9 @@ function originDepartureTime(
|
|||||||
assignments: Record<string, Assignment[]>,
|
assignments: Record<string, Assignment[]>,
|
||||||
reservations: Reservation[],
|
reservations: Reservation[],
|
||||||
): string | null {
|
): string | null {
|
||||||
for (const a of assignments[String(dayId)] ?? []) {
|
// A tour's place is where it starts and its time when it starts: a leg leaving a loop is no departure then.
|
||||||
|
const stops = (assignments[String(dayId)] ?? []).filter(a => a.tour_place_id == null || a.tour_place_id !== a.place?.id)
|
||||||
|
for (const a of stops) {
|
||||||
if (a.place?.lat != null && a.place?.lng != null && `${a.place.lat},${a.place.lng}` === originKey) return a.place.place_time ?? null
|
if (a.place?.lat != null && a.place?.lng != null && `${a.place.lat},${a.place.lng}` === originKey) return a.place.place_time ?? null
|
||||||
}
|
}
|
||||||
for (const r of reservations) {
|
for (const r of reservations) {
|
||||||
|
|||||||
@@ -0,0 +1,255 @@
|
|||||||
|
import { renderHook, waitFor } from '@testing-library/react';
|
||||||
|
import type { TourListItem } from '@trek/shared';
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { buildAssignment, buildPlace, buildReservation } from '../../../tests/helpers/factories';
|
||||||
|
import { TranslationProvider } from '../../i18n/TranslationContext';
|
||||||
|
import { tourRepo } from '../../repo/tourRepo';
|
||||||
|
import type { RouteSegment } from '../../types';
|
||||||
|
import type { MergedItem } from '../../utils/dayMerge';
|
||||||
|
import { useTransitLegPlanner, type TransitLegPlannerDeps } from './useTransitLegPlanner';
|
||||||
|
|
||||||
|
// CW-08: the transit leg behind the desktop day plan and the phone timeline.
|
||||||
|
|
||||||
|
vi.mock('../../repo/tourRepo', async (importOriginal) => {
|
||||||
|
const actual = await importOriginal<typeof import('../../repo/tourRepo')>();
|
||||||
|
return { ...actual, tourRepo: { ...actual.tourRepo, detail: vi.fn() } };
|
||||||
|
});
|
||||||
|
|
||||||
|
const oldTown = buildPlace({
|
||||||
|
id: 51,
|
||||||
|
name: 'Old town',
|
||||||
|
lat: 52.52,
|
||||||
|
lng: 13.4,
|
||||||
|
route_geometry: '[[52.52,13.4],[52.515,13.41],[52.51,13.42]]',
|
||||||
|
});
|
||||||
|
const harbour = buildPlace({
|
||||||
|
id: 52,
|
||||||
|
name: 'Harbour',
|
||||||
|
lat: 52.5,
|
||||||
|
lng: 13.45,
|
||||||
|
route_geometry: '[[52.5,13.45],[52.49,13.46]]',
|
||||||
|
});
|
||||||
|
const museum = buildPlace({ id: 53, name: 'Museum', lat: 52.47, lng: 13.48, place_time: '9:05' });
|
||||||
|
const cafe = buildPlace({ id: 54, name: 'Corner cafe', lat: 52.48, lng: 13.47 });
|
||||||
|
|
||||||
|
const walkA = buildAssignment({
|
||||||
|
id: 201,
|
||||||
|
day_id: 10,
|
||||||
|
order_index: 0,
|
||||||
|
tour_place_id: 51,
|
||||||
|
place: { ...oldTown, place_time: '10:00' },
|
||||||
|
});
|
||||||
|
const walkB = buildAssignment({
|
||||||
|
id: 202,
|
||||||
|
day_id: 10,
|
||||||
|
order_index: 1,
|
||||||
|
tour_place_id: 52,
|
||||||
|
place: { ...harbour, place_time: '13:00' },
|
||||||
|
});
|
||||||
|
const assignments = {
|
||||||
|
'10': [walkB, walkA],
|
||||||
|
'11': [
|
||||||
|
buildAssignment({ id: 301, day_id: 11, order_index: 0, place: museum }),
|
||||||
|
buildAssignment({ id: 302, day_id: 11, order_index: 1, place: cafe }),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
function walk(place: { id: number; name: string }): TourListItem {
|
||||||
|
return {
|
||||||
|
place_id: place.id,
|
||||||
|
name: place.name,
|
||||||
|
tour_type: 'walk',
|
||||||
|
duration: 90,
|
||||||
|
planned_duration_minutes: null,
|
||||||
|
break_additional_minutes: null,
|
||||||
|
station_count: 2,
|
||||||
|
station_stay_minutes: 45,
|
||||||
|
station_stays_unknown: 0,
|
||||||
|
} as TourListItem;
|
||||||
|
}
|
||||||
|
const tours = new Map([walk(oldTown), walk(harbour)].map((tour) => [tour.place_id, tour]));
|
||||||
|
|
||||||
|
const BETWEEN_WALKS = { from: [52.51, 13.42], to: [52.5, 13.45] } as unknown as RouteSegment;
|
||||||
|
const MUSEUM_TO_CAFE = { from: [52.47, 13.48], to: [52.48, 13.47] } as unknown as RouteSegment;
|
||||||
|
|
||||||
|
function setup(overrides: Partial<TransitLegPlannerDeps> = {}) {
|
||||||
|
const onPlan = vi.fn();
|
||||||
|
const deps: TransitLegPlannerDeps = {
|
||||||
|
tripId: 1,
|
||||||
|
assignments,
|
||||||
|
accommodations: [],
|
||||||
|
reservations: [],
|
||||||
|
places: [oldTown, harbour, museum, cafe],
|
||||||
|
toursEnabled: true,
|
||||||
|
tourOf: (placeId) => tours.get(placeId),
|
||||||
|
onPlan,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
const { result, unmount } = renderHook(() => useTransitLegPlanner(deps), { wrapper: TranslationProvider });
|
||||||
|
return { onPlan, result, unmount };
|
||||||
|
}
|
||||||
|
|
||||||
|
const detail = (placeId: number, names: [string, string]) => ({
|
||||||
|
tour: tours.get(placeId),
|
||||||
|
waypoints: names.map((name, sequence) => ({
|
||||||
|
lat: 0,
|
||||||
|
lng: 0,
|
||||||
|
role: 'via',
|
||||||
|
sequence,
|
||||||
|
key: `${placeId}-${sequence}`,
|
||||||
|
name,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Walk reads that answer only once let go, and what each was asked with. */
|
||||||
|
function heldReads() {
|
||||||
|
let release: () => void = () => undefined;
|
||||||
|
const gate = new Promise<void>((resolve) => {
|
||||||
|
release = resolve;
|
||||||
|
});
|
||||||
|
vi.mocked(tourRepo.detail).mockImplementation((_tripId, placeId) =>
|
||||||
|
gate.then(() => detail(placeId, ['First', 'Last']) as never)
|
||||||
|
);
|
||||||
|
const signals = () => vi.mocked(tourRepo.detail).mock.calls.map((call) => call[2]?.aborted);
|
||||||
|
// A turn of the event loop lets every read and what follows it settle.
|
||||||
|
const settle = async () => {
|
||||||
|
release();
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
|
};
|
||||||
|
return { signals, settle };
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.mocked(tourRepo.detail).mockReset();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('useTransitLegPlanner', () => {
|
||||||
|
it('offers no leg without a way to open the search, and the leg as for any connector with one', () => {
|
||||||
|
expect(setup({ onPlan: undefined }).result.current.legFor(11, MUSEUM_TO_CAFE)).toBeNull();
|
||||||
|
expect(setup().result.current.legFor(11, MUSEUM_TO_CAFE)).toEqual({
|
||||||
|
from: { name: 'Museum', lat: 52.47, lng: 13.48 },
|
||||||
|
to: { name: 'Corner cafe', lat: 52.48, lng: 13.47 },
|
||||||
|
time: '09:05',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('opens the search for an ordinary leg at once, with nothing said of walks', () => {
|
||||||
|
const { onPlan, result } = setup();
|
||||||
|
const leg = result.current.legFor(11, MUSEUM_TO_CAFE);
|
||||||
|
if (!leg) throw new Error('no leg');
|
||||||
|
result.current.plan(11, leg, 301);
|
||||||
|
expect(onPlan.mock.calls[0]?.[0]).toStrictEqual({ dayId: 11, ...leg });
|
||||||
|
expect(tourRepo.detail).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('between two walks, opens it from the last stop to the first once both are read, when the first one ends', async () => {
|
||||||
|
vi.mocked(tourRepo.detail).mockImplementation((_tripId, placeId) =>
|
||||||
|
Promise.resolve(
|
||||||
|
detail(placeId, placeId === 51 ? ['Town hall', 'Old bridge'] : ['Fish market', 'Lighthouse']) as never
|
||||||
|
)
|
||||||
|
);
|
||||||
|
const { onPlan, result } = setup();
|
||||||
|
const leg = result.current.legFor(10, BETWEEN_WALKS);
|
||||||
|
if (!leg) throw new Error('no leg');
|
||||||
|
result.current.plan(10, leg, walkA.id);
|
||||||
|
|
||||||
|
expect(onPlan).not.toHaveBeenCalled();
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(onPlan).toHaveBeenCalledWith({
|
||||||
|
dayId: 10,
|
||||||
|
from: { name: 'Old bridge', lat: 52.51, lng: 13.42 },
|
||||||
|
to: { name: 'Fish market', lat: 52.5, lng: 13.45 },
|
||||||
|
time: '12:15',
|
||||||
|
walk: {
|
||||||
|
dayId: 10,
|
||||||
|
fromWalk: 'Old town',
|
||||||
|
toWalk: 'Harbour',
|
||||||
|
ends: '12:15',
|
||||||
|
endsNextDay: false,
|
||||||
|
endsAtLeast: false,
|
||||||
|
nextStarts: '13:00',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
);
|
||||||
|
expect(vi.mocked(tourRepo.detail).mock.calls.map((call) => call[1])).toEqual([51, 52]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('still opens it where a walk cannot be read, naming that end after its walk', async () => {
|
||||||
|
vi.mocked(tourRepo.detail).mockImplementation((_tripId, placeId) =>
|
||||||
|
placeId === 51
|
||||||
|
? Promise.reject(new Error('Tour not available offline'))
|
||||||
|
: // Route ends without keys stand in for stops this device does not hold.
|
||||||
|
Promise.resolve({
|
||||||
|
tour: tours.get(52),
|
||||||
|
waypoints: [{ lat: 52.5, lng: 13.45, role: 'start', sequence: 0 }],
|
||||||
|
} as never)
|
||||||
|
);
|
||||||
|
const { onPlan, result } = setup();
|
||||||
|
const leg = result.current.legFor(10, BETWEEN_WALKS);
|
||||||
|
if (!leg) throw new Error('no leg');
|
||||||
|
result.current.plan(10, leg, walkA.id);
|
||||||
|
|
||||||
|
await waitFor(() => expect(onPlan).toHaveBeenCalledTimes(1));
|
||||||
|
expect(onPlan.mock.calls[0]?.[0]).toMatchObject({
|
||||||
|
from: { name: 'End of Old town' },
|
||||||
|
to: { name: 'Start of Harbour' },
|
||||||
|
time: '12:15',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('with tours off, treats the leg between two walks as any other', () => {
|
||||||
|
const { onPlan, result } = setup({ toursEnabled: false });
|
||||||
|
const leg = result.current.legFor(10, BETWEEN_WALKS);
|
||||||
|
if (!leg) throw new Error('no leg');
|
||||||
|
result.current.plan(10, leg, walkA.id);
|
||||||
|
expect(onPlan).toHaveBeenCalledWith({ dayId: 10, ...leg });
|
||||||
|
expect(tourRepo.detail).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('opens nothing without a way to open the search', () => {
|
||||||
|
const { result } = setup({ onPlan: undefined });
|
||||||
|
const leg = { from: { name: '', lat: 52.51, lng: 13.42 }, to: { name: '', lat: 52.5, lng: 13.45 }, time: null };
|
||||||
|
expect(() => result.current.plan(10, leg, walkA.id)).not.toThrow();
|
||||||
|
expect(tourRepo.detail).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('opens only the leg asked for last, and drops the walks still being read for an earlier one', async () => {
|
||||||
|
const reads = heldReads();
|
||||||
|
const { onPlan, result } = setup();
|
||||||
|
const between = result.current.legFor(10, BETWEEN_WALKS);
|
||||||
|
const ordinary = result.current.legFor(11, MUSEUM_TO_CAFE);
|
||||||
|
if (!between || !ordinary) throw new Error('no leg');
|
||||||
|
|
||||||
|
result.current.plan(10, between, walkA.id);
|
||||||
|
result.current.plan(10, between, walkA.id);
|
||||||
|
result.current.plan(11, ordinary, 301);
|
||||||
|
expect(reads.signals()).toEqual([true, true, true, true]);
|
||||||
|
await reads.settle();
|
||||||
|
|
||||||
|
expect(onPlan).toHaveBeenCalledTimes(1);
|
||||||
|
expect(onPlan).toHaveBeenCalledWith({ dayId: 11, ...ordinary });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('opens nothing once the view is gone before the walks are read', async () => {
|
||||||
|
const reads = heldReads();
|
||||||
|
const { onPlan, result, unmount } = setup();
|
||||||
|
const leg = result.current.legFor(10, BETWEEN_WALKS);
|
||||||
|
if (!leg) throw new Error('no leg');
|
||||||
|
|
||||||
|
result.current.plan(10, leg, walkA.id);
|
||||||
|
expect(reads.signals()).toEqual([false, false]);
|
||||||
|
unmount();
|
||||||
|
expect(reads.signals()).toEqual([true, true]);
|
||||||
|
await reads.settle();
|
||||||
|
|
||||||
|
expect(onPlan).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('says when a saved journey now arrives after the walk it leads to starts, while tours are on', () => {
|
||||||
|
const journey = buildReservation({ id: 300, type: 'transit', reservation_end_time: '2025-06-01T13:10' });
|
||||||
|
const following = [{ type: 'place', sortKey: 1, data: walkB }] as MergedItem[];
|
||||||
|
const day = { date: '2025-06-01' };
|
||||||
|
expect(setup().result.current.lateBefore(day, journey, following)).toEqual({ walk: 'Harbour', time: '13:00' });
|
||||||
|
expect(setup({ toursEnabled: false }).result.current.lateBefore(day, journey, following)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import { useCallback, useEffect, useMemo, useRef } from 'react';
|
||||||
|
import { useTranslation } from '../../i18n';
|
||||||
|
import type { Accommodation, AssignmentsMap, Day, Place, Reservation, RouteSegment } from '../../types';
|
||||||
|
import type { MergedItem } from '../../utils/dayMerge';
|
||||||
|
import { projectDayItinerary } from '../Map/dayTourProjection';
|
||||||
|
import { readWalkStations } from '../Tours/walk/walkStationsRead';
|
||||||
|
import { journeyLate, walkPairAt, walkTransitLeg, type TourOf, type WalkLate } from '../Tours/walk/walkTransit';
|
||||||
|
import { buildTransitLeg, buildTransitNameIndex, type PlannedTransitLeg, type TransitLeg } from './transitLeg';
|
||||||
|
|
||||||
|
export interface TransitLegPlannerDeps {
|
||||||
|
tripId: number | string;
|
||||||
|
assignments: AssignmentsMap;
|
||||||
|
accommodations: Accommodation[];
|
||||||
|
reservations: Reservation[];
|
||||||
|
places: Place[];
|
||||||
|
toursEnabled: boolean;
|
||||||
|
tourOf: TourOf;
|
||||||
|
/** Opens the search for a leg; without it no leg offers one, as on a trip without dates. */
|
||||||
|
onPlan: ((leg: PlannedTransitLeg) => void) | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A walk's stops, or null where this device cannot read them. */
|
||||||
|
async function stopsOrNull(tripId: number | string, placeId: number, signal: AbortSignal) {
|
||||||
|
try {
|
||||||
|
return await readWalkStations(tripId, placeId, signal);
|
||||||
|
} catch {
|
||||||
|
// They only name the leg's two ends: without them it opens named after the walks.
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Public transit for one leg of a day (#2398), behind the desktop day plan and
|
||||||
|
* the phone timeline alike: the leg's two ends and the time its origin is
|
||||||
|
* planned for. Between two city walks (CW-08) it runs from the first walk's
|
||||||
|
* last stop to the next one's first, departing when the first one ends, and a
|
||||||
|
* saved journey that now arrives after the next walk starts says so. Nothing
|
||||||
|
* is saved here: the search opens, and only the connection picked there is
|
||||||
|
* added to the day. Only the last leg asked for opens it, and none after the
|
||||||
|
* view is gone.
|
||||||
|
*/
|
||||||
|
export function useTransitLegPlanner({
|
||||||
|
tripId,
|
||||||
|
assignments,
|
||||||
|
accommodations,
|
||||||
|
reservations,
|
||||||
|
places,
|
||||||
|
toursEnabled,
|
||||||
|
tourOf,
|
||||||
|
onPlan,
|
||||||
|
}: TransitLegPlannerDeps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
// Coordinates back to names, over every located place, hotel and booking endpoint of the trip.
|
||||||
|
const names = useMemo(
|
||||||
|
() => buildTransitNameIndex(assignments, accommodations, reservations),
|
||||||
|
[assignments, accommodations, reservations]
|
||||||
|
);
|
||||||
|
|
||||||
|
const legFor = useCallback(
|
||||||
|
(dayId: number, seg?: RouteSegment): TransitLeg | null =>
|
||||||
|
onPlan ? buildTransitLeg(seg, dayId, names, assignments, reservations) : null,
|
||||||
|
[onPlan, names, assignments, reservations]
|
||||||
|
);
|
||||||
|
|
||||||
|
// The walks' stops being read for the leg asked for last; a later leg, or leaving the view, drops them.
|
||||||
|
const pending = useRef<AbortController | null>(null);
|
||||||
|
useEffect(() => () => pending.current?.abort(), []);
|
||||||
|
|
||||||
|
/** Opens the search for a leg, told by the entry it leaves where the connector carries one. */
|
||||||
|
const plan = useCallback(
|
||||||
|
(dayId: number, leg: TransitLeg, originId?: number) => {
|
||||||
|
if (!onPlan) return;
|
||||||
|
pending.current?.abort();
|
||||||
|
const day = [...(assignments[String(dayId)] ?? [])].sort((a, b) => a.order_index - b.order_index);
|
||||||
|
const pair = toursEnabled ? walkPairAt(projectDayItinerary(day, true, places), leg, tourOf, originId) : null;
|
||||||
|
if (!pair) {
|
||||||
|
onPlan({ dayId, ...leg });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const controller = new AbortController();
|
||||||
|
pending.current = controller;
|
||||||
|
// The stops name the ends; read from this device's copy when offline, so the search waits only for them.
|
||||||
|
void Promise.all([
|
||||||
|
stopsOrNull(tripId, pair.first.item.placeId, controller.signal),
|
||||||
|
stopsOrNull(tripId, pair.next.item.placeId, controller.signal),
|
||||||
|
]).then(([first, next]) => {
|
||||||
|
if (controller.signal.aborted) return;
|
||||||
|
onPlan({ dayId, ...walkTransitLeg({ leg, dayId, pair, stops: { first, next }, places, t }) });
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[onPlan, assignments, toursEnabled, places, tourOf, tripId, t]
|
||||||
|
);
|
||||||
|
|
||||||
|
/** A saved journey on a day that arrives after the walk it leads to starts; null otherwise. */
|
||||||
|
const lateBefore = useCallback(
|
||||||
|
(day: Pick<Day, 'date'>, reservation: Reservation, following: readonly MergedItem[]): WalkLate | null =>
|
||||||
|
toursEnabled ? journeyLate({ reservation, following, date: day.date ?? null, tourOf }) : null,
|
||||||
|
[toursEnabled, tourOf]
|
||||||
|
);
|
||||||
|
|
||||||
|
return { legFor, plan, lateBefore };
|
||||||
|
}
|
||||||
@@ -64,4 +64,26 @@ describe('ToggleSwitch', () => {
|
|||||||
rerender(<ToggleSwitch on={true} onToggle={() => {}} />);
|
rerender(<ToggleSwitch on={true} onToggle={() => {}} />);
|
||||||
expect(button.querySelector('span')!.style.left).toBe('22px');
|
expect(button.querySelector('span')!.style.left).toBe('22px');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('FE-COMP-TOGGLESWITCH-009: a disabled switch is out of reach and says so', async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
const onToggle = vi.fn();
|
||||||
|
render(<ToggleSwitch on={false} onToggle={onToggle} disabled />);
|
||||||
|
const button = screen.getByRole('button');
|
||||||
|
expect(button).toBeDisabled();
|
||||||
|
expect(button).toHaveAttribute('aria-disabled', 'true');
|
||||||
|
expect(button.style.cursor).toBe('not-allowed');
|
||||||
|
await user.click(button);
|
||||||
|
await user.tab();
|
||||||
|
expect(onToggle).not.toHaveBeenCalled();
|
||||||
|
expect(button).not.toHaveFocus();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-COMP-TOGGLESWITCH-010: an enabled switch keeps the pointer and no aria-disabled', () => {
|
||||||
|
render(<ToggleSwitch on={false} onToggle={() => {}} />);
|
||||||
|
const button = screen.getByRole('button');
|
||||||
|
expect(button).toBeEnabled();
|
||||||
|
expect(button).not.toHaveAttribute('aria-disabled');
|
||||||
|
expect(button.style.cursor).toBe('pointer');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -5,16 +5,18 @@ const EASE = 'cubic-bezier(0.32, 0.72, 0, 1)'
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* `describedBy` names the element that explains the switch, for a switch whose label alone
|
* `describedBy` names the element that explains the switch, for a switch whose label alone
|
||||||
* does not say what flipping it changes.
|
* does not say what flipping it changes. `disabled` takes it out of the tab order and tells
|
||||||
|
* assistive tech it cannot act; the caller dims it and says why.
|
||||||
*/
|
*/
|
||||||
export default function ToggleSwitch({ on, onToggle, label, describedBy }: { on: boolean; onToggle: () => void; label?: string; describedBy?: string }) {
|
export default function ToggleSwitch({ on, onToggle, label, describedBy, disabled = false }: { on: boolean; onToggle: () => void; label?: string; describedBy?: string; disabled?: boolean }) {
|
||||||
return (
|
return (
|
||||||
<button type="button" onClick={onToggle} aria-pressed={on} aria-label={label} aria-describedby={describedBy}
|
<button type="button" onClick={onToggle} aria-pressed={on} aria-label={label} aria-describedby={describedBy}
|
||||||
|
disabled={disabled} aria-disabled={disabled || undefined}
|
||||||
// A keyboard focus ring in the text colour, like the fields; the pointer gets none.
|
// A keyboard focus ring in the text colour, like the fields; the pointer gets none.
|
||||||
className="group outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--text-primary)] focus-visible:ring-offset-2 focus-visible:ring-offset-[color:var(--bg-card)]"
|
className="group outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--text-primary)] focus-visible:ring-offset-2 focus-visible:ring-offset-[color:var(--bg-card)]"
|
||||||
style={{
|
style={{
|
||||||
position: 'relative', width: 44, height: 24, minWidth: 44, flexShrink: 0,
|
position: 'relative', width: 44, height: 24, minWidth: 44, flexShrink: 0,
|
||||||
borderRadius: 12, border: 'none', padding: 0, cursor: 'pointer',
|
borderRadius: 12, border: 'none', padding: 0, cursor: disabled ? 'not-allowed' : 'pointer',
|
||||||
background: on ? 'var(--accent, #111827)' : 'var(--border-primary, #d1d5db)',
|
background: on ? 'var(--accent, #111827)' : 'var(--border-primary, #d1d5db)',
|
||||||
boxShadow: 'inset 0 1px 2px color-mix(in srgb, var(--text-primary) 12%, transparent)',
|
boxShadow: 'inset 0 1px 2px color-mix(in srgb, var(--text-primary) 12%, transparent)',
|
||||||
transition: `background 0.2s ${EASE}`,
|
transition: `background 0.2s ${EASE}`,
|
||||||
|
|||||||
@@ -16,11 +16,14 @@ import {
|
|||||||
} from './settingsKit';
|
} from './settingsKit';
|
||||||
import ToggleSwitch from './ToggleSwitch';
|
import ToggleSwitch from './ToggleSwitch';
|
||||||
import { useWandererConnection } from './useWandererConnection';
|
import { useWandererConnection } from './useWandererConnection';
|
||||||
|
import WandererWatchRow from './WandererWatchRow';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Settings → Integrations → wanderer: the reader's own trail database, from
|
* Settings → Integrations → wanderer: the reader's own trail database, from
|
||||||
* which the Tours workspace imports trails. Laid out like the Dawarich and
|
* which the Tours workspace imports trails. Laid out like the Dawarich and
|
||||||
* AirTrail cards beside it; the behaviour is in `useWandererConnection`.
|
* AirTrail cards beside it; the behaviour is in `useWandererConnection`.
|
||||||
|
* Under the form, the optional background check of the imported trails
|
||||||
|
* (WAN-02), which switches on its own and needs no save.
|
||||||
*/
|
*/
|
||||||
export default function WandererConnectionSection(): React.ReactElement {
|
export default function WandererConnectionSection(): React.ReactElement {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -136,6 +139,8 @@ export default function WandererConnectionSection(): React.ReactElement {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<WandererWatchRow refreshKey={S.checkKey} />
|
||||||
</Section>
|
</Section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import userEvent from '@testing-library/user-event';
|
||||||
|
import type { WandererSourceHintItem, WandererWatch } from '@trek/shared';
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { render, screen, waitFor, within } from '../../../tests/helpers/render';
|
||||||
|
import WandererWatchRow from './WandererWatchRow';
|
||||||
|
|
||||||
|
const repo = vi.hoisted(() => ({ getWatch: vi.fn(), setWatch: vi.fn() }));
|
||||||
|
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }));
|
||||||
|
const navigate = vi.hoisted(() => vi.fn());
|
||||||
|
vi.mock('../../repo/wandererRepo', () => ({ wandererRepo: repo }));
|
||||||
|
vi.mock('../shared/Toast', () => ({ useToast: () => toast }));
|
||||||
|
vi.mock('react-router', async () => ({
|
||||||
|
...(await vi.importActual<typeof import('react-router')>('react-router')),
|
||||||
|
useNavigate: () => navigate,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const off: WandererWatch = {
|
||||||
|
enabled: false,
|
||||||
|
connected: true,
|
||||||
|
lastRunAt: null,
|
||||||
|
pausedUntil: null,
|
||||||
|
blocked: false,
|
||||||
|
hints: [],
|
||||||
|
};
|
||||||
|
const hints: WandererSourceHintItem[] = [
|
||||||
|
{
|
||||||
|
placeId: 7,
|
||||||
|
tripId: 3,
|
||||||
|
tripTitle: 'Alps',
|
||||||
|
tourName: 'Ridge',
|
||||||
|
state: 'changed',
|
||||||
|
changes: ['name'],
|
||||||
|
reason: null,
|
||||||
|
externalUpdated: '2026-10-14',
|
||||||
|
checkedAt: '2026-10-20T10:00:00Z',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
placeId: 8,
|
||||||
|
tripId: 3,
|
||||||
|
tripTitle: 'Alps',
|
||||||
|
tourName: 'Gorge',
|
||||||
|
state: 'unverifiable',
|
||||||
|
changes: [],
|
||||||
|
reason: 'unavailable',
|
||||||
|
externalUpdated: null,
|
||||||
|
checkedAt: '2026-10-19T10:00:00Z',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('WandererWatchRow (WAN-02)', () => {
|
||||||
|
it('is off by default and dimmed, not hidden, without a connection', async () => {
|
||||||
|
repo.getWatch.mockResolvedValue({ ...off, connected: false });
|
||||||
|
render(<WandererWatchRow refreshKey="false||" />);
|
||||||
|
await waitFor(() => expect(repo.getWatch).toHaveBeenCalled());
|
||||||
|
const toggle = await screen.findByRole('button', { name: 'Check my trails for changes', pressed: false });
|
||||||
|
expect(toggle).toHaveAttribute('aria-pressed', 'false');
|
||||||
|
expect(toggle).toBeDisabled();
|
||||||
|
expect(toggle).toHaveAttribute('aria-disabled', 'true');
|
||||||
|
await userEvent.tab();
|
||||||
|
expect(toggle).not.toHaveFocus();
|
||||||
|
expect(screen.queryByTestId('wanderer-watch-status')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('switches on at once and then says when it last looked', async () => {
|
||||||
|
repo.getWatch.mockResolvedValue(off);
|
||||||
|
repo.setWatch.mockResolvedValue({ ...off, enabled: true });
|
||||||
|
render(<WandererWatchRow refreshKey="true||" />);
|
||||||
|
const toggle = await screen.findByRole('button', { name: 'Check my trails for changes', pressed: false });
|
||||||
|
await waitFor(() => expect(toggle).toBeEnabled());
|
||||||
|
await userEvent.click(toggle);
|
||||||
|
expect(repo.setWatch).toHaveBeenCalledWith(true);
|
||||||
|
expect(await screen.findByText('Not looked yet')).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('button', { name: /Hints/ })).toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('counts the open hints on the button and opens each tour from the dialog', async () => {
|
||||||
|
repo.getWatch.mockResolvedValue({ ...off, enabled: true, lastRunAt: '2026-10-20T10:00:00Z', hints });
|
||||||
|
render(<WandererWatchRow refreshKey="true||" />);
|
||||||
|
expect(await screen.findByTestId('wanderer-hint-count')).toHaveTextContent('2');
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: /Hints/ }));
|
||||||
|
|
||||||
|
const dialog = await screen.findByRole('dialog');
|
||||||
|
expect(within(dialog).getByText('Hints on your trails')).toBeInTheDocument();
|
||||||
|
expect(within(dialog).getByText('2 open hints')).toBeInTheDocument();
|
||||||
|
const ridge = within(dialog).getByTestId('wanderer-hint-7');
|
||||||
|
expect(within(ridge).getByText('Changed')).toBeInTheDocument();
|
||||||
|
expect(within(ridge).getByText('Name')).toBeInTheDocument();
|
||||||
|
expect(within(within(dialog).getByTestId('wanderer-hint-8')).getByText('Trail out of reach')).toBeInTheDocument();
|
||||||
|
|
||||||
|
await userEvent.click(ridge);
|
||||||
|
expect(navigate).toHaveBeenCalledWith('/trips/3?tab=plan&place=7');
|
||||||
|
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
|
||||||
|
});
|
||||||
|
|
||||||
|
it('names a refused token instead of a last look', async () => {
|
||||||
|
repo.getWatch.mockResolvedValue({ ...off, enabled: true, blocked: true });
|
||||||
|
render(<WandererWatchRow refreshKey="true||" />);
|
||||||
|
expect(await screen.findByText('Token refused')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import { BellRing } from 'lucide-react';
|
||||||
|
import React from 'react';
|
||||||
|
import { useTranslation } from '../../i18n';
|
||||||
|
import { fs } from '../shared/DialogShell';
|
||||||
|
import { Tooltip } from '../shared/Tooltip';
|
||||||
|
import { InfoDot } from '../Tours/tourParts';
|
||||||
|
import WandererHintsDialog from '../Tours/wanderer/WandererHintsDialog';
|
||||||
|
import { SETTINGS_BUTTON, SettingRow, SettingRows, StatusPill } from './settingsKit';
|
||||||
|
import ToggleSwitch from './ToggleSwitch';
|
||||||
|
import { useWandererWatch, type WandererWatchController } from './useWandererWatch';
|
||||||
|
|
||||||
|
/** The switch, dimmed with a word on why while there is no connection to watch with. */
|
||||||
|
function WatchSwitch({ W }: { W: WandererWatchController }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const off = !W.available;
|
||||||
|
// A disabled button takes no focus and, in some browsers, no hover either, so
|
||||||
|
// the reason sits on a focusable wrapper the tooltip listens to. The wrapper
|
||||||
|
// stays once the switch can be used, so the button is never mounted anew and
|
||||||
|
// keeps its focus when the connection is known.
|
||||||
|
return (
|
||||||
|
<Tooltip label={t('wanderer.watch.notConnected')} disabled={!off}>
|
||||||
|
<span
|
||||||
|
tabIndex={off ? 0 : undefined}
|
||||||
|
className={`inline-flex rounded-full outline-none ${off ? 'cursor-not-allowed opacity-50 focus-visible:ring-2 focus-visible:ring-[color:var(--text-primary)] focus-visible:ring-offset-2 focus-visible:ring-offset-[color:var(--bg-card)]' : ''}`}
|
||||||
|
>
|
||||||
|
<span className={`inline-flex ${off ? 'pointer-events-none' : ''}`}>
|
||||||
|
<ToggleSwitch
|
||||||
|
on={W.enabled}
|
||||||
|
onToggle={() => void W.toggle()}
|
||||||
|
label={t('wanderer.watch.label')}
|
||||||
|
disabled={off}
|
||||||
|
/>
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</Tooltip>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The open hints behind a button, their number as a badge on its corner; dimmed while there are none. */
|
||||||
|
function HintsButton({ W }: { W: WandererWatchController }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const count = W.hints.length;
|
||||||
|
return (
|
||||||
|
<Tooltip label={count ? t('wanderer.watch.hintsCount', { count }) : t('wanderer.watch.empty')}>
|
||||||
|
<span className="inline-flex">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={W.openHints}
|
||||||
|
disabled={count === 0}
|
||||||
|
className={`${SETTINGS_BUTTON} relative`}
|
||||||
|
style={fs(12.5, 'body')}
|
||||||
|
>
|
||||||
|
<BellRing size={13} strokeWidth={2.2} />
|
||||||
|
{t('wanderer.watch.hints')}
|
||||||
|
{count > 0 && (
|
||||||
|
<span
|
||||||
|
aria-label={t('wanderer.watch.hintsCount', { count })}
|
||||||
|
data-testid="wanderer-hint-count"
|
||||||
|
className="absolute -end-1.5 -top-1.5 grid h-[18px] min-w-[18px] place-items-center rounded-full bg-accent px-1 font-geist font-semibold tabular-nums text-accent-text ring-2 ring-[color:var(--bg-card)]"
|
||||||
|
style={fs(10)}
|
||||||
|
>
|
||||||
|
{count}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
</Tooltip>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WAN-02 in the wanderer card: the optional background check of the user's
|
||||||
|
* own imported trails. Off until switched on; while on, what it last did and
|
||||||
|
* its open hints, which open in a dialog that leads to each tour.
|
||||||
|
*/
|
||||||
|
export default function WandererWatchRow({ refreshKey }: { refreshKey: string }): React.ReactElement {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const W = useWandererWatch(refreshKey);
|
||||||
|
return (
|
||||||
|
<SettingRows>
|
||||||
|
<SettingRow
|
||||||
|
label={
|
||||||
|
<span className="inline-flex items-center gap-1.5">
|
||||||
|
{t('wanderer.watch.label')}
|
||||||
|
<InfoDot label={t('wanderer.watch.label')} description={t('wanderer.watch.info')} />
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
hint={t('wanderer.watch.hint')}
|
||||||
|
dimmed={W.saving}
|
||||||
|
control={<WatchSwitch W={W} />}
|
||||||
|
>
|
||||||
|
{W.status && (
|
||||||
|
<div className="flex flex-wrap items-center gap-2" data-testid="wanderer-watch-status">
|
||||||
|
<Tooltip label={W.status.why ?? ''} disabled={!W.status.why}>
|
||||||
|
<span className="inline-flex">
|
||||||
|
<StatusPill tone={W.status.tone}>{W.status.text}</StatusPill>
|
||||||
|
</span>
|
||||||
|
</Tooltip>
|
||||||
|
<span className="ms-auto">
|
||||||
|
<HintsButton W={W} />
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</SettingRow>
|
||||||
|
<WandererHintsDialog open={W.hintsOpen} hints={W.hints} onClose={W.closeHints} onOpenTour={W.openTour} />
|
||||||
|
</SettingRows>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -27,6 +27,7 @@ export const EVENT_LABEL_KEYS: Record<string, string> = {
|
|||||||
photos_shared: 'settings.notifyPhotosShared',
|
photos_shared: 'settings.notifyPhotosShared',
|
||||||
collab_message: 'settings.notifyCollabMessage',
|
collab_message: 'settings.notifyCollabMessage',
|
||||||
packing_tagged: 'settings.notifyPackingTagged',
|
packing_tagged: 'settings.notifyPackingTagged',
|
||||||
|
wanderer_source_hint: 'settings.notifyWandererSourceHint',
|
||||||
version_available: 'settings.notifyVersionAvailable',
|
version_available: 'settings.notifyVersionAvailable',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -129,6 +129,13 @@ export function useWandererConnection() {
|
|||||||
saved?.lastCheckedAt && saved.lastCheckOk === false && saved.lastCheckError
|
saved?.lastCheckedAt && saved.lastCheckOk === false && saved.lastCheckError
|
||||||
? errorText(saved.lastCheckError)
|
? errorText(saved.lastCheckError)
|
||||||
: null;
|
: null;
|
||||||
|
/**
|
||||||
|
* Changes whenever the server's view of the connection does: connecting,
|
||||||
|
* disconnecting, a saved token (which clears the last check) or a test that
|
||||||
|
* stored a new result. The watch row re-reads itself on it, since each of
|
||||||
|
* those can lift or set its "token refused" state.
|
||||||
|
*/
|
||||||
|
const checkKey = `${connected}|${saved?.lastCheckedAt ?? ''}|${saved?.lastCheckOk ?? ''}`;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
url,
|
url,
|
||||||
@@ -145,6 +152,7 @@ export function useWandererConnection() {
|
|||||||
tokenInvalid,
|
tokenInvalid,
|
||||||
canSave,
|
canSave,
|
||||||
lastCheck,
|
lastCheck,
|
||||||
|
checkKey,
|
||||||
save,
|
save,
|
||||||
test,
|
test,
|
||||||
disconnect,
|
disconnect,
|
||||||
|
|||||||
@@ -0,0 +1,148 @@
|
|||||||
|
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||||
|
import type { WandererSourceHintItem, WandererWatch } from '@trek/shared';
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { useWandererWatch, watchStatusOf } from './useWandererWatch';
|
||||||
|
|
||||||
|
const repo = vi.hoisted(() => ({ getWatch: vi.fn(), setWatch: vi.fn() }));
|
||||||
|
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }));
|
||||||
|
const navigate = vi.hoisted(() => vi.fn());
|
||||||
|
vi.mock('../../repo/wandererRepo', () => ({ wandererRepo: repo }));
|
||||||
|
vi.mock('../shared/Toast', () => ({ useToast: () => toast }));
|
||||||
|
vi.mock('../../i18n', () => ({
|
||||||
|
useTranslation: () => ({
|
||||||
|
t: (key: string, params?: Record<string, unknown>) => (params ? `${key} ${JSON.stringify(params)}` : key),
|
||||||
|
locale: 'en',
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
vi.mock('react-router', async () => ({
|
||||||
|
...(await vi.importActual<typeof import('react-router')>('react-router')),
|
||||||
|
useNavigate: () => navigate,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const t = (key: string) => key;
|
||||||
|
const off: WandererWatch = {
|
||||||
|
enabled: false,
|
||||||
|
connected: true,
|
||||||
|
lastRunAt: null,
|
||||||
|
pausedUntil: null,
|
||||||
|
blocked: false,
|
||||||
|
hints: [],
|
||||||
|
};
|
||||||
|
const hint: WandererSourceHintItem = {
|
||||||
|
placeId: 7,
|
||||||
|
tripId: 3,
|
||||||
|
tripTitle: 'Alps',
|
||||||
|
tourName: 'Ridge',
|
||||||
|
state: 'possible_change',
|
||||||
|
changes: [],
|
||||||
|
reason: null,
|
||||||
|
externalUpdated: '2026-10-14',
|
||||||
|
checkedAt: '2026-10-20T10:00:00Z',
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
repo.getWatch.mockResolvedValue(off);
|
||||||
|
repo.setWatch.mockImplementation(async (enabled: boolean) => ({ ...off, enabled }));
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('watchStatusOf (WAN-02)', () => {
|
||||||
|
const now = Date.parse('2026-10-20T12:00:00Z');
|
||||||
|
|
||||||
|
it('says nothing while the watch is off', () => {
|
||||||
|
expect(watchStatusOf(null, t, 'en', now)).toBeNull();
|
||||||
|
expect(watchStatusOf(off, t, 'en', now)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('names a refused token first, then a pause still running, then the last look', () => {
|
||||||
|
const on = { ...off, enabled: true };
|
||||||
|
expect(watchStatusOf({ ...on, blocked: true, pausedUntil: '2026-10-21T00:00:00Z' }, t, 'en', now)).toEqual({
|
||||||
|
tone: 'danger',
|
||||||
|
text: 'wanderer.watch.blocked',
|
||||||
|
why: 'wanderer.watch.blockedHint',
|
||||||
|
});
|
||||||
|
expect(watchStatusOf({ ...on, pausedUntil: '2026-10-20T14:00:00Z' }, t, 'en', now)).toMatchObject({
|
||||||
|
tone: 'warning',
|
||||||
|
text: 'wanderer.watch.paused',
|
||||||
|
why: 'wanderer.watch.pausedHint',
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
watchStatusOf({ ...on, pausedUntil: '2026-10-20T11:00:00Z', lastRunAt: '2026-10-20T10:00:00Z' }, t, 'en', now)
|
||||||
|
).toEqual({ tone: 'neutral', text: 'wanderer.watch.lastRun', why: null });
|
||||||
|
expect(watchStatusOf(on, t, 'en', now)).toEqual({ tone: 'neutral', text: 'wanderer.watch.neverRun', why: null });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('useWandererWatch (WAN-02)', () => {
|
||||||
|
it('loads with the card and again when the connection comes or goes', async () => {
|
||||||
|
const { result, rerender } = renderHook(({ refreshKey }) => useWandererWatch(refreshKey), {
|
||||||
|
initialProps: { refreshKey: 'true||' },
|
||||||
|
});
|
||||||
|
await waitFor(() => expect(result.current.available).toBe(true));
|
||||||
|
expect(result.current.enabled).toBe(false);
|
||||||
|
expect(result.current.status).toBeNull();
|
||||||
|
rerender({ refreshKey: 'true||' });
|
||||||
|
expect(repo.getWatch).toHaveBeenCalledTimes(1);
|
||||||
|
rerender({ refreshKey: 'false||' });
|
||||||
|
await waitFor(() => expect(repo.getWatch).toHaveBeenCalledTimes(2));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('drops a refused token once a connection test passes, without a reload', async () => {
|
||||||
|
repo.getWatch.mockResolvedValueOnce({ ...off, enabled: true, blocked: true, pausedUntil: '2999-01-01T00:00:00Z' });
|
||||||
|
repo.getWatch.mockResolvedValueOnce({ ...off, enabled: true, lastRunAt: '2026-10-20T10:00:00Z' });
|
||||||
|
const { result, rerender } = renderHook(({ refreshKey }) => useWandererWatch(refreshKey), {
|
||||||
|
initialProps: { refreshKey: 'true|2026-10-20T09:00:00Z|false' },
|
||||||
|
});
|
||||||
|
await waitFor(() => expect(result.current.status?.text).toBe('wanderer.watch.blocked'));
|
||||||
|
rerender({ refreshKey: 'true|2026-10-20T11:00:00Z|true' });
|
||||||
|
await waitFor(() => expect(result.current.status?.tone).toBe('neutral'));
|
||||||
|
expect(result.current.status?.text).toMatch(/^wanderer\.watch\.lastRun/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('switches at once, and says so either way', async () => {
|
||||||
|
const { result } = renderHook(() => useWandererWatch('true||'));
|
||||||
|
await waitFor(() => expect(result.current.available).toBe(true));
|
||||||
|
await act(async () => {
|
||||||
|
await result.current.toggle();
|
||||||
|
});
|
||||||
|
expect(repo.setWatch).toHaveBeenCalledWith(true);
|
||||||
|
expect(result.current.enabled).toBe(true);
|
||||||
|
expect(toast.success).toHaveBeenCalledWith('wanderer.watch.on');
|
||||||
|
|
||||||
|
repo.setWatch.mockRejectedValueOnce(new Error('down'));
|
||||||
|
await act(async () => {
|
||||||
|
await result.current.toggle();
|
||||||
|
});
|
||||||
|
expect(toast.error).toHaveBeenCalledWith('wanderer.watch.failed');
|
||||||
|
expect(result.current.enabled).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('leaves the switch alone without a connection, or when the watch could not be read', async () => {
|
||||||
|
repo.getWatch.mockResolvedValueOnce({ ...off, connected: false });
|
||||||
|
const { result } = renderHook(() => useWandererWatch('false||'));
|
||||||
|
await waitFor(() => expect(repo.getWatch).toHaveBeenCalled());
|
||||||
|
await act(async () => {
|
||||||
|
await result.current.toggle();
|
||||||
|
});
|
||||||
|
expect(repo.setWatch).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
repo.getWatch.mockRejectedValueOnce(new Error('offline'));
|
||||||
|
const failed = renderHook(() => useWandererWatch('true||'));
|
||||||
|
await waitFor(() => expect(repo.getWatch).toHaveBeenCalledTimes(2));
|
||||||
|
expect(failed.result.current.available).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lists the hints and opens the tour one is about', async () => {
|
||||||
|
repo.getWatch.mockResolvedValue({ ...off, enabled: true, hints: [hint] });
|
||||||
|
const { result } = renderHook(() => useWandererWatch('true||'));
|
||||||
|
await waitFor(() => expect(result.current.hints).toEqual([hint]));
|
||||||
|
act(() => result.current.openHints());
|
||||||
|
expect(result.current.hintsOpen).toBe(true);
|
||||||
|
act(() => result.current.openTour(hint));
|
||||||
|
expect(navigate).toHaveBeenCalledWith('/trips/3?tab=plan&place=7');
|
||||||
|
expect(result.current.hintsOpen).toBe(false);
|
||||||
|
act(() => result.current.openHints());
|
||||||
|
act(() => result.current.closeHints());
|
||||||
|
expect(result.current.hintsOpen).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
import type { WandererSourceHintItem, WandererWatch } from '@trek/shared';
|
||||||
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
|
import { useNavigate } from 'react-router';
|
||||||
|
import { useTranslation } from '../../i18n';
|
||||||
|
import { wandererRepo } from '../../repo/wandererRepo';
|
||||||
|
import { useToast } from '../shared/Toast';
|
||||||
|
import { hintWhen } from '../Tours/wanderer/hintWhen';
|
||||||
|
|
||||||
|
type Translate = (key: string, params?: Record<string, unknown>) => string;
|
||||||
|
|
||||||
|
/** What the watch last did, as one pill: refused, waiting after errors, last looked, or not yet. */
|
||||||
|
interface WandererWatchStatus {
|
||||||
|
tone: 'neutral' | 'warning' | 'danger';
|
||||||
|
text: string;
|
||||||
|
/** Why, for the tooltip; null where the text says it all. */
|
||||||
|
why: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The pill for a switched-on watch; null while it is off, since then nothing runs to report on. */
|
||||||
|
export function watchStatusOf(
|
||||||
|
watch: WandererWatch | null,
|
||||||
|
t: Translate,
|
||||||
|
locale: string,
|
||||||
|
now = Date.now()
|
||||||
|
): WandererWatchStatus | null {
|
||||||
|
if (!watch?.enabled) return null;
|
||||||
|
if (watch.blocked) return { tone: 'danger', text: t('wanderer.watch.blocked'), why: t('wanderer.watch.blockedHint') };
|
||||||
|
const pausedUntil = watch.pausedUntil ? new Date(watch.pausedUntil).getTime() : Number.NaN;
|
||||||
|
if (pausedUntil > now) {
|
||||||
|
return {
|
||||||
|
tone: 'warning',
|
||||||
|
text: t('wanderer.watch.paused', { time: hintWhen(watch.pausedUntil, locale) }),
|
||||||
|
why: t('wanderer.watch.pausedHint'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const lastRun = hintWhen(watch.lastRunAt, locale);
|
||||||
|
return {
|
||||||
|
tone: 'neutral',
|
||||||
|
text: lastRun ? t('wanderer.watch.lastRun', { date: lastRun }) : t('wanderer.watch.neverRun'),
|
||||||
|
why: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WAN-02: the background watch in the wanderer card. It loads with the card
|
||||||
|
* and again whenever `refreshKey` changes, which the connection card bumps on
|
||||||
|
* connecting, disconnecting, saving a token and a stored test result, so a
|
||||||
|
* refused token clears once it is fixed. It switches on and off at
|
||||||
|
* once (there is nothing to save with the form), and opens the tour a hint is
|
||||||
|
* about. Online-only like the rest of the connection: the watch runs on the
|
||||||
|
* server and its hints are read from there.
|
||||||
|
*/
|
||||||
|
export function useWandererWatch(refreshKey: string) {
|
||||||
|
const { t, locale } = useTranslation();
|
||||||
|
const toast = useToast();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const [watch, setWatch] = useState<WandererWatch | null>(null);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [hintsOpen, setHintsOpen] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
wandererRepo.getWatch().then(
|
||||||
|
(next) => {
|
||||||
|
if (!cancelled) setWatch(next);
|
||||||
|
},
|
||||||
|
() => {
|
||||||
|
// The card above already says when the connection cannot be read; without
|
||||||
|
// an answer the switch simply stays dimmed.
|
||||||
|
if (!cancelled) setWatch(null);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [refreshKey]);
|
||||||
|
|
||||||
|
const toggle = useCallback(async () => {
|
||||||
|
if (!watch?.connected || saving) return;
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
const next = await wandererRepo.setWatch(!watch.enabled);
|
||||||
|
setWatch(next);
|
||||||
|
toast.success(next.enabled ? t('wanderer.watch.on') : t('wanderer.watch.off'));
|
||||||
|
} catch {
|
||||||
|
toast.error(t('wanderer.watch.failed'));
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
}, [saving, t, toast, watch]);
|
||||||
|
|
||||||
|
const openTour = useCallback(
|
||||||
|
(hint: WandererSourceHintItem) => {
|
||||||
|
setHintsOpen(false);
|
||||||
|
void navigate(`/trips/${hint.tripId}?tab=plan&place=${hint.placeId}`);
|
||||||
|
},
|
||||||
|
[navigate]
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
/** The switch can act: the server knows a connection to watch with. */
|
||||||
|
available: !!watch?.connected,
|
||||||
|
enabled: !!watch?.enabled,
|
||||||
|
saving,
|
||||||
|
status: watchStatusOf(watch, t, locale),
|
||||||
|
hints: watch?.hints ?? [],
|
||||||
|
hintsOpen,
|
||||||
|
openHints: useCallback(() => setHintsOpen(true), []),
|
||||||
|
closeHints: useCallback(() => setHintsOpen(false), []),
|
||||||
|
openTour,
|
||||||
|
toggle,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export type WandererWatchController = ReturnType<typeof useWandererWatch>;
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
import {
|
||||||
|
BIKE_PROFILES,
|
||||||
|
importableTourTypeSchema,
|
||||||
|
type BikeProfile,
|
||||||
|
type PaddleBoatType,
|
||||||
|
type PaddleWaterContext,
|
||||||
|
} from '@trek/shared';
|
||||||
|
import { Info } from 'lucide-react';
|
||||||
|
import { useId } from 'react';
|
||||||
|
import { useTranslation } from '../../i18n';
|
||||||
|
import { LABEL, Segmented } from '../shared/dialogParts';
|
||||||
|
import { DialogSection } from '../shared/DialogShell';
|
||||||
|
import type { GpxImportChoicesState } from './gpxImportChoices';
|
||||||
|
import { RecordedRideFacts } from './horse/RecordedRideFacts';
|
||||||
|
import { TourTypeSelect } from './planner/TourTypeSelect';
|
||||||
|
import { RunProfileField } from './run/RunFields';
|
||||||
|
import { SkiClassificationFields } from './ski/SkiClassificationFields';
|
||||||
|
import { TourNotice } from './tourParts';
|
||||||
|
|
||||||
|
const BOATS: readonly PaddleBoatType[] = ['kayak', 'canoe', 'sup', 'other'];
|
||||||
|
const WATERS: readonly PaddleWaterContext[] = ['river', 'lake'];
|
||||||
|
/** Every type a GPX file can come in as: the planner's, and ski, which is only kept (SKI-02). */
|
||||||
|
const IMPORT_TYPES = importableTourTypeSchema.options;
|
||||||
|
|
||||||
|
/** A paddle import's boat and water, side by side, each chosen on purpose. */
|
||||||
|
function PaddleImportFields({ choices }: { choices: GpxImportChoicesState }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { chosen } = choices;
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div data-testid="gpx-preview-paddle" className="grid grid-cols-1 gap-3 sm:grid-cols-[3fr_2fr]">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<span className={LABEL}>{t('tours.paddle.boat')}</span>
|
||||||
|
<Segmented<PaddleBoatType>
|
||||||
|
value={(chosen.boat ?? '') as PaddleBoatType}
|
||||||
|
onChange={choices.setBoat}
|
||||||
|
label={t('tours.paddle.boat')}
|
||||||
|
fill
|
||||||
|
options={BOATS.map((value) => ({ value, label: t(`tours.paddle.boat.${value}`) }))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<span className={LABEL}>{t('tours.paddle.water')}</span>
|
||||||
|
<Segmented<PaddleWaterContext>
|
||||||
|
value={(chosen.water ?? '') as PaddleWaterContext}
|
||||||
|
onChange={choices.setWater}
|
||||||
|
label={t('tours.paddle.water')}
|
||||||
|
fill
|
||||||
|
options={WATERS.map((value) => ({ value, label: t(`tours.paddle.water.${value}`) }))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{(chosen.boat === null || chosen.water === null) && (
|
||||||
|
<TourNotice role="status" icon={<Info size={13} strokeWidth={2} />}>
|
||||||
|
{t('tours.paddle.chooseBoatImport')}
|
||||||
|
</TourNotice>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The preview's "import as" section: the type, and below it what that type
|
||||||
|
* names: a bike or run profile, a paddle tour's boat and water, a ski track's
|
||||||
|
* discipline and technique (SKI-02), and for a ride (HOR-02) what the import
|
||||||
|
* keeps and does not work out.
|
||||||
|
*/
|
||||||
|
export function GpxImportTypeSection({ choices }: { choices: GpxImportChoicesState }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const typeLabelId = useId();
|
||||||
|
const { chosen } = choices;
|
||||||
|
return (
|
||||||
|
<DialogSection label={<span id={typeLabelId}>{t('tours.import.previewAs')}</span>}>
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
<TourTypeSelect value={chosen.type} onChange={choices.setType} labelId={typeLabelId} types={IMPORT_TYPES} />
|
||||||
|
{chosen.type === 'bike' && (
|
||||||
|
<div data-testid="gpx-preview-bike" className="min-w-0">
|
||||||
|
<span className={LABEL}>{t('tours.bike.profile')}</span>
|
||||||
|
<Segmented<BikeProfile>
|
||||||
|
value={chosen.bikeProfile}
|
||||||
|
onChange={choices.setBikeProfile}
|
||||||
|
label={t('tours.bike.profile')}
|
||||||
|
fill
|
||||||
|
options={BIKE_PROFILES.map((value) => ({ value, label: t(`tours.bike.profile.${value}`) }))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{chosen.type === 'run' && <RunProfileField value={chosen.runProfile} onChange={choices.setRunProfile} />}
|
||||||
|
{chosen.type === 'kayak' && <PaddleImportFields choices={choices} />}
|
||||||
|
{chosen.type === 'ski' && <SkiClassificationFields choice={chosen.ski} onChange={choices.setSki} />}
|
||||||
|
{chosen.type === 'horse' && (
|
||||||
|
<div data-testid="gpx-preview-horse">
|
||||||
|
<RecordedRideFacts />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</DialogSection>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { AlertTriangle, Loader2, RefreshCw, WifiOff } from 'lucide-react';
|
||||||
|
import { useTranslation } from '../../i18n';
|
||||||
|
import { fs } from '../shared/DialogShell';
|
||||||
|
import { CardAction, TourNotice } from './tourParts';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How a card's online read stands while it has no answer to show (a bike
|
||||||
|
* tour's ways, a hike's SAC grades): still asking, offline, or failed with a
|
||||||
|
* way to ask again. Nothing while the answer is there, so the card shows it.
|
||||||
|
*/
|
||||||
|
export function ReadStatusNotice({
|
||||||
|
status,
|
||||||
|
messages,
|
||||||
|
onRetry,
|
||||||
|
}: {
|
||||||
|
status: string;
|
||||||
|
messages: { loading: string; offline: string; failed: string };
|
||||||
|
onRetry: () => void;
|
||||||
|
}) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
if (status === 'loading')
|
||||||
|
return (
|
||||||
|
<span role="status" className="inline-flex items-center gap-1.5 text-content-muted" style={fs(11.5, 'body')}>
|
||||||
|
<Loader2 size={12} strokeWidth={2} className="animate-spin" />
|
||||||
|
{messages.loading}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
if (status === 'offline')
|
||||||
|
return <TourNotice icon={<WifiOff size={13} strokeWidth={2} />}>{messages.offline}</TourNotice>;
|
||||||
|
if (status !== 'failed') return null;
|
||||||
|
return (
|
||||||
|
<TourNotice tone="warning" icon={<AlertTriangle size={13} strokeWidth={2} />}>
|
||||||
|
<span className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||||
|
<span>{messages.failed}</span>
|
||||||
|
<CardAction icon={<RefreshCw size={12} strokeWidth={2} />} onClick={onRetry}>
|
||||||
|
{t('common.errorRetry')}
|
||||||
|
</CardAction>
|
||||||
|
</span>
|
||||||
|
</TourNotice>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import type { LucideIcon } from 'lucide-react';
|
||||||
|
import { Tooltip } from '../shared/Tooltip';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A frosted badge on the top corner of a tour's round tile, carrying one
|
||||||
|
* icon: a ski tour's discipline (SKI-02).
|
||||||
|
* Its tooltip and accessible name say what the icon stands for.
|
||||||
|
*/
|
||||||
|
export function TourCornerMark({
|
||||||
|
icon: Icon,
|
||||||
|
label,
|
||||||
|
size = 15,
|
||||||
|
testId,
|
||||||
|
}: {
|
||||||
|
icon: LucideIcon;
|
||||||
|
label: string;
|
||||||
|
/** The badge's diameter in pixels, about half the tile's. */
|
||||||
|
size?: number;
|
||||||
|
testId: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<span className="absolute -end-1 -top-1 flex">
|
||||||
|
<Tooltip label={label}>
|
||||||
|
<span
|
||||||
|
data-testid={testId}
|
||||||
|
role="img"
|
||||||
|
aria-label={label}
|
||||||
|
className="grid place-items-center rounded-full bg-surface-card text-info shadow-sm ring-1 ring-inset ring-edge-faint"
|
||||||
|
style={{ width: size, height: size }}
|
||||||
|
>
|
||||||
|
<Icon size={Math.round(size * 0.64)} strokeWidth={2.4} aria-hidden="true" />
|
||||||
|
</span>
|
||||||
|
</Tooltip>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
import type { TourListItem } from '@trek/shared';
|
import type { TourListItem } from '@trek/shared';
|
||||||
import { Bike, Footprints, Mountain, Route } from 'lucide-react';
|
import { Bike, Footprints, Mountain, Route } from 'lucide-react';
|
||||||
import { describe, expect, it, vi } from 'vitest';
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
import { paddleBench } from '../../../tests/helpers/paddleCheck';
|
import { paddleBench } from '../../../tests/helpers/paddleCheck';
|
||||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||||
|
import { useTourVisitStore } from '../../store/tourVisitStore';
|
||||||
import TourDayRowFacts, { TourDayRowIcon, TourDayRowPills } from './TourDayRowFacts';
|
import TourDayRowFacts, { TourDayRowIcon, TourDayRowPills } from './TourDayRowFacts';
|
||||||
import { tourDayRowIcon } from './tourDayRowIcon';
|
import { tourDayRowIcon } from './tourDayRowIcon';
|
||||||
|
|
||||||
@@ -34,6 +35,14 @@ describe('RC-01 Tour day-row facts', () => {
|
|||||||
expect(screen.getByTestId('plan-tour-icon').querySelector('.lucide-mountain')).toBeTruthy();
|
expect(screen.getByTestId('plan-tour-icon').querySelector('.lucide-mountain')).toBeTruthy();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('HOR-01: a ride with a recorded time shows the horseshoe beside its riding time', () => {
|
||||||
|
render(<TourDayRowFacts tour={{ ...tour, tour_type: 'horse', max_hiking_difficulty: null }} />);
|
||||||
|
const time = screen.getByTestId('trip-plan-tour-walking-time');
|
||||||
|
expect(time.getAttribute('aria-label')).toMatch(/^Riding time/);
|
||||||
|
expect(time.querySelector('.lucide-horseshoe')).toBeTruthy();
|
||||||
|
expect(time.querySelector('.lucide-footprints')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
it.each([false, true])('renders compact facts with accessible meaning (mobile=%s)', (mobile) => {
|
it.each([false, true])('renders compact facts with accessible meaning (mobile=%s)', (mobile) => {
|
||||||
render(<TourDayRowFacts tour={tour} mobile={mobile} />);
|
render(<TourDayRowFacts tour={tour} mobile={mobile} />);
|
||||||
expect(screen.getByTestId('plan-tour-distance')).toHaveTextContent('4');
|
expect(screen.getByTestId('plan-tour-distance')).toHaveTextContent('4');
|
||||||
@@ -117,6 +126,78 @@ describe('PAD-09 the check bench on a tour row', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("CW-02 a city walk's time on its day row", () => {
|
||||||
|
const walk: TourListItem = {
|
||||||
|
...tour,
|
||||||
|
tour_type: 'walk',
|
||||||
|
duration: 45,
|
||||||
|
break_additional_minutes: 15,
|
||||||
|
max_hiking_difficulty: null,
|
||||||
|
station_count: 3,
|
||||||
|
station_stay_minutes: 120,
|
||||||
|
station_stays_unknown: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
it('shows the walking time and the stays as the planned total, its breaks left out', () => {
|
||||||
|
render(<TourDayRowPills tour={walk} />);
|
||||||
|
const time = screen.getByTestId('trip-plan-tour-time');
|
||||||
|
expect(time).toHaveTextContent('2 h 45 min');
|
||||||
|
expect(time).toHaveAccessibleName('Walking: 45 min, Stays: 2 h, Planned total duration: 2 h 45 min');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('says the total is at least what is known while a stay is not entered', () => {
|
||||||
|
render(<TourDayRowPills tour={{ ...walk, station_stay_minutes: 90, station_stays_unknown: 1 }} />);
|
||||||
|
const time = screen.getByTestId('trip-plan-tour-time');
|
||||||
|
expect(time).toHaveTextContent('≥ 2 h 15 min');
|
||||||
|
expect(time).toHaveAccessibleName(
|
||||||
|
'Walking: 45 min, Stays: at least 1 h 30 min, Planned total duration: at least 2 h 15 min'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the same total among the facts of a phone row, and no breaks', () => {
|
||||||
|
render(<TourDayRowFacts tour={{ ...walk, station_stay_minutes: 90, station_stays_unknown: 1 }} mobile />);
|
||||||
|
expect(screen.getByTestId('trip-plan-tour-planned-duration')).toHaveTextContent('≥ 2 h 15 min');
|
||||||
|
expect(screen.getByTestId('trip-plan-tour-walking-time')).toHaveAccessibleName('Walking: 45 min');
|
||||||
|
expect(screen.queryByTestId('trip-plan-tour-breaks')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("CW-03 a city walk's progress among the facts of a day row", () => {
|
||||||
|
const walk: TourListItem = { ...tour, tour_type: 'walk', max_hiking_difficulty: null, station_count: 5 };
|
||||||
|
|
||||||
|
beforeEach(() =>
|
||||||
|
useTourVisitStore.setState({
|
||||||
|
tripId: '4',
|
||||||
|
byAssignment: { 9: { 'stop-01': 'visited', 'stop-02': 'skipped' } },
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
it.each([false, true])('shows the stops visited on that day, a tap naming them whole (mobile=%s)', (mobile) => {
|
||||||
|
const openRow = vi.fn();
|
||||||
|
render(
|
||||||
|
<div onClick={openRow}>
|
||||||
|
<TourDayRowFacts tour={walk} assignmentId={9} mobile={mobile} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
const progress = screen.getByTestId('plan-walk-progress');
|
||||||
|
expect(progress).toHaveTextContent('1/5');
|
||||||
|
expect(progress).toHaveAccessibleName('1 of 5 visited');
|
||||||
|
fireEvent.click(progress);
|
||||||
|
expect(screen.getByRole('note')).toHaveTextContent('1 of 5 visited');
|
||||||
|
expect(openRow).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows none without a day, or before a stop of that day is marked', () => {
|
||||||
|
render(
|
||||||
|
<>
|
||||||
|
<TourDayRowFacts tour={walk} mobile />
|
||||||
|
<TourDayRowFacts tour={walk} assignmentId={10} mobile />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
expect(screen.queryByTestId('plan-walk-progress')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('the compact facts of a tour list row', () => {
|
describe('the compact facts of a tour list row', () => {
|
||||||
const testIds = () =>
|
const testIds = () =>
|
||||||
[...document.querySelectorAll('[data-testid^="plan-tour"], [data-testid="trip-plan-tour-time"]')].map((el) =>
|
[...document.querySelectorAll('[data-testid^="plan-tour"], [data-testid="trip-plan-tour-time"]')].map((el) =>
|
||||||
@@ -144,3 +225,58 @@ describe('the compact facts of a tour list row', () => {
|
|||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('TIME-01: the estimated time of an import on a row', () => {
|
||||||
|
// 12 km, 300 m up and 500 m down, never timed by the planner: 4 h by DIN 33466.
|
||||||
|
const imported: TourListItem = {
|
||||||
|
...tour,
|
||||||
|
distance: 12,
|
||||||
|
elevation_gain: 300,
|
||||||
|
elevation_loss: 500,
|
||||||
|
duration: null,
|
||||||
|
break_additional_minutes: null,
|
||||||
|
max_hiking_difficulty: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
it('TIME-01-FE-001: a day-plan and list row shows the estimate marked as one, its words saying how it was worked out', () => {
|
||||||
|
render(<TourDayRowPills tour={imported} compact />);
|
||||||
|
const time = screen.getByTestId('trip-plan-tour-time');
|
||||||
|
expect(time).toHaveTextContent('≈ 4 h');
|
||||||
|
expect(time.getAttribute('aria-label')).toBe(
|
||||||
|
'Estimated time: 4 h. Worked out from distance, ascent and descent by the hiking signpost rule (DIN 33466), without breaks.'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('TIME-01-FE-002: a total the travellers entered is the time shown, the estimate kept beside it in the words', () => {
|
||||||
|
render(<TourDayRowPills tour={{ ...imported, planned_duration_minutes: 300 }} />);
|
||||||
|
const time = screen.getByTestId('trip-plan-tour-time');
|
||||||
|
expect(time).toHaveTextContent('5 h');
|
||||||
|
expect(time).not.toHaveTextContent('≈');
|
||||||
|
expect(time.getAttribute('aria-label')).toContain('Estimated time: 4 h');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('TIME-01-FE-003: a phone row shows the estimate as a fact of its own, and an unknown one not at all', () => {
|
||||||
|
const { unmount } = render(<TourDayRowFacts tour={imported} mobile />);
|
||||||
|
expect(screen.getByTestId('trip-plan-tour-estimate')).toHaveTextContent('≈ 4 h');
|
||||||
|
expect(screen.getByTestId('trip-plan-tour-estimate')).toHaveAccessibleName(/^Estimated time: 4 h\. Worked out/);
|
||||||
|
expect(screen.queryByTestId('trip-plan-tour-walking-time')).not.toBeInTheDocument();
|
||||||
|
unmount();
|
||||||
|
render(<TourDayRowFacts tour={{ ...imported, elevation_gain: null, elevation_loss: null }} mobile />);
|
||||||
|
expect(screen.queryByTestId('trip-plan-tour-estimate')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('TIME-01-FE-006: with a total the travellers entered a phone row shows that one time, the estimate in its words', () => {
|
||||||
|
render(<TourDayRowFacts tour={{ ...imported, planned_duration_minutes: 300 }} mobile />);
|
||||||
|
expect(screen.queryByTestId('trip-plan-tour-estimate')).not.toBeInTheDocument();
|
||||||
|
const total = screen.getByTestId('trip-plan-tour-planned-duration');
|
||||||
|
expect(total).toHaveTextContent('5 h');
|
||||||
|
expect(total).not.toHaveTextContent('≈');
|
||||||
|
expect(total.getAttribute('aria-label')).toMatch(/: 5 h\. Estimated time: 4 h\. Worked out/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('TIME-01-FE-004: a tour the planner timed shows its own time and no estimate', () => {
|
||||||
|
render(<TourDayRowFacts tour={tour} />);
|
||||||
|
expect(screen.queryByTestId('trip-plan-tour-estimate')).not.toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId('trip-plan-tour-walking-time')).toHaveAccessibleName('Walking time: 53 min');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { TourListItem } from '@trek/shared';
|
import { importableTourTypeSchema, type TourListItem } from '@trek/shared';
|
||||||
import { ArrowUp, Clock, Pause, Ruler, type LucideIcon } from 'lucide-react';
|
import { ArrowUp, CheckCheck, Clock, Gauge, Pause, Ruler, type LucideIcon } from 'lucide-react';
|
||||||
import { createElement, useId, useState } from 'react';
|
import { createElement, useId, useState } from 'react';
|
||||||
import { useTranslation } from '../../i18n';
|
import { useTranslation } from '../../i18n';
|
||||||
import { useSettingsStore } from '../../store/settingsStore';
|
import { useSettingsStore } from '../../store/settingsStore';
|
||||||
@@ -8,13 +8,37 @@ import { WhiteBadge } from '../Planner/planParts';
|
|||||||
import { fs } from '../shared/DialogShell';
|
import { fs } from '../shared/DialogShell';
|
||||||
import { Tooltip } from '../shared/Tooltip';
|
import { Tooltip } from '../shared/Tooltip';
|
||||||
import { paddleCheckFact } from './paddle/paddleCheckModel';
|
import { paddleCheckFact } from './paddle/paddleCheckModel';
|
||||||
|
import { runPaceText } from './run/runPaceText';
|
||||||
|
import { SkiCornerMark } from './ski/skiMarks';
|
||||||
import { tourDayRowIcon } from './tourDayRowIcon';
|
import { tourDayRowIcon } from './tourDayRowIcon';
|
||||||
import { movingTimeLabel } from './tourFacts';
|
import { movingTimeLabel } from './tourFacts';
|
||||||
import { formatPlannedTourDuration, tourPlannedTimes } from './tourPresentation';
|
import {
|
||||||
|
estimateBadgeText,
|
||||||
|
estimateLabel,
|
||||||
|
formatPlannedTourDuration,
|
||||||
|
plannedTotalText,
|
||||||
|
tourPlannedTimes,
|
||||||
|
type TourPlannedTimes,
|
||||||
|
} from './tourPresentation';
|
||||||
|
import { useWalkProgress } from './walk/walkProgress';
|
||||||
|
import { walkStaysText } from './walk/walkTimeFields';
|
||||||
|
|
||||||
|
/** Whether the app names this type: one it plans or keeps, not a key only the catalogue holds. */
|
||||||
|
function knownType(type: string): boolean {
|
||||||
|
return importableTourTypeSchema.safeParse(type).success;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The icon the time on the move goes by: a bike tour, a ride on horseback, a
|
||||||
|
* run, a paddle or a ski tour by its type's own, any walk by footprints.
|
||||||
|
*/
|
||||||
|
function movingIconType(type: string): string {
|
||||||
|
return type === 'kayak' || type === 'bike' || type === 'run' || type === 'horse' || type === 'ski' ? type : 'walk';
|
||||||
|
}
|
||||||
|
|
||||||
export function TourDayRowIcon({ type, size = 27 }: { type: string; size?: number }) {
|
export function TourDayRowIcon({ type, size = 27 }: { type: string; size?: number }) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const known = ['hike', 'bike', 'walk', 'kayak'].includes(type);
|
const known = knownType(type);
|
||||||
return (
|
return (
|
||||||
<span
|
<span
|
||||||
data-testid="plan-tour-icon"
|
data-testid="plan-tour-icon"
|
||||||
@@ -80,18 +104,38 @@ function Fact({
|
|||||||
/**
|
/**
|
||||||
* A tour's tile in the day plan and in its detail: the T-scale grade in a round
|
* A tour's tile in the day plan and in its detail: the T-scale grade in a round
|
||||||
* tile, the same tile the tour lists use, so a tour reads alike wherever it
|
* tile, the same tile the tour lists use, so a tour reads alike wherever it
|
||||||
* shows. A GPX import has no grade and shows its type's icon instead.
|
* shows. A GPX import has no grade and shows its type's icon instead. A ski
|
||||||
|
* tour's discipline (SKI-02) sits on the tile's corner, as in the tour lists.
|
||||||
*/
|
*/
|
||||||
export function TourDayRowAvatar({
|
export function TourDayRowAvatar({
|
||||||
tour,
|
tour,
|
||||||
size = 32,
|
size = 32,
|
||||||
}: {
|
}: {
|
||||||
tour: Pick<TourListItem, 'tour_type' | 'max_hiking_difficulty'>;
|
tour: Pick<TourListItem, 'tour_type' | 'max_hiking_difficulty'> &
|
||||||
|
Partial<Pick<TourListItem, 'ski_discipline' | 'ski_technique'>>;
|
||||||
size?: number;
|
size?: number;
|
||||||
|
}) {
|
||||||
|
const avatar = <TourGradeAvatar tour={tour} size={size} />;
|
||||||
|
if (tour.tour_type !== 'ski' || !tour.ski_discipline) return avatar;
|
||||||
|
const markSize = Math.round(size * 0.44);
|
||||||
|
return (
|
||||||
|
<span className="relative flex flex-none">
|
||||||
|
{avatar}
|
||||||
|
<SkiCornerMark tour={tour} size={markSize} />
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function TourGradeAvatar({
|
||||||
|
tour,
|
||||||
|
size,
|
||||||
|
}: {
|
||||||
|
tour: Pick<TourListItem, 'tour_type' | 'max_hiking_difficulty'>;
|
||||||
|
size: number;
|
||||||
}) {
|
}) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const level = tour.max_hiking_difficulty;
|
const level = tour.max_hiking_difficulty;
|
||||||
const known = ['hike', 'bike', 'walk', 'kayak'].includes(tour.tour_type);
|
const known = knownType(tour.tour_type);
|
||||||
const label =
|
const label =
|
||||||
level != null
|
level != null
|
||||||
? t(`tours.planner.difficulty.t${level}`)
|
? t(`tours.planner.difficulty.t${level}`)
|
||||||
@@ -141,6 +185,20 @@ export function TourDayRowPill({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TIME-01: what an import is estimated to take as a row says it, the badge
|
||||||
|
* marked with ≈ and its words saying what it was worked out by; both null
|
||||||
|
* while it is unknown or there is none, since a row has no room for a badge
|
||||||
|
* that says nothing. The detail names an unknown one.
|
||||||
|
*/
|
||||||
|
function estimateFact(
|
||||||
|
times: TourPlannedTimes,
|
||||||
|
t: Parameters<typeof estimateLabel>[1]
|
||||||
|
): { value: string | null; label: string | null } {
|
||||||
|
const value = estimateBadgeText(times.estimate);
|
||||||
|
return value && times.estimate ? { value, label: estimateLabel(times.estimate, t) } : { value: null, label: null };
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A paddle tour's check bench as one fact (PAD-09), or null for a hike, a tour
|
* A paddle tour's check bench as one fact (PAD-09), or null for a hike, a tour
|
||||||
* listed without one, or an area without obstacle data: a row has no room for
|
* listed without one, or an area without obstacle data: a row has no room for
|
||||||
@@ -163,27 +221,30 @@ export function TourDayRowPills({ tour, compact = false }: { tour: TourListItem;
|
|||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const unit = useSettingsStore((state) => state.settings.distance_unit) || 'metric';
|
const unit = useSettingsStore((state) => state.settings.distance_unit) || 'metric';
|
||||||
const times = tourPlannedTimes(tour);
|
const times = tourPlannedTimes(tour);
|
||||||
const shownMinutes = times.plannedTotalMinutes ?? times.walkingMinutes;
|
const walking = times.walkingMinutes == null ? null : formatPlannedTourDuration(times.walkingMinutes);
|
||||||
|
const total = plannedTotalText(times, t);
|
||||||
|
const staysText = times.walk ? walkStaysText(times.walk, t) : null;
|
||||||
|
const pace = runPaceText(tour, t, unit);
|
||||||
|
const estimate = estimateFact(times, t);
|
||||||
const timeParts = [
|
const timeParts = [
|
||||||
times.walkingMinutes != null
|
walking ? `${movingTimeLabel(tour, t('tours.planner.inspector.duration'), t)}: ${walking}` : null,
|
||||||
? `${movingTimeLabel(tour, t('tours.planner.inspector.duration'), t)}: ${formatPlannedTourDuration(times.walkingMinutes)}`
|
// RUN-01: the pace the running time is planned at.
|
||||||
: null,
|
pace ? `${t('tours.run.pace')}: ${pace}` : null,
|
||||||
times.breakMinutes
|
times.breakMinutes
|
||||||
? `${t('tours.planner.breaksAdditional')}: ${formatPlannedTourDuration(times.breakMinutes)}`
|
? `${t('tours.planner.breaksAdditional')}: ${formatPlannedTourDuration(times.breakMinutes)}`
|
||||||
: null,
|
: null,
|
||||||
times.plannedTotalMinutes != null
|
// CW-02: a city walk's stays, which its total adds to the walking time.
|
||||||
? `${t('tours.planner.plannedTotalDuration')}: ${formatPlannedTourDuration(times.plannedTotalMinutes)}${times.manuallyOverridden ? ` (${t('tours.planner.plannedTotalManual')})` : ''}`
|
staysText ? `${t('tours.walk.stays')}: ${staysText}` : null,
|
||||||
|
total
|
||||||
|
? `${t('tours.planner.plannedTotalDuration')}: ${total}${times.manuallyOverridden ? ` (${t('tours.planner.plannedTotalManual')})` : ''}`
|
||||||
: null,
|
: null,
|
||||||
|
// TIME-01: an import's estimate, apart from any total the travellers entered.
|
||||||
|
estimate.label,
|
||||||
].filter((part): part is string => part !== null);
|
].filter((part): part is string => part !== null);
|
||||||
const check = paddleCheckOf(tour, t);
|
const check = paddleCheckOf(tour, t);
|
||||||
const time = shownMinutes != null && (
|
const shown = plannedTotalText(times, t, true) ?? walking ?? estimate.value;
|
||||||
<TourDayRowPill
|
const time = shown != null && (
|
||||||
key="time"
|
<TourDayRowPill key="time" icon={Clock} value={shown} label={timeParts.join(', ')} testId="trip-plan-tour-time" />
|
||||||
icon={Clock}
|
|
||||||
value={formatPlannedTourDuration(shownMinutes)}
|
|
||||||
label={timeParts.join(', ')}
|
|
||||||
testId="trip-plan-tour-time"
|
|
||||||
/>
|
|
||||||
);
|
);
|
||||||
const distance = tour.distance != null && (
|
const distance = tour.distance != null && (
|
||||||
<TourDayRowPill
|
<TourDayRowPill
|
||||||
@@ -209,24 +270,47 @@ export function TourDayRowPills({ tour, compact = false }: { tour: TourListItem;
|
|||||||
return <>{tour.tour_type === 'kayak' ? [time, bench, distance] : [time, distance, ascent]}</>;
|
return <>{tour.tour_type === 'kayak' ? [time, bench, distance] : [time, distance, ascent]}</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function TourDayRowFacts({ tour, mobile = false }: { tour: TourListItem; mobile?: boolean }) {
|
export default function TourDayRowFacts({
|
||||||
|
tour,
|
||||||
|
assignmentId,
|
||||||
|
mobile = false,
|
||||||
|
}: {
|
||||||
|
tour: TourListItem;
|
||||||
|
/** The row's day assignment, for a city walk's progress on that day (CW-03). */
|
||||||
|
assignmentId?: number;
|
||||||
|
mobile?: boolean;
|
||||||
|
}) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const unit = useSettingsStore((state) => state.settings.distance_unit) || 'metric';
|
const unit = useSettingsStore((state) => state.settings.distance_unit) || 'metric';
|
||||||
|
const progress = useWalkProgress(tour, assignmentId);
|
||||||
const times = tourPlannedTimes(tour);
|
const times = tourPlannedTimes(tour);
|
||||||
const facts: Array<{ icon: LucideIcon; value: string; label: string; testId: string }> = [];
|
const facts: Array<{ icon: LucideIcon; value: string; label: string; testId: string; said?: string }> = [];
|
||||||
const add = (icon: LucideIcon, value: string, label: string, testId: string) =>
|
const add = (icon: LucideIcon, value: string, label: string, testId: string, said?: string) =>
|
||||||
facts.push({ icon, value, label, testId });
|
facts.push({ icon, value, label, testId, said });
|
||||||
if (tour.distance != null)
|
if (tour.distance != null)
|
||||||
add(Ruler, formatDistance(tour.distance, unit), t('tours.detail.distance'), 'plan-tour-distance');
|
add(Ruler, formatDistance(tour.distance, unit), t('tours.detail.distance'), 'plan-tour-distance');
|
||||||
if (tour.elevation_gain != null)
|
if (tour.elevation_gain != null)
|
||||||
add(ArrowUp, formatElevation(tour.elevation_gain, unit), t('tours.detail.ascent'), 'plan-tour-ascent');
|
add(ArrowUp, formatElevation(tour.elevation_gain, unit), t('tours.detail.ascent'), 'plan-tour-ascent');
|
||||||
if (times.walkingMinutes != null)
|
if (times.walkingMinutes != null)
|
||||||
add(
|
add(
|
||||||
tourDayRowIcon(tour.tour_type === 'kayak' || tour.tour_type === 'bike' ? tour.tour_type : 'walk'),
|
tourDayRowIcon(movingIconType(tour.tour_type)),
|
||||||
formatPlannedTourDuration(times.walkingMinutes),
|
formatPlannedTourDuration(times.walkingMinutes),
|
||||||
movingTimeLabel(tour, t('tours.planner.inspector.duration'), t),
|
movingTimeLabel(tour, t('tours.planner.inspector.duration'), t),
|
||||||
'trip-plan-tour-walking-time'
|
'trip-plan-tour-walking-time'
|
||||||
);
|
);
|
||||||
|
// TIME-01: an import's estimate, said in full where it is opened. A total
|
||||||
|
// the travellers entered is the time shown; the estimate then only joins its words.
|
||||||
|
const estimate = estimateFact(times, t);
|
||||||
|
if (estimate.value && estimate.label && times.plannedTotalMinutes == null)
|
||||||
|
add(
|
||||||
|
tourDayRowIcon(movingIconType(tour.tour_type)),
|
||||||
|
estimate.value,
|
||||||
|
t('tours.estimate.label'),
|
||||||
|
'trip-plan-tour-estimate',
|
||||||
|
estimate.label
|
||||||
|
);
|
||||||
|
const pace = runPaceText(tour, t, unit);
|
||||||
|
if (pace) add(Gauge, pace, t('tours.run.pace'), 'plan-tour-run-pace');
|
||||||
if (times.breakMinutes != null && times.breakMinutes > 0)
|
if (times.breakMinutes != null && times.breakMinutes > 0)
|
||||||
add(
|
add(
|
||||||
Pause,
|
Pause,
|
||||||
@@ -234,20 +318,28 @@ export default function TourDayRowFacts({ tour, mobile = false }: { tour: TourLi
|
|||||||
t('tours.planner.breaksAdditional'),
|
t('tours.planner.breaksAdditional'),
|
||||||
'trip-plan-tour-breaks'
|
'trip-plan-tour-breaks'
|
||||||
);
|
);
|
||||||
if (times.plannedTotalMinutes != null)
|
const total = plannedTotalText(times, t, true);
|
||||||
add(
|
if (total) {
|
||||||
Clock,
|
const label = `${t('tours.planner.plannedTotalDuration')}${times.manuallyOverridden ? `, ${t('tours.planner.plannedTotalManual')}` : ''}`;
|
||||||
formatPlannedTourDuration(times.plannedTotalMinutes),
|
const said = estimate.label ? `${label}: ${total}. ${estimate.label}` : undefined;
|
||||||
`${t('tours.planner.plannedTotalDuration')}${times.manuallyOverridden ? `, ${t('tours.planner.plannedTotalManual')}` : ''}`,
|
add(Clock, total, label, 'trip-plan-tour-planned-duration', said);
|
||||||
'trip-plan-tour-planned-duration'
|
}
|
||||||
);
|
|
||||||
const check = paddleCheckOf(tour, t);
|
const check = paddleCheckOf(tour, t);
|
||||||
if (check) add(check.icon, check.value, t('tours.paddle.check.title'), 'plan-tour-paddle-check');
|
if (check) add(check.icon, check.value, t('tours.paddle.check.title'), 'plan-tour-paddle-check');
|
||||||
return (
|
return (
|
||||||
<span data-testid="plan-tour-facts" className="flex min-w-0 flex-wrap items-center gap-1">
|
<span data-testid="plan-tour-facts" className="flex min-w-0 flex-wrap items-center gap-1">
|
||||||
{facts.map((fact) => (
|
{facts.map(({ said, ...fact }) => (
|
||||||
<Fact key={fact.testId} {...fact} label={`${fact.label}: ${fact.value}`} mobile={mobile} />
|
<Fact key={fact.testId} {...fact} label={said ?? `${fact.label}: ${fact.value}`} mobile={mobile} />
|
||||||
))}
|
))}
|
||||||
|
{progress && (
|
||||||
|
<Fact
|
||||||
|
icon={CheckCheck}
|
||||||
|
value={`${progress.visited}/${progress.total}`}
|
||||||
|
label={t('tours.walk.progress', progress)}
|
||||||
|
testId="plan-walk-progress"
|
||||||
|
mobile={mobile}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</span>
|
</span>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
// TIME-02-011 to TIME-02-016, TIME-02-021 and TIME-02-022: how the day plan says a tour's time, its overrun and the hint below its time fields.
|
||||||
|
import type { TourListItem } from '@trek/shared';
|
||||||
|
import { beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
import { render, screen } from '../../../tests/helpers/render';
|
||||||
|
import { seedStore } from '../../../tests/helpers/store';
|
||||||
|
import { useSettingsStore } from '../../store/settingsStore';
|
||||||
|
import { TourDayTimeText, TourEndHint, TourOverrunLine } from './TourDayTimeParts';
|
||||||
|
import { workedOutEndHint } from './tourDayTimeHint';
|
||||||
|
|
||||||
|
const tour: TourListItem = {
|
||||||
|
place_id: 7,
|
||||||
|
name: 'Ridge',
|
||||||
|
tour_type: 'hike',
|
||||||
|
distance: 8,
|
||||||
|
elevation_gain: 300,
|
||||||
|
elevation_loss: 300,
|
||||||
|
duration: 150,
|
||||||
|
planned_duration_minutes: null,
|
||||||
|
break_additional_minutes: 30,
|
||||||
|
difficulty: null,
|
||||||
|
wanderer_ref: null,
|
||||||
|
match_confidence: 1,
|
||||||
|
max_hiking_difficulty: 2,
|
||||||
|
planned: true,
|
||||||
|
caution: false,
|
||||||
|
};
|
||||||
|
const imported: TourListItem = {
|
||||||
|
...tour,
|
||||||
|
distance: 12,
|
||||||
|
elevation_loss: 500,
|
||||||
|
duration: null,
|
||||||
|
break_additional_minutes: null,
|
||||||
|
};
|
||||||
|
const t = (key: string, params?: Record<string, unknown>) => `${key} ${JSON.stringify(params ?? {})}`;
|
||||||
|
const clock = (value: string) => value;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
seedStore(useSettingsStore, { settings: { time_format: '24h' } });
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('TourDayTimeText', () => {
|
||||||
|
it('TIME-02-011: a worked-out end is set apart and says how it was worked out', () => {
|
||||||
|
render(<TourDayTimeText entry={{ start: '09:00', end: null }} tour={tour} />);
|
||||||
|
const end = screen.getByTestId('tour-day-end-worked-out');
|
||||||
|
expect(end).toHaveTextContent('12:00');
|
||||||
|
expect(end).toHaveClass('text-content-faint');
|
||||||
|
expect(end).toHaveAccessibleName('Ends at 12:00, worked out from the start and the tour time of 3 h');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('TIME-02-012: an estimate is marked with ≈, a phone row uses its own tone, and past midnight says +1', () => {
|
||||||
|
const { unmount } = render(<TourDayTimeText entry={{ start: '09:00', end: null }} tour={imported} mobile />);
|
||||||
|
expect(screen.getByTestId('tour-day-end-worked-out')).toHaveTextContent('≈ 13:00');
|
||||||
|
expect(screen.getByTestId('tour-day-end-worked-out')).toHaveClass('text-m-faint');
|
||||||
|
unmount();
|
||||||
|
render(<TourDayTimeText entry={{ start: '22:30', end: null }} tour={tour} />);
|
||||||
|
expect(screen.getByTestId('tour-day-end-worked-out')).toHaveTextContent('01:30 +1');
|
||||||
|
expect(screen.getByTestId('tour-day-end-worked-out')).toHaveAccessibleName(
|
||||||
|
'Ends at 01:30 on the next day, worked out from the start and the tour time of 3 h'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('TIME-02-013: an end typed by hand shows as typed, and without an end only the start shows', () => {
|
||||||
|
const { container, unmount } = render(<TourDayTimeText entry={{ start: '09:00', end: '15:00' }} tour={tour} />);
|
||||||
|
expect(container).toHaveTextContent('09:00 → 15:00');
|
||||||
|
expect(screen.queryByTestId('tour-day-end-worked-out')).not.toBeInTheDocument();
|
||||||
|
unmount();
|
||||||
|
const unknown = { ...imported, elevation_gain: null, elevation_loss: null };
|
||||||
|
const plain = render(<TourDayTimeText entry={{ start: '09:00', end: null }} tour={unknown} />);
|
||||||
|
expect(plain.container.textContent).toBe('09:00');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('TIME-02-021: a city walk with a stay nobody entered ends then at the earliest, marked with ≥', () => {
|
||||||
|
// 2 h 15 min on foot and 1 h of stays entered, one station of four without one.
|
||||||
|
const walk: TourListItem = {
|
||||||
|
...tour,
|
||||||
|
tour_type: 'walk',
|
||||||
|
duration: 135,
|
||||||
|
max_hiking_difficulty: null,
|
||||||
|
station_count: 4,
|
||||||
|
station_stay_minutes: 60,
|
||||||
|
station_stays_unknown: 1,
|
||||||
|
};
|
||||||
|
render(<TourDayTimeText entry={{ start: '09:00', end: null }} tour={walk} />);
|
||||||
|
const end = screen.getByTestId('tour-day-end-worked-out');
|
||||||
|
expect(end).toHaveTextContent('≥ 12:15');
|
||||||
|
expect(end).toHaveAccessibleName('Ends at 12:15, worked out from the start and the tour time of ≥ 3 h 15 min');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('TIME-02-022: in a right-to-left language the arrow points from the start on the right to the end', () => {
|
||||||
|
seedStore(useSettingsStore, { settings: { time_format: '24h', language: 'ar' } });
|
||||||
|
const { container, unmount } = render(<TourDayTimeText entry={{ start: '09:00', end: '15:00' }} tour={tour} />);
|
||||||
|
expect(container.textContent).toBe('09:00 ← 15:00');
|
||||||
|
unmount();
|
||||||
|
const worked = render(<TourDayTimeText entry={{ start: '09:00', end: null }} tour={tour} />);
|
||||||
|
expect(worked.container).toHaveTextContent('09:00 ← 12:00');
|
||||||
|
expect(worked.container.textContent).not.toContain('→');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('TourOverrunLine', () => {
|
||||||
|
it('TIME-02-014: names the item the end runs into, and says nothing without one', () => {
|
||||||
|
const { container, unmount } = render(<TourOverrunLine overrun={null} />);
|
||||||
|
expect(container).toBeEmptyDOMElement();
|
||||||
|
unmount();
|
||||||
|
render(<TourOverrunLine overrun={{ name: 'Lunch', time: '12:00', end: '13:00' }} />);
|
||||||
|
expect(screen.getByTestId('tour-day-overrun')).toHaveTextContent('Ends at 13:00, after Lunch starts at 12:00');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('TIME-02-014b: an item without a name is called the next item', () => {
|
||||||
|
render(<TourOverrunLine overrun={{ name: '', time: '12:00', end: '13:00' }} />);
|
||||||
|
expect(screen.getByTestId('tour-day-overrun')).toHaveTextContent(
|
||||||
|
'Ends at 13:00, after the next item starts at 12:00'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('workedOutEndHint', () => {
|
||||||
|
it('TIME-02-015: says the worked-out end while none is typed, and that a start will set one', () => {
|
||||||
|
expect(workedOutEndHint({ start: '09:00', end: '' }, imported, t, clock)).toBe(
|
||||||
|
'tours.dayTime.formHint {"time":"13:00","total":"≈ 4 h"}'
|
||||||
|
);
|
||||||
|
expect(workedOutEndHint({ start: '', end: '' }, tour, t, clock)).toBe('tours.dayTime.formNoStart {"total":"3 h"}');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('TIME-02-016: says nothing for a typed end, a stage day, a plain place or a tour without a known time', () => {
|
||||||
|
expect(workedOutEndHint({ start: '09:00', end: '15:00' }, tour, t, clock)).toBeNull();
|
||||||
|
expect(workedOutEndHint({ start: '09:00', end: '', stageKey: 'stop-2' }, tour, t, clock)).toBeNull();
|
||||||
|
expect(workedOutEndHint({ start: '09:00', end: '' }, null, t, clock)).toBeNull();
|
||||||
|
const unknown = { ...imported, elevation_gain: null, elevation_loss: null };
|
||||||
|
expect(workedOutEndHint({ start: '09:00', end: '' }, unknown, t, clock)).toBeNull();
|
||||||
|
expect(workedOutEndHint({ start: '', end: '' }, unknown, t, clock)).toBeNull();
|
||||||
|
render(<TourEndHint start="09:00" end="" assignment={{ tour_stage_key: null }} tour={tour} />);
|
||||||
|
expect(screen.getByTestId('tour-day-end-hint')).toHaveTextContent('12:00');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
import type { TourListItem } from '@trek/shared';
|
||||||
|
import { Clock } from 'lucide-react';
|
||||||
|
import { isRtlLanguage, useTranslation } from '../../i18n';
|
||||||
|
import { useSettingsStore } from '../../store/settingsStore';
|
||||||
|
import type { Assignment } from '../../types';
|
||||||
|
import { formatTime } from '../../utils/formatters';
|
||||||
|
import { fs } from '../shared/DialogShell';
|
||||||
|
import { Tooltip } from '../shared/Tooltip';
|
||||||
|
import { tourDayTimeOf, type TourDayEntry, type TourDayTime, type TourOverrun } from './tourDayTime';
|
||||||
|
import { totalText, workedOutEndHint, type Translate } from './tourDayTimeHint';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TIME-02: how the day plan says a tour's time on a day, on the desktop and
|
||||||
|
* the phone alike; each only places it in its own badge or chip.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** The words a worked-out end is explained by: when it ends and the total it follows from. */
|
||||||
|
function workedOutLabel(time: TourDayTime, t: Translate, clock: (value: string) => string): string {
|
||||||
|
const params = { time: clock(time.end ?? ''), total: totalText(time) };
|
||||||
|
return t(time.nextDay ? 'tours.dayTime.workedOutNextDay' : 'tours.dayTime.workedOut', params);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TIME-02: a tour's time on its day as the row shows it: the start, then the
|
||||||
|
* end. An end worked out from the start and the total is fainter, marked `≈`
|
||||||
|
* for an estimate or `≥` where a stay is not known yet, `+1` past midnight,
|
||||||
|
* and says in its tooltip how it was worked out. An end typed by hand shows
|
||||||
|
* as typed.
|
||||||
|
*/
|
||||||
|
export function TourDayTimeText({
|
||||||
|
entry,
|
||||||
|
tour,
|
||||||
|
mobile = false,
|
||||||
|
}: {
|
||||||
|
/** The day entry's times; `tourDayEntryOf` reads them off an assignment. */
|
||||||
|
entry: TourDayEntry;
|
||||||
|
tour: TourListItem;
|
||||||
|
mobile?: boolean;
|
||||||
|
}) {
|
||||||
|
const { t, locale, language } = useTranslation();
|
||||||
|
const timeFormat = useSettingsStore((state) => state.settings.time_format) ?? '24h';
|
||||||
|
const time = tourDayTimeOf(entry, tour);
|
||||||
|
if (!time) return null;
|
||||||
|
const clock = (value: string) => formatTime(value, locale, timeFormat);
|
||||||
|
// The arrow is not mirrored by the bidi rules: in a right-to-left row the start sits on the right.
|
||||||
|
const arrow = isRtlLanguage(language) ? '←' : '→';
|
||||||
|
if (!time.end) return <>{clock(time.start)}</>;
|
||||||
|
if (!time.workedOut) return <>{`${clock(time.start)} ${arrow} ${clock(time.end)}`}</>;
|
||||||
|
const label = workedOutLabel(time, t, clock);
|
||||||
|
const mark = time.estimated ? '≈ ' : time.atLeast ? '≥ ' : '';
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{`${clock(time.start)} ${arrow} `}
|
||||||
|
<Tooltip label={label}>
|
||||||
|
<span
|
||||||
|
data-testid="tour-day-end-worked-out"
|
||||||
|
aria-label={label}
|
||||||
|
className={mobile ? 'text-m-faint' : 'text-content-faint'}
|
||||||
|
>
|
||||||
|
{`${mark}${clock(time.end)}${time.nextDay ? ' +1' : ''}`}
|
||||||
|
</span>
|
||||||
|
</Tooltip>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TIME-02: a tour whose end runs past the start of the next timed item of
|
||||||
|
* its day, said on one line that wraps, as a connection that arrives late is
|
||||||
|
* (CW-08). Nothing is moved or changed.
|
||||||
|
*/
|
||||||
|
export function TourOverrunLine({ overrun }: { overrun: TourOverrun | null | undefined }) {
|
||||||
|
const { t, locale } = useTranslation();
|
||||||
|
const timeFormat = useSettingsStore((state) => state.settings.time_format) ?? '24h';
|
||||||
|
if (!overrun) return null;
|
||||||
|
const clock = (value: string) => formatTime(value, locale, timeFormat);
|
||||||
|
const said = t('tours.dayTime.overrun', {
|
||||||
|
end: clock(overrun.end),
|
||||||
|
name: overrun.name || t('tours.dayTime.nextItem'),
|
||||||
|
time: clock(overrun.time),
|
||||||
|
});
|
||||||
|
// A clock, not a warning sign: the plan is not wrong, its times only meet.
|
||||||
|
return (
|
||||||
|
<p data-testid="tour-day-overrun" className="m-0 mt-1 flex items-start gap-1 text-warning" style={fs(11, 'body')}>
|
||||||
|
<Clock size={12} strokeWidth={2.2} aria-hidden="true" className="mt-[2px] flex-none" />
|
||||||
|
<span className="min-w-0 break-words">{said}</span>
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TIME-02: the hint below the time fields of a tour's day entry, on the
|
||||||
|
* desktop form and the phone sheet alike, read while the fields are typed in.
|
||||||
|
*/
|
||||||
|
export function TourEndHint({
|
||||||
|
start,
|
||||||
|
end,
|
||||||
|
assignment,
|
||||||
|
tour,
|
||||||
|
mobile = false,
|
||||||
|
}: {
|
||||||
|
start: string;
|
||||||
|
end: string;
|
||||||
|
/** The day entry the times are typed for, which says the stage of a multi-day tour it holds. */
|
||||||
|
assignment: Pick<Assignment, 'tour_stage_key'> | undefined;
|
||||||
|
tour: TourListItem | null | undefined;
|
||||||
|
mobile?: boolean;
|
||||||
|
}) {
|
||||||
|
const { t, locale } = useTranslation();
|
||||||
|
const timeFormat = useSettingsStore((state) => state.settings.time_format) ?? '24h';
|
||||||
|
const entry = { start, end, stageKey: assignment?.tour_stage_key ?? null };
|
||||||
|
const hint = workedOutEndHint(entry, tour, t, (value) => formatTime(value, locale, timeFormat));
|
||||||
|
if (!hint) return null;
|
||||||
|
return (
|
||||||
|
<p
|
||||||
|
data-testid="tour-day-end-hint"
|
||||||
|
className={`m-0 ${mobile ? 'mt-[5px] font-geist text-m-faint' : 'text-content-muted'}`}
|
||||||
|
style={fs(11, 'body')}
|
||||||
|
>
|
||||||
|
{hint}
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,13 +1,15 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/render'
|
import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/render'
|
||||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
import type { TourListItem } from '@trek/shared'
|
import type { TourListItem } from '@trek/shared'
|
||||||
import { buildPlace } from '../../../tests/helpers/factories'
|
import { buildAssignment, buildDay, buildPlace } from '../../../tests/helpers/factories'
|
||||||
import { paddleBench } from '../../../tests/helpers/paddleCheck'
|
import { paddleBench } from '../../../tests/helpers/paddleCheck'
|
||||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
|
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
|
||||||
import { useSettingsStore } from '../../store/settingsStore'
|
import { useSettingsStore } from '../../store/settingsStore'
|
||||||
|
import { useTourActivityCompareStore } from '../../store/tourActivityCompareStore'
|
||||||
import TourDetailDialog from './TourDetailDialog'
|
import TourDetailDialog from './TourDetailDialog'
|
||||||
import { useTripStore } from '../../store/tripStore'
|
import { useTripStore } from '../../store/tripStore'
|
||||||
|
import { tourRepo } from '../../repo/tourRepo'
|
||||||
|
|
||||||
vi.mock('../../../../server/src/config', () => { throw new Error('Config initialization is forbidden in client tests') })
|
vi.mock('../../../../server/src/config', () => { throw new Error('Config initialization is forbidden in client tests') })
|
||||||
vi.mock('../../../../server/src/db/database', () => { throw new Error('Legacy database imports are forbidden in client tests') })
|
vi.mock('../../../../server/src/db/database', () => { throw new Error('Legacy database imports are forbidden in client tests') })
|
||||||
@@ -60,6 +62,12 @@ beforeEach(() => {
|
|||||||
seedStore(useSettingsStore, { settings: { distance_unit: 'metric' } })
|
seedStore(useSettingsStore, { settings: { distance_unit: 'metric' } })
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// A repository answer one test stubs never reaches the tests after it.
|
||||||
|
afterEach(() => {
|
||||||
|
vi.restoreAllMocks()
|
||||||
|
useTourActivityCompareStore.setState({ comparison: null, mapAvailable: false })
|
||||||
|
})
|
||||||
|
|
||||||
describe('TourDetailDialog', () => {
|
describe('TourDetailDialog', () => {
|
||||||
it('keeps desktop detail non-modal and returns focus to its Tour row on Escape', async () => {
|
it('keeps desktop detail non-modal and returns focus to its Tour row on Escape', async () => {
|
||||||
const opener = document.createElement('button')
|
const opener = document.createElement('button')
|
||||||
@@ -142,6 +150,85 @@ describe('TourDetailDialog', () => {
|
|||||||
expect(screen.getByText('Planned (Manual override)')).toBeInTheDocument()
|
expect(screen.getByText('Planned (Manual override)')).toBeInTheDocument()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('CW-02: shows a city walk its walking time, its stays and their total, and no breaks left from another type', async () => {
|
||||||
|
const walk = {
|
||||||
|
...tour, tour_type: 'walk' as const, max_hiking_difficulty: null, duration: 45, break_additional_minutes: 15,
|
||||||
|
station_count: 3, station_stay_minutes: 120, station_stays_unknown: 0,
|
||||||
|
}
|
||||||
|
vi.spyOn(tourRepo, 'detail').mockResolvedValue({ tour: walk, waypoints: [] })
|
||||||
|
const view = render(<TourDetailDialog {...defaultProps} tour={walk} />)
|
||||||
|
|
||||||
|
// 45 min of walking, a museum of 90 min and a cafe of 30 min, as the day row says it too.
|
||||||
|
expect(screen.getByLabelText('Walking: 45 min, Stays: 2 h, Planned: 2 h 45 min')).toHaveTextContent('2 h 45 min')
|
||||||
|
expect(screen.getByText('Stays')).toBeInTheDocument()
|
||||||
|
expect(screen.queryByText('Breaks')).not.toBeInTheDocument()
|
||||||
|
|
||||||
|
view.rerender(<TourDetailDialog {...defaultProps} tour={{ ...walk, station_stay_minutes: 90, station_stays_unknown: 1 }} />)
|
||||||
|
expect(screen.getByLabelText('Walking: 45 min, Stays: at least 1 h 30 min, Planned: at least 2 h 15 min'))
|
||||||
|
.toHaveTextContent('≥ 2 h 15 min')
|
||||||
|
// On a phone's three narrow columns the longer values wrap rather than being cut.
|
||||||
|
const stays = screen.getByText('Stays').closest('dt')?.nextElementSibling
|
||||||
|
expect(stays).toHaveTextContent('at least 1 h 30 min')
|
||||||
|
expect(stays).toHaveClass('break-words')
|
||||||
|
expect(stays).not.toHaveClass('truncate')
|
||||||
|
|
||||||
|
view.rerender(<TourDetailDialog {...defaultProps}
|
||||||
|
tour={{ ...walk, station_stay_minutes: 90, station_stays_unknown: 1, planned_duration_minutes: 240 }} />)
|
||||||
|
expect(screen.getByLabelText(
|
||||||
|
'Walking: 45 min, Stays: at least 1 h 30 min, Planned (Manual override): 4 h, Computed: at least 2 h 15 min'
|
||||||
|
)).toHaveTextContent('4 h')
|
||||||
|
expect(screen.getByText('Computed')).toBeInTheDocument()
|
||||||
|
expect(await screen.findByTestId('walk-stations')).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('CW-04: a walk opened from a day it is on keeps that day for its times; opened otherwise, a day can be picked', async () => {
|
||||||
|
const walk = { ...tour, tour_type: 'walk' as const, max_hiking_difficulty: null, duration: 20, station_count: 1 }
|
||||||
|
vi.spyOn(tourRepo, 'detail').mockResolvedValue({ tour: walk, waypoints: [
|
||||||
|
{ lat: 48, lng: 11, role: 'start', sequence: 0, key: 'stop-01', name: 'Museum', stay_minutes: 30, opening_hours: 'Mo-Fr 10:00-18:00' },
|
||||||
|
] })
|
||||||
|
// 2026-10-19 is a Monday: the museum opens at 10:00.
|
||||||
|
const days = [buildDay({ id: 7, date: '2026-10-19' }), buildDay({ id: 8, date: '2026-10-20' })]
|
||||||
|
const assignments = {
|
||||||
|
'7': [buildAssignment({ id: 9, day_id: 7, place_id: 42, assignment_time: '09:00', place })],
|
||||||
|
'8': [buildAssignment({ id: 10, day_id: 8, place_id: 42, assignment_time: '11:00', place })],
|
||||||
|
}
|
||||||
|
const view = render(<TourDetailDialog {...defaultProps} tour={walk} days={days} assignments={assignments} selectedDayId={7} />)
|
||||||
|
|
||||||
|
expect(screen.getByTestId('walk-day')).toHaveTextContent(/^Day 1, Mon, Oct 19(, 2026)?, start 09:00$/)
|
||||||
|
expect(screen.queryByTestId('walk-day-picker')).not.toBeInTheDocument()
|
||||||
|
expect(await screen.findByText('Arrival about 09:00, stay until 09:30')).toBeInTheDocument()
|
||||||
|
expect(screen.getByTestId('walk-station-conflict'))
|
||||||
|
.toHaveTextContent('Museum is closed at 09:00, the stay would last until 09:30; open 10:00 to 18:00')
|
||||||
|
expect(screen.getByText('Mark visited')).toBeInTheDocument()
|
||||||
|
|
||||||
|
view.rerender(<TourDetailDialog {...defaultProps} tour={walk} days={days} assignments={assignments} />)
|
||||||
|
expect(screen.getByTestId('walk-day-picker')).toHaveTextContent(/^Day 1, Mon, Oct 19(, 2026)?, start 09:00$/)
|
||||||
|
expect(screen.queryByText('Mark visited')).not.toBeInTheDocument()
|
||||||
|
fireEvent.click(screen.getByTestId('walk-day-picker'))
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /^Day 2, .*start 11:00$/ }))
|
||||||
|
expect(await screen.findByText('Arrival about 11:00, stay until 11:30')).toBeInTheDocument()
|
||||||
|
expect(screen.queryByTestId('walk-station-conflict')).not.toBeInTheDocument()
|
||||||
|
expect(screen.getByText(/Open 10:00 to 18:00/)).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('CW-11: a walk saved with its stops only says once that its way is planned in the planner, and shows no measures yet', async () => {
|
||||||
|
const pending = {
|
||||||
|
...tour, tour_type: 'walk' as const, max_hiking_difficulty: null, distance: null, elevation_gain: null, elevation_loss: null,
|
||||||
|
station_count: 2, route_pending: true,
|
||||||
|
}
|
||||||
|
vi.spyOn(tourRepo, 'detail').mockResolvedValue({ tour: pending, waypoints: [] })
|
||||||
|
const view = render(<TourDetailDialog {...defaultProps} tour={pending} place={{ ...place, route_geometry: null }} />)
|
||||||
|
|
||||||
|
expect(screen.getByText(
|
||||||
|
'Saved with its stops only. The way between them is planned when the walk is opened in the planner and saved.'
|
||||||
|
)).toBeInTheDocument()
|
||||||
|
expect(screen.queryByText('Distance')).not.toBeInTheDocument()
|
||||||
|
expect(await screen.findByTestId('walk-stations')).toBeInTheDocument()
|
||||||
|
|
||||||
|
view.rerender(<TourDetailDialog {...defaultProps} tour={{ ...pending, route_pending: false }} />)
|
||||||
|
expect(screen.queryByText(/Saved with its stops only/)).not.toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
it('PAD-01: a paddle tour without heights shows distance, paddling and total side by side in one row', () => {
|
it('PAD-01: a paddle tour without heights shows distance, paddling and total side by side in one row', () => {
|
||||||
render(<TourDetailDialog {...defaultProps} tour={{ ...tour, tour_type: 'kayak', has_waypoints: true, duration: 50 }} />)
|
render(<TourDetailDialog {...defaultProps} tour={{ ...tour, tour_type: 'kayak', has_waypoints: true, duration: 50 }} />)
|
||||||
|
|
||||||
@@ -198,6 +285,16 @@ describe('TourDetailDialog', () => {
|
|||||||
expect(defaultProps.onUpdatePlace).toHaveBeenCalledWith(42, { name: 'New route name' })
|
expect(defaultProps.onUpdatePlace).toHaveBeenCalledWith(42, { name: 'New route name' })
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('TIME-01-FE-005: an import shows its estimated time apart from a planned one, and an import without heights says it is unknown', () => {
|
||||||
|
const imported = { ...tour, has_waypoints: false, origin: 'gpx' as const, distance: 12, elevation_gain: 300, elevation_loss: 500 }
|
||||||
|
const view = render(<TourDetailDialog {...defaultProps} tour={imported} />)
|
||||||
|
expect(screen.getByLabelText('Estimated time: ≈ 4 h')).toHaveTextContent('≈ 4 h')
|
||||||
|
expect(screen.getByText('Estimated time')).toBeInTheDocument()
|
||||||
|
view.unmount()
|
||||||
|
render(<TourDetailDialog {...defaultProps} tour={{ ...imported, elevation_gain: null, elevation_loss: null }} />)
|
||||||
|
expect(screen.getByText('Unknown')).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
it('RC-03: names a GPX import as such, without a read-only notice in the plan', () => {
|
it('RC-03: names a GPX import as such, without a read-only notice in the plan', () => {
|
||||||
render(<TourDetailDialog {...defaultProps} tour={{ ...tour, has_waypoints: false }} />)
|
render(<TourDetailDialog {...defaultProps} tour={{ ...tour, has_waypoints: false }} />)
|
||||||
|
|
||||||
@@ -219,6 +316,64 @@ describe('TourDetailDialog', () => {
|
|||||||
expect(screen.queryByText(/Based on/)).not.toBeInTheDocument()
|
expect(screen.queryByText(/Based on/)).not.toBeInTheDocument()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('SKI-02: names a snowshoe tour by its discipline in its head and on its tile, and a hike by none', () => {
|
||||||
|
const { unmount } = render(<TourDetailDialog {...defaultProps} />)
|
||||||
|
expect(screen.queryByTestId('tour-detail-ski')).not.toBeInTheDocument()
|
||||||
|
expect(screen.queryByTestId('tour-ski-mark')).not.toBeInTheDocument()
|
||||||
|
unmount()
|
||||||
|
|
||||||
|
const snowshoe = { ...tour, tour_type: 'ski' as const, max_hiking_difficulty: null, ski_discipline: 'snowshoe' as const }
|
||||||
|
render(<TourDetailDialog {...defaultProps} tour={snowshoe} />)
|
||||||
|
expect(screen.getByTestId('tour-detail-ski')).toHaveTextContent('Snowshoeing')
|
||||||
|
expect(screen.getByRole('img', { name: 'Snowshoeing' })).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('ACT-01: a recording that is the actual track of a tour names that tour in its head', () => {
|
||||||
|
seedStore(useTripStore, { places: [buildPlace({ id: 7, name: 'Lake loop' }), place] })
|
||||||
|
render(<TourDetailDialog {...defaultProps} tour={{ ...tour, has_waypoints: false, origin: 'gpx', activity_of: 7 }} />)
|
||||||
|
|
||||||
|
expect(screen.getByTestId('tour-detail-track-of')).toHaveTextContent('Actual track of Lake loop')
|
||||||
|
expect(screen.getByTestId('tour-detail-track-of').querySelector('svg.lucide-check-check')).not.toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('ACT-02: an actual track stands beside the plan the head shows, and only the map detail offers to compare it there', async () => {
|
||||||
|
const activity = {
|
||||||
|
id: 4,
|
||||||
|
assignment_id: null,
|
||||||
|
day_id: null,
|
||||||
|
assigned_at: null,
|
||||||
|
track: { place_id: 20, name: 'Watch export', origin: 'gpx' as const, file_name: 'morning.gpx', imported_at: null },
|
||||||
|
metrics: {
|
||||||
|
distance_km: 3,
|
||||||
|
elevation_gain_m: null,
|
||||||
|
elevation_loss_m: null,
|
||||||
|
started_at: null,
|
||||||
|
ended_at: null,
|
||||||
|
elapsed_minutes: null,
|
||||||
|
point_count: 2,
|
||||||
|
},
|
||||||
|
geometry: [
|
||||||
|
[48, 11],
|
||||||
|
[48, 11.03],
|
||||||
|
] as [number, number][],
|
||||||
|
}
|
||||||
|
vi.spyOn(tourRepo, 'detail').mockResolvedValue({ tour, waypoints: [], activities: [activity] })
|
||||||
|
// The planner map is on screen, so the map detail may offer the switch.
|
||||||
|
useTourActivityCompareStore.setState({ comparison: null, mapAvailable: true })
|
||||||
|
const { unmount } = render(<TourDetailDialog {...defaultProps} desktopNonModal />)
|
||||||
|
|
||||||
|
const distance = await screen.findByTestId('tour-activity-compare-distance')
|
||||||
|
// The plan as the head measures it from the line, not the list's stale 999 km.
|
||||||
|
expect(distance).toHaveTextContent('2.2 km')
|
||||||
|
expect(distance).toHaveTextContent('3 km')
|
||||||
|
expect(screen.getByRole('button', { name: /Compare on map/ })).toBeInTheDocument()
|
||||||
|
unmount()
|
||||||
|
|
||||||
|
render(<TourDetailDialog {...defaultProps} />)
|
||||||
|
await screen.findByTestId('tour-activity-compare-distance')
|
||||||
|
expect(screen.queryByRole('button', { name: /Compare on map/ })).not.toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
it('shows the grade on the tile and no second difficulty scale', () => {
|
it('shows the grade on the tile and no second difficulty scale', () => {
|
||||||
render(<TourDetailDialog {...defaultProps} tour={{ ...tour, difficulty: 'easy', max_hiking_difficulty: 1 }} />)
|
render(<TourDetailDialog {...defaultProps} tour={{ ...tour, difficulty: 'easy', max_hiking_difficulty: 1 }} />)
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
ArrowDown,
|
ArrowDown,
|
||||||
ArrowUp,
|
ArrowUp,
|
||||||
Check,
|
Check,
|
||||||
|
CheckCheck,
|
||||||
ChevronDown,
|
ChevronDown,
|
||||||
ChevronUp,
|
ChevronUp,
|
||||||
Clock,
|
Clock,
|
||||||
@@ -17,7 +18,6 @@ import {
|
|||||||
Minus,
|
Minus,
|
||||||
Navigation,
|
Navigation,
|
||||||
Pencil,
|
Pencil,
|
||||||
Plus,
|
|
||||||
Route,
|
Route,
|
||||||
Ruler,
|
Ruler,
|
||||||
Upload,
|
Upload,
|
||||||
@@ -48,22 +48,37 @@ import TrackColorPicker from '../shared/TrackColorPicker';
|
|||||||
import { markdownLinkComponents } from '../shared/markdownLink';
|
import { markdownLinkComponents } from '../shared/markdownLink';
|
||||||
import { TourDayRowAvatar } from './TourDayRowFacts';
|
import { TourDayRowAvatar } from './TourDayRowFacts';
|
||||||
import { TourGpxExportButton } from './TourGpxExportButton';
|
import { TourGpxExportButton } from './TourGpxExportButton';
|
||||||
|
import TourActivitySection from './activity/TourActivitySection';
|
||||||
|
import type { PlanValues } from './activity/planComparison';
|
||||||
|
import { TourSaveToCollectionButton } from './collection/TourSaveToCollectionButton';
|
||||||
|
import { TourPackingSection } from './packing/TourPackingSection';
|
||||||
import { PaddleCheckSection } from './paddle/PaddleCheckSection';
|
import { PaddleCheckSection } from './paddle/PaddleCheckSection';
|
||||||
import { PaddleWindSection } from './paddle/PaddleWindCard';
|
import { PaddleWindSection } from './paddle/PaddleWindCard';
|
||||||
import { TourProvenanceBlock } from './provenance/TourProvenanceSection';
|
import { TourProvenanceBlock } from './provenance/TourProvenanceSection';
|
||||||
|
import { RunHeadPills } from './run/RunHeadPills';
|
||||||
|
import { SkiHeadPill } from './ski/skiMarks';
|
||||||
|
import { TourDayAddButton } from './stages/TourDayAddButton';
|
||||||
|
import { stageKeysOfTour, type TourDayHow } from './stages/stageSpread';
|
||||||
import { tourDayRowIcon } from './tourDayRowIcon';
|
import { tourDayRowIcon } from './tourDayRowIcon';
|
||||||
import { tourDaysOf } from './tourDays';
|
import { tourDaysOf } from './tourDays';
|
||||||
import { heightsUnknown, movingTimeLabel, withoutHeights } from './tourFacts';
|
import { heightsUnknown, movingTimeLabel, withoutHeights } from './tourFacts';
|
||||||
import { TourDayPills, TourFactFields, TourMetricFields, type TourMetricField } from './tourParts';
|
import { TourDayTiles, TourFactFields, TourMetricFields, type TourMetricField } from './tourParts';
|
||||||
import {
|
import {
|
||||||
|
estimateBadgeText,
|
||||||
|
estimateField,
|
||||||
formatPlannedTourDuration,
|
formatPlannedTourDuration,
|
||||||
hikeSourceBadgeLabel,
|
hikeSourceBadgeLabel,
|
||||||
|
plannedTotalText,
|
||||||
tourPlannedTimes,
|
tourPlannedTimes,
|
||||||
tourSource,
|
tourSource,
|
||||||
tourWebsitePresentation,
|
tourWebsitePresentation,
|
||||||
|
type TourPlannedTimes,
|
||||||
} from './tourPresentation';
|
} from './tourPresentation';
|
||||||
import { useTourDayAssignment } from './useTourDayAssignment';
|
import { useTourDayAssignment } from './useTourDayAssignment';
|
||||||
import { useTourPermissions, type TourPermissionProps } from './useTourPermissions';
|
import { useTourPermissions, type TourPermissionProps } from './useTourPermissions';
|
||||||
|
import { WalkRoutePendingHint } from './walk/WalkRoutePending';
|
||||||
|
import { WalkStationsCard } from './walk/WalkStations';
|
||||||
|
import { walkTimeFields } from './walk/walkTimeFields';
|
||||||
|
|
||||||
interface TourDetailDialogProps extends TourPermissionProps {
|
interface TourDetailDialogProps extends TourPermissionProps {
|
||||||
tour: TourListItem;
|
tour: TourListItem;
|
||||||
@@ -80,7 +95,12 @@ interface TourDetailDialogProps extends TourPermissionProps {
|
|||||||
onSourceReimported?: (tour: TourListItem) => Promise<void> | void;
|
onSourceReimported?: (tour: TourListItem) => Promise<void> | void;
|
||||||
/** P2C-07: save this tour again as a new, independent one. */
|
/** P2C-07: save this tour again as a new, independent one. */
|
||||||
onSaveAsNew?: (tour: TourListItem) => Promise<void> | void;
|
onSaveAsNew?: (tour: TourListItem) => Promise<void> | void;
|
||||||
onAssignToDay?: (placeId: number, dayId?: number) => void;
|
/** ACT-01: a recorded track was assigned, taken off or imported; the lists take in these tours. */
|
||||||
|
onToursChanged?: (placeIds: number[]) => Promise<void> | void;
|
||||||
|
/** P2D-XD-01: opens the trip's packing list the tour points at. */
|
||||||
|
onOpenPacking?: () => void;
|
||||||
|
/** `how` is the answer the day menu got for a multi-day tour (MDT-02); without it the plan asks. */
|
||||||
|
onAssignToDay?: (placeId: number, dayId?: number, position?: number, how?: TourDayHow) => void;
|
||||||
onRemoveAssignment?: (dayId: number, assignmentId: number) => void;
|
onRemoveAssignment?: (dayId: number, assignmentId: number) => void;
|
||||||
onDelete?: () => void;
|
onDelete?: () => void;
|
||||||
leftWidth?: number;
|
leftWidth?: number;
|
||||||
@@ -143,7 +163,13 @@ function TourDetailMeasures({
|
|||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<TourMetricFields analysis={analysis} unit={unit} columns={5} />
|
<TourMetricFields analysis={analysis} unit={unit} columns={5} />
|
||||||
{timeFields.length > 0 && <TourFactFields fields={timeFields} columns={3} />}
|
{/* The times fill the row: two share it, three take a third each. */}
|
||||||
|
{timeFields.length > 0 && (
|
||||||
|
<TourFactFields
|
||||||
|
fields={timeFields}
|
||||||
|
columns={timeFields.length === 2 ? 2 : timeFields.length >= 3 ? 3 : undefined}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{analysis.distanceIndexedProfileSamples.length >= 2 && (
|
{analysis.distanceIndexedProfileSamples.length >= 2 && (
|
||||||
@@ -166,19 +192,28 @@ function placeStart(place: Place): { lat: number; lng: number } | null {
|
|||||||
|
|
||||||
type Translate = (key: string, params?: Record<string, unknown>) => string;
|
type Translate = (key: string, params?: Record<string, unknown>) => string;
|
||||||
|
|
||||||
/** The parts of the time a tour takes, as fields: walking, breaks, the planned total. */
|
/**
|
||||||
|
* The parts of the time a tour takes, as fields: walking, breaks, the planned
|
||||||
|
* total; a city walk its walking time, its stays and their total, in the
|
||||||
|
* planner's wording (CW-02).
|
||||||
|
*/
|
||||||
function tourTimeFields(
|
function tourTimeFields(
|
||||||
times: ReturnType<typeof tourPlannedTimes>,
|
times: TourPlannedTimes,
|
||||||
t: Translate,
|
t: Translate,
|
||||||
tour: Pick<TourListItem, 'tour_type'>
|
tour: Pick<TourListItem, 'tour_type'>
|
||||||
): TourMetricField[] {
|
): TourMetricField[] {
|
||||||
|
const walking = { label: movingTimeLabel(tour, t('tours.planner.walkingShort'), t) };
|
||||||
|
if (times.walk) {
|
||||||
|
return walkTimeFields({
|
||||||
|
walking,
|
||||||
|
walkingMinutes: times.walkingMinutes,
|
||||||
|
stays: times.walk,
|
||||||
|
manualMinutes: times.manuallyOverridden ? times.plannedTotalMinutes : null,
|
||||||
|
t,
|
||||||
|
});
|
||||||
|
}
|
||||||
return [
|
return [
|
||||||
times.walkingMinutes != null
|
times.walkingMinutes != null ? { ...walking, value: formatPlannedTourDuration(times.walkingMinutes) } : null,
|
||||||
? {
|
|
||||||
label: movingTimeLabel(tour, t('tours.planner.walkingShort'), t),
|
|
||||||
value: formatPlannedTourDuration(times.walkingMinutes),
|
|
||||||
}
|
|
||||||
: null,
|
|
||||||
times.breakMinutes
|
times.breakMinutes
|
||||||
? { label: t('tours.planner.breaksShort'), value: formatPlannedTourDuration(times.breakMinutes) }
|
? { label: t('tours.planner.breaksShort'), value: formatPlannedTourDuration(times.breakMinutes) }
|
||||||
: null,
|
: null,
|
||||||
@@ -190,30 +225,38 @@ function tourTimeFields(
|
|||||||
value: formatPlannedTourDuration(times.plannedTotalMinutes),
|
value: formatPlannedTourDuration(times.plannedTotalMinutes),
|
||||||
}
|
}
|
||||||
: null,
|
: null,
|
||||||
|
// TIME-01: what an import is estimated to take, or that it is unknown, apart from the times above.
|
||||||
|
times.estimate ? estimateField(times.estimate, t) : null,
|
||||||
].filter((field): field is TourMetricField => field !== null);
|
].filter((field): field is TourMetricField => field !== null);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The head's facts as pills: the type, where it came from, the time (its parts
|
* The head's facts as pills: the type, a run's profile and pace or a ski tour's
|
||||||
|
* discipline, where it came from, the time (its parts
|
||||||
* in the tooltip), distance, ascent, descent, and a caution.
|
* in the tooltip), distance, ascent, descent, and a caution.
|
||||||
*/
|
*/
|
||||||
function TourHeadPills({
|
function TourHeadPills({
|
||||||
tour,
|
tour,
|
||||||
trackColor,
|
trackColor,
|
||||||
timeFields,
|
timeFields,
|
||||||
shownMinutes,
|
times,
|
||||||
metrics,
|
metrics,
|
||||||
}: {
|
}: {
|
||||||
tour: TourListItem;
|
tour: TourListItem;
|
||||||
trackColor: string;
|
trackColor: string;
|
||||||
timeFields: TourMetricField[];
|
timeFields: TourMetricField[];
|
||||||
shownMinutes: number | null;
|
/** The planned total where there is one, as the day row shows it, otherwise the walking time. */
|
||||||
|
times: TourPlannedTimes;
|
||||||
/** Measured from the line as it is now, so the head says what the fields below say. */
|
/** Measured from the line as it is now, so the head says what the fields below say. */
|
||||||
metrics: { distanceKm: number | null; gain: number | null; loss: number | null };
|
metrics: { distanceKm: number | null; gain: number | null; loss: number | null };
|
||||||
}) {
|
}) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const distanceUnit = useSettingsStore((state) => state.settings.distance_unit) ?? 'metric';
|
const distanceUnit = useSettingsStore((state) => state.settings.distance_unit) ?? 'metric';
|
||||||
const timeTooltip = timeFields.map((field) => `${field.label}: ${field.value}`).join(', ');
|
const timeTooltip = timeFields.map((field) => `${field.label}: ${field.value}`).join(', ');
|
||||||
|
const shownTime =
|
||||||
|
plannedTotalText(times, t, true) ??
|
||||||
|
(times.walkingMinutes == null ? null : formatPlannedTourDuration(times.walkingMinutes)) ??
|
||||||
|
estimateBadgeText(times.estimate);
|
||||||
const source = tourSource(tour);
|
const source = tourSource(tour);
|
||||||
// The import this tour was planned from, named while it is still in the trip.
|
// The import this tour was planned from, named while it is still in the trip.
|
||||||
const derivedFromName = useTripStore((state) =>
|
const derivedFromName = useTripStore((state) =>
|
||||||
@@ -221,6 +264,10 @@ function TourHeadPills({
|
|||||||
? null
|
? null
|
||||||
: (state.places.find((p) => p.id === tour.derived_from_place_id)?.name ?? null)
|
: (state.places.find((p) => p.id === tour.derived_from_place_id)?.name ?? null)
|
||||||
);
|
);
|
||||||
|
// ACT-01: the tour this one is the recorded track of.
|
||||||
|
const documentsName = useTripStore((state) =>
|
||||||
|
tour.activity_of == null ? null : (state.places.find((p) => p.id === tour.activity_of)?.name ?? null)
|
||||||
|
);
|
||||||
return (
|
return (
|
||||||
<div className="mt-2 flex flex-wrap items-center gap-1.5">
|
<div className="mt-2 flex flex-wrap items-center gap-1.5">
|
||||||
<span className={HEAD_PILL} style={fs(10.5)}>
|
<span className={HEAD_PILL} style={fs(10.5)}>
|
||||||
@@ -232,6 +279,10 @@ function TourHeadPills({
|
|||||||
})}
|
})}
|
||||||
{t(`tourTypes.${tour.tour_type}`)}
|
{t(`tourTypes.${tour.tour_type}`)}
|
||||||
</span>
|
</span>
|
||||||
|
{/* RUN-01: a run's profile and the pace its time is planned at. */}
|
||||||
|
<RunHeadPills tour={tour} className={HEAD_PILL} />
|
||||||
|
{/* SKI-02: a ski tour's discipline, a cross-country technique inside it. */}
|
||||||
|
<SkiHeadPill tour={tour} className={HEAD_PILL} />
|
||||||
{/* A paddle tour names its boat and its water, each a badge of its own. */}
|
{/* A paddle tour names its boat and its water, each a badge of its own. */}
|
||||||
{tour.boat_type && (
|
{tour.boat_type && (
|
||||||
<span className={HEAD_PILL} style={fs(10.5)} data-testid="tour-detail-boat">
|
<span className={HEAD_PILL} style={fs(10.5)} data-testid="tour-detail-boat">
|
||||||
@@ -257,11 +308,19 @@ function TourHeadPills({
|
|||||||
</span>
|
</span>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
)}
|
)}
|
||||||
{shownMinutes != null && (
|
{documentsName && (
|
||||||
|
<Tooltip label={t('tours.activity.isTrackHint')}>
|
||||||
|
<span data-testid="tour-detail-track-of" className={`${HEAD_PILL} max-w-[220px]`} style={fs(10.5)}>
|
||||||
|
<CheckCheck size={11} strokeWidth={2} className="flex-none text-success" />
|
||||||
|
<span className="min-w-0 truncate">{t('tours.activity.ofTour', { name: documentsName })}</span>
|
||||||
|
</span>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
{shownTime != null && (
|
||||||
<Tooltip label={timeTooltip}>
|
<Tooltip label={timeTooltip}>
|
||||||
<span aria-label={timeTooltip} className={HEAD_PILL} style={fs(10.5)}>
|
<span aria-label={timeTooltip} className={HEAD_PILL} style={fs(10.5)}>
|
||||||
<Clock size={11} strokeWidth={2} className="flex-none text-content-faint" />
|
<Clock size={11} strokeWidth={2} className="flex-none text-content-faint" />
|
||||||
{formatPlannedTourDuration(shownMinutes)}
|
{shownTime}
|
||||||
</span>
|
</span>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
)}
|
)}
|
||||||
@@ -369,6 +428,79 @@ function useTourNameEditor(place: Place, onUpdatePlace?: TourDetailDialogProps['
|
|||||||
return { editingName, setEditingName, nameDraft, setNameDraft, savingName, saveName };
|
return { editingName, setEditingName, nameDraft, setNameDraft, savingName, saveName };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The tour's name in the head; `onUpdatePlace` is given only to someone who may rename it, in place. */
|
||||||
|
function TourNameHeading({
|
||||||
|
place,
|
||||||
|
onUpdatePlace,
|
||||||
|
}: {
|
||||||
|
place: Place;
|
||||||
|
onUpdatePlace?: TourDetailDialogProps['onUpdatePlace'];
|
||||||
|
}) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { editingName, setEditingName, nameDraft, setNameDraft, savingName, saveName } = useTourNameEditor(
|
||||||
|
place,
|
||||||
|
onUpdatePlace
|
||||||
|
);
|
||||||
|
if (onUpdatePlace && editingName) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
autoFocus
|
||||||
|
value={nameDraft}
|
||||||
|
onChange={(event) => setNameDraft(event.target.value)}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === 'Enter') void saveName();
|
||||||
|
if (event.key === 'Escape') {
|
||||||
|
event.preventDefault();
|
||||||
|
setNameDraft(place.name);
|
||||||
|
setEditingName(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
aria-label={t('places.formName')}
|
||||||
|
className="-ms-1.5 block min-w-0 flex-1 rounded-[8px] border-0 bg-surface-card px-1.5 py-0.5 font-bold tracking-[-0.01em] text-content shadow-sm outline-none"
|
||||||
|
style={fs(17, 'subtitle')}
|
||||||
|
/>
|
||||||
|
<Tooltip label={t('common.save')}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void saveName()}
|
||||||
|
disabled={savingName}
|
||||||
|
aria-label={t('common.save')}
|
||||||
|
className="grid h-8 w-8 flex-none place-items-center rounded-full bg-accent text-accent-text shadow-sm disabled:opacity-50"
|
||||||
|
>
|
||||||
|
<Check size={15} strokeWidth={2.4} />
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="flex min-w-0 items-center gap-1.5">
|
||||||
|
<h2
|
||||||
|
className="m-0 min-w-0 break-words font-bold leading-snug tracking-[-0.01em] text-content"
|
||||||
|
style={fs(17, 'subtitle')}
|
||||||
|
>
|
||||||
|
{place.name}
|
||||||
|
</h2>
|
||||||
|
{onUpdatePlace && (
|
||||||
|
<Tooltip label={t('common.edit')}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setNameDraft(place.name);
|
||||||
|
setEditingName(true);
|
||||||
|
}}
|
||||||
|
aria-label={t('common.edit')}
|
||||||
|
className="grid h-6 w-6 flex-none place-items-center rounded-full text-content-faint transition-colors hover:bg-surface-card hover:text-content"
|
||||||
|
>
|
||||||
|
<Pencil size={12} strokeWidth={2.2} />
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export default function TourDetailDialog({
|
export default function TourDetailDialog({
|
||||||
tour,
|
tour,
|
||||||
place,
|
place,
|
||||||
@@ -382,6 +514,8 @@ export default function TourDetailDialog({
|
|||||||
onFileUpload,
|
onFileUpload,
|
||||||
onSourceReimported,
|
onSourceReimported,
|
||||||
onSaveAsNew,
|
onSaveAsNew,
|
||||||
|
onToursChanged,
|
||||||
|
onOpenPacking,
|
||||||
onAssignToDay,
|
onAssignToDay,
|
||||||
onRemoveAssignment,
|
onRemoveAssignment,
|
||||||
onDelete,
|
onDelete,
|
||||||
@@ -399,16 +533,16 @@ export default function TourDetailDialog({
|
|||||||
canAssign: assignPermission,
|
canAssign: assignPermission,
|
||||||
});
|
});
|
||||||
const canEdit = hasEditPermission && !readOnly;
|
const canEdit = hasEditPermission && !readOnly;
|
||||||
const dayAssignment = useTourDayAssignment({ canAssign, onAssignToDay: (id, dayId) => onAssignToDay?.(id, dayId) });
|
const dayAssignment = useTourDayAssignment({
|
||||||
|
canAssign,
|
||||||
|
onAssignToDay: (id, dayId, position, how) =>
|
||||||
|
how ? onAssignToDay?.(id, dayId, position, how) : onAssignToDay?.(id, dayId),
|
||||||
|
});
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const distanceUnit = useSettingsStore((state) => state.settings.distance_unit) ?? 'metric';
|
const distanceUnit = useSettingsStore((state) => state.settings.distance_unit) ?? 'metric';
|
||||||
const [colorOpen, setColorOpen] = useState(false);
|
const [colorOpen, setColorOpen] = useState(false);
|
||||||
const [navigationOpen, setNavigationOpen] = useState(false);
|
const [navigationOpen, setNavigationOpen] = useState(false);
|
||||||
const navigationAnchorRef = useRef<HTMLSpanElement>(null);
|
const navigationAnchorRef = useRef<HTMLSpanElement>(null);
|
||||||
const { editingName, setEditingName, nameDraft, setNameDraft, savingName, saveName } = useTourNameEditor(
|
|
||||||
place,
|
|
||||||
canEdit ? onUpdatePlace : undefined
|
|
||||||
);
|
|
||||||
useDesktopEscape(desktopNonModal, onClose, desktopFocusReturnTarget);
|
useDesktopEscape(desktopNonModal, onClose, desktopFocusReturnTarget);
|
||||||
|
|
||||||
const heightsHidden = heightsUnknown(tour);
|
const heightsHidden = heightsUnknown(tour);
|
||||||
@@ -429,6 +563,21 @@ export default function TourDetailDialog({
|
|||||||
const times = tourPlannedTimes(tour);
|
const times = tourPlannedTimes(tour);
|
||||||
|
|
||||||
const timeFields = tourTimeFields(times, t, tour);
|
const timeFields = tourTimeFields(times, t, tour);
|
||||||
|
// The plan as the line measures it now: the head says it, and an actual track is compared with it (ACT-02).
|
||||||
|
const planDistanceKm = analysis?.distanceKm ?? tour.distance;
|
||||||
|
const planGain = analysis ? analysis.gain : tour.elevation_gain;
|
||||||
|
const planLoss = analysis ? analysis.loss : tour.elevation_loss;
|
||||||
|
const plan = useMemo<PlanValues>(
|
||||||
|
() => ({
|
||||||
|
distanceKm: planDistanceKm,
|
||||||
|
gain: planGain,
|
||||||
|
loss: planLoss,
|
||||||
|
minutes: times.plannedTotalMinutes,
|
||||||
|
minutesAtLeast: times.atLeast,
|
||||||
|
line: analysis?.routeCoordinates ?? null,
|
||||||
|
}),
|
||||||
|
[analysis, planDistanceKm, planGain, planLoss, times.atLeast, times.plannedTotalMinutes]
|
||||||
|
);
|
||||||
|
|
||||||
const header = (
|
const header = (
|
||||||
<>
|
<>
|
||||||
@@ -453,71 +602,13 @@ export default function TourDetailDialog({
|
|||||||
</Tooltip>
|
</Tooltip>
|
||||||
</div>
|
</div>
|
||||||
<div className="min-w-0 flex-1 pt-0.5">
|
<div className="min-w-0 flex-1 pt-0.5">
|
||||||
{canEdit && editingName ? (
|
<TourNameHeading place={place} onUpdatePlace={canEdit ? onUpdatePlace : undefined} />
|
||||||
<div className="flex items-center gap-1.5">
|
|
||||||
<input
|
|
||||||
autoFocus
|
|
||||||
value={nameDraft}
|
|
||||||
onChange={(event) => setNameDraft(event.target.value)}
|
|
||||||
onKeyDown={(event) => {
|
|
||||||
if (event.key === 'Enter') void saveName();
|
|
||||||
if (event.key === 'Escape') {
|
|
||||||
event.preventDefault();
|
|
||||||
setNameDraft(place.name);
|
|
||||||
setEditingName(false);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
aria-label={t('places.formName')}
|
|
||||||
className="-mx-1.5 block min-w-0 flex-1 rounded-[8px] border-0 bg-surface-card px-1.5 py-0.5 font-bold tracking-[-0.01em] text-content shadow-sm outline-none"
|
|
||||||
style={fs(17, 'subtitle')}
|
|
||||||
/>
|
|
||||||
<Tooltip label={t('common.save')}>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => void saveName()}
|
|
||||||
disabled={savingName}
|
|
||||||
aria-label={t('common.save')}
|
|
||||||
className="grid h-7 w-7 flex-none place-items-center rounded-full bg-accent text-accent-text disabled:opacity-50"
|
|
||||||
>
|
|
||||||
<Check size={14} strokeWidth={2.4} />
|
|
||||||
</button>
|
|
||||||
</Tooltip>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="flex min-w-0 items-center gap-1.5">
|
|
||||||
<h2
|
|
||||||
className="m-0 min-w-0 break-words font-bold leading-snug tracking-[-0.01em] text-content"
|
|
||||||
style={fs(17, 'subtitle')}
|
|
||||||
>
|
|
||||||
{place.name}
|
|
||||||
</h2>
|
|
||||||
{canEdit && onUpdatePlace && (
|
|
||||||
<Tooltip label={t('common.edit')}>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => {
|
|
||||||
setNameDraft(place.name);
|
|
||||||
setEditingName(true);
|
|
||||||
}}
|
|
||||||
aria-label={t('common.edit')}
|
|
||||||
className="grid h-6 w-6 flex-none place-items-center rounded-full text-content-faint transition-colors hover:bg-surface-card hover:text-content"
|
|
||||||
>
|
|
||||||
<Pencil size={12} strokeWidth={2.2} />
|
|
||||||
</button>
|
|
||||||
</Tooltip>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<TourHeadPills
|
<TourHeadPills
|
||||||
tour={tour}
|
tour={tour}
|
||||||
trackColor={trackColor}
|
trackColor={trackColor}
|
||||||
timeFields={timeFields}
|
timeFields={timeFields}
|
||||||
shownMinutes={times.plannedTotalMinutes ?? times.walkingMinutes}
|
times={times}
|
||||||
metrics={{
|
metrics={{ distanceKm: plan.distanceKm, gain: plan.gain, loss: plan.loss }}
|
||||||
distanceKm: analysis?.distanceKm ?? tour.distance,
|
|
||||||
gain: analysis ? analysis.gain : tour.elevation_gain,
|
|
||||||
loss: analysis ? analysis.loss : tour.elevation_loss,
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
@@ -540,14 +631,13 @@ export default function TourDetailDialog({
|
|||||||
</DialogButton>
|
</DialogButton>
|
||||||
)
|
)
|
||||||
: onAssignToDay && (
|
: onAssignToDay && (
|
||||||
<DialogButton
|
<TourDayAddButton
|
||||||
variant="primary"
|
placeId={place.id}
|
||||||
onClick={() => void dayAssignment.assign(place.id, selectedDayId)}
|
dayId={selectedDayId}
|
||||||
disabled={!dayAssignment.isAvailable(place.id, selectedDayId)}
|
days={days}
|
||||||
icon={<Plus size={14} strokeWidth={2} />}
|
stageCount={stageKeysOfTour(tour).length}
|
||||||
>
|
assignment={dayAssignment}
|
||||||
{t('inspector.addToDay')}
|
/>
|
||||||
</DialogButton>
|
|
||||||
))}
|
))}
|
||||||
{navigationTargets.length > 0 && (
|
{navigationTargets.length > 0 && (
|
||||||
<>
|
<>
|
||||||
@@ -591,7 +681,12 @@ export default function TourDetailDialog({
|
|||||||
)}
|
)}
|
||||||
{/* A tour written here offline has no server copy to export until it syncs. */}
|
{/* A tour written here offline has no server copy to export until it syncs. */}
|
||||||
{analysis && place.id > 0 && (
|
{analysis && place.id > 0 && (
|
||||||
<TourGpxExportButton target={{ tripId: place.trip_id, placeId: place.id, name: place.name }} />
|
<TourGpxExportButton
|
||||||
|
target={{ tripId: place.trip_id, placeId: place.id, name: place.name, revision: tour.revision }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{place.id > 0 && (
|
||||||
|
<TourSaveToCollectionButton target={{ tripId: place.trip_id, placeId: place.id, name: place.name }} />
|
||||||
)}
|
)}
|
||||||
{canEdit && onSaveAsNew && <SaveAsNewButton onSave={() => onSaveAsNew(tour)} />}
|
{canEdit && onSaveAsNew && <SaveAsNewButton onSave={() => onSaveAsNew(tour)} />}
|
||||||
<FooterSpacer />
|
<FooterSpacer />
|
||||||
@@ -633,9 +728,7 @@ export default function TourDetailDialog({
|
|||||||
|
|
||||||
<DialogSection className="flex-none" label={t('tours.days.label')}>
|
<DialogSection className="flex-none" label={t('tours.days.label')}>
|
||||||
{tourDays.length > 0 ? (
|
{tourDays.length > 0 ? (
|
||||||
<div data-testid="tour-days" className="flex flex-wrap gap-1">
|
<TourDayTiles tourDays={tourDays} />
|
||||||
<TourDayPills tourDays={tourDays} shown={tourDays.length} />
|
|
||||||
</div>
|
|
||||||
) : (
|
) : (
|
||||||
<p className="m-0 text-content-faint" style={fs(12, 'body')}>
|
<p className="m-0 text-content-faint" style={fs(12, 'body')}>
|
||||||
{t('tours.days.none')}
|
{t('tours.days.none')}
|
||||||
@@ -643,6 +736,7 @@ export default function TourDetailDialog({
|
|||||||
)}
|
)}
|
||||||
</DialogSection>
|
</DialogSection>
|
||||||
|
|
||||||
|
{tour.route_pending && <WalkRoutePendingHint />}
|
||||||
{analysis && (
|
{analysis && (
|
||||||
<TourDetailMeasures
|
<TourDetailMeasures
|
||||||
analysis={analysis}
|
analysis={analysis}
|
||||||
@@ -652,8 +746,40 @@ export default function TourDetailDialog({
|
|||||||
placeId={place.id}
|
placeId={place.id}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
{tour.tour_type === 'walk' && (
|
||||||
|
<WalkStationsCard
|
||||||
|
tour={tour}
|
||||||
|
tripId={place.trip_id}
|
||||||
|
assignment={assignment}
|
||||||
|
canMark={canAssign}
|
||||||
|
days={days}
|
||||||
|
assignments={assignments}
|
||||||
|
route={analysis?.routeCoordinates ?? null}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
{tour.tour_type === 'kayak' && <PaddleCheckSection tour={tour} />}
|
{tour.tour_type === 'kayak' && <PaddleCheckSection tour={tour} />}
|
||||||
{tour.tour_type === 'kayak' && <PaddleWindSection placeId={place.id} start={placeStart(place)} />}
|
{tour.tour_type === 'kayak' && <PaddleWindSection placeId={place.id} start={placeStart(place)} />}
|
||||||
|
{/* A tour written here offline has no server copy to assign a recording to until it syncs. */}
|
||||||
|
{place.id > 0 && (
|
||||||
|
<TourActivitySection
|
||||||
|
tripId={place.trip_id}
|
||||||
|
tour={tour}
|
||||||
|
days={days}
|
||||||
|
assignments={assignments}
|
||||||
|
canEdit={canEdit}
|
||||||
|
plan={plan}
|
||||||
|
planColor={trackColor}
|
||||||
|
mapCompare={desktopNonModal}
|
||||||
|
onToursChanged={onToursChanged}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<TourPackingSection
|
||||||
|
tripId={place.trip_id}
|
||||||
|
tour={tour}
|
||||||
|
tourName={place.name}
|
||||||
|
canEdit={canEdit}
|
||||||
|
onOpenPacking={onOpenPacking}
|
||||||
|
/>
|
||||||
|
|
||||||
{description && (
|
{description && (
|
||||||
<DialogSection className="flex-none" label={t('places.formDescription')}>
|
<DialogSection className="flex-none" label={t('places.formDescription')}>
|
||||||
@@ -699,7 +825,7 @@ function SaveAsNewButton({ onSave }: { onSave: () => Promise<void> | void }) {
|
|||||||
icon={saving ? <Loader2 size={14} className="animate-spin" /> : <CopyPlus size={14} strokeWidth={2} />}
|
icon={saving ? <Loader2 size={14} className="animate-spin" /> : <CopyPlus size={14} strokeWidth={2} />}
|
||||||
aria-label={t('tours.copy.action')}
|
aria-label={t('tours.copy.action')}
|
||||||
>
|
>
|
||||||
<span className="max-sm:hidden">{t('tours.copy.action')}</span>
|
<span className="max-sm:hidden">{t('common.copy')}</span>
|
||||||
</DialogButton>
|
</DialogButton>
|
||||||
</span>
|
</span>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ describe('TourGpxDropZone', () => {
|
|||||||
const zone = screen.getByText('workspace').parentElement as HTMLElement;
|
const zone = screen.getByText('workspace').parentElement as HTMLElement;
|
||||||
|
|
||||||
fireEvent.dragEnter(zone, filesDrag);
|
fireEvent.dragEnter(zone, filesDrag);
|
||||||
expect(screen.getByTestId('tour-gpx-drop')).toHaveTextContent('Drop GPX files to import them');
|
expect(screen.getByTestId('tour-gpx-drop')).toHaveTextContent('Drop GPX, KML or KMZ files to import them');
|
||||||
|
|
||||||
fireEvent.drop(zone, filesDrag);
|
fireEvent.drop(zone, filesDrag);
|
||||||
expect(importer.importFiles).toHaveBeenCalledWith([file]);
|
expect(importer.importFiles).toHaveBeenCalledWith([file]);
|
||||||
@@ -89,7 +89,7 @@ describe('TourGpxDropZone', () => {
|
|||||||
<p>workspace</p>
|
<p>workspace</p>
|
||||||
</TourGpxDropZone>
|
</TourGpxDropZone>
|
||||||
);
|
);
|
||||||
expect(screen.getByTestId('tour-gpx-drop')).toHaveTextContent('Importing GPX…');
|
expect(screen.getByTestId('tour-gpx-drop')).toHaveTextContent('Importing…');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user