mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-23 13:23:04 +00:00
feat(tours): show a city walk's progress on the phone's day row, and check its stops off offline (CW-03)
The day row on the phone now shows how many stops of a city walk were visited on that day, "2 of 5 visited", like the desktop row does. Both rows read it from one place, and a tap on the phone names it in full without opening the row. A walk's stops can be checked off, skipped and taken back without a connection. The mark shows at once, waits in the offline queue and goes out when the connection is back, in the order the marks were made and behind any older mark of the same day that still waits. The day plan, the walk's detail and a reload read the visits kept on this device with the waiting marks on top, so a mark made offline stays on screen until the server has it. A mark the server answers with "not found", because the stop, the day or the walk was removed meanwhile, counts as done and holds back no later mark of that day. Any other refusal, the Tours addon turned off among them, keeps the mark as a failed change to try again from the offline settings. The visits are read again when the connection comes and goes, and once more after the waiting marks went out, so a mark the server dropped or refused leaves the day plan. A trip's visits that answer after another trip was opened no longer show there. The offline sync keeps each trip's walk visits and reads the stops of a walk this device has never opened, so it can be checked off offline too. A walk whose stops this device could not read lists no stand-in stops and no count, and says to open it again while online. A walk put on a day while offline says its stops can be checked off once it has synced, instead of offering buttons that cannot work yet. A mark that fails says to open the walk again and try once more, in every language. Marks carry no version, so the last one to reach the server wins, as with the other changes sent after being offline. The offline guide says so.
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
import type { TourListItem } from '@trek/shared';
|
||||
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 { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import { useTourVisitStore } from '../../store/tourVisitStore';
|
||||
import TourDayRowFacts, { TourDayRowIcon, TourDayRowPills } from './TourDayRowFacts';
|
||||
import { tourDayRowIcon } from './tourDayRowIcon';
|
||||
|
||||
@@ -153,6 +154,42 @@ describe("CW-02 a city walk's time on its day row", () => {
|
||||
});
|
||||
});
|
||||
|
||||
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', () => {
|
||||
const testIds = () =>
|
||||
[...document.querySelectorAll('[data-testid^="plan-tour"], [data-testid="trip-plan-tour-time"]')].map((el) =>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { TourListItem } from '@trek/shared';
|
||||
import { ArrowUp, Clock, Pause, Ruler, type LucideIcon } from 'lucide-react';
|
||||
import { ArrowUp, CheckCheck, Clock, Pause, Ruler, type LucideIcon } from 'lucide-react';
|
||||
import { createElement, useId, useState } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
@@ -11,6 +11,7 @@ import { paddleCheckFact } from './paddle/paddleCheckModel';
|
||||
import { tourDayRowIcon } from './tourDayRowIcon';
|
||||
import { movingTimeLabel } from './tourFacts';
|
||||
import { formatPlannedTourDuration, plannedTotalText, tourPlannedTimes } from './tourPresentation';
|
||||
import { useWalkProgress } from './walk/walkProgress';
|
||||
import { walkStaysText } from './walk/walkTimeFields';
|
||||
|
||||
export function TourDayRowIcon({ type, size = 27 }: { type: string; size?: number }) {
|
||||
@@ -206,9 +207,19 @@ export function TourDayRowPills({ tour, compact = false }: { tour: TourListItem;
|
||||
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 unit = useSettingsStore((state) => state.settings.distance_unit) || 'metric';
|
||||
const progress = useWalkProgress(tour, assignmentId);
|
||||
const times = tourPlannedTimes(tour);
|
||||
const facts: Array<{ icon: LucideIcon; value: string; label: string; testId: string }> = [];
|
||||
const add = (icon: LucideIcon, value: string, label: string, testId: string) =>
|
||||
@@ -246,6 +257,15 @@ export default function TourDayRowFacts({ tour, mobile = false }: { tour: TourLi
|
||||
{facts.map((fact) => (
|
||||
<Fact key={fact.testId} {...fact} label={`${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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
// CW-03, CW-04: a city walk's stops in its detail, checked off for the day it
|
||||
// was opened from, and its progress as a pill of the desktop day row.
|
||||
import type { TourDetailResponse, TourListItem, TourWaypoint } from '@trek/shared';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen, within } from '../../../../tests/helpers/render';
|
||||
import { tourRepo } from '../../../repo/tourRepo';
|
||||
import { tourVisitRepo } from '../../../repo/tourVisitRepo';
|
||||
import { useTourVisitStore } from '../../../store/tourVisitStore';
|
||||
import { ToastContainer } from '../../shared/Toast';
|
||||
import { WalkProgressPill, WalkStationsCard, type WalkDay } from './WalkStations';
|
||||
|
||||
const walk: TourListItem = {
|
||||
place_id: 42,
|
||||
name: 'Old town',
|
||||
tour_type: 'walk',
|
||||
distance: 0.3,
|
||||
elevation_gain: null,
|
||||
elevation_loss: null,
|
||||
duration: 20,
|
||||
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: 3,
|
||||
};
|
||||
|
||||
const waypoints: TourWaypoint[] = [
|
||||
{
|
||||
lat: 48,
|
||||
lng: 11,
|
||||
role: 'start',
|
||||
sequence: 0,
|
||||
key: 'stop-01',
|
||||
name: 'Museum',
|
||||
stay_minutes: 30,
|
||||
opening_hours: 'Mo-Fr 09:00-09:20',
|
||||
},
|
||||
{ lat: 48.0005, lng: 11, role: 'via', sequence: 1, key: 'shape-01', shaping: true },
|
||||
{ lat: 48.001, lng: 11, role: 'via', sequence: 2, key: 'stop-02', opening_hours: 'sunrise-sunset' },
|
||||
{ lat: 48.002, lng: 11, role: 'end', sequence: 3, name: 'Cafe', stay_minutes: 15, opening_hours: 'Mo 10:00-18:00' },
|
||||
];
|
||||
|
||||
const day: WalkDay = {
|
||||
date: '2026-10-19',
|
||||
start: '09:00',
|
||||
route: [
|
||||
[48, 11],
|
||||
[48.001, 11],
|
||||
[48.002, 11],
|
||||
],
|
||||
walkingMinutes: 20,
|
||||
};
|
||||
|
||||
function detail(points: TourWaypoint[] = waypoints): Promise<TourDetailResponse> {
|
||||
return Promise.resolve({ tour: walk, waypoints: points });
|
||||
}
|
||||
|
||||
function card(props: Partial<Parameters<typeof WalkStationsCard>[0]> = {}) {
|
||||
return render(
|
||||
<>
|
||||
<ToastContainer />
|
||||
<WalkStationsCard tour={walk} tripId={4} assignmentId={9} canMark {...props} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const UNREAD = 'The stops of this walk could not be loaded. Open it again while online to see them and check them off.';
|
||||
|
||||
const rowOf = async (name: string) =>
|
||||
(await screen.findAllByTestId('walk-station')).find((row) => row.textContent?.includes(name)) as HTMLElement;
|
||||
|
||||
beforeEach(() => {
|
||||
useTourVisitStore.setState({ tripId: '4', byAssignment: {} });
|
||||
vi.spyOn(tourRepo, 'detail').mockImplementation(() => detail());
|
||||
});
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
describe('WalkStationsCard', () => {
|
||||
it('shows nothing for a tour that is no city walk', () => {
|
||||
render(<WalkStationsCard tour={{ ...walk, tour_type: 'hike' }} tripId={4} assignmentId={9} canMark />);
|
||||
expect(screen.queryByTestId('walk-stations')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('says it is loading until the stops are read', () => {
|
||||
vi.mocked(tourRepo.detail).mockReturnValue(new Promise(() => undefined));
|
||||
card();
|
||||
expect(screen.getByText('Loading...')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('lists the stops in their order without the shaping points, an unnamed one by its number', async () => {
|
||||
card();
|
||||
const rows = await screen.findAllByTestId('walk-station');
|
||||
expect(rows.map((row) => row.querySelector('.font-semibold')?.textContent)).toEqual(['Museum', 'Stop 2', 'Cafe']);
|
||||
expect(tourRepo.detail).toHaveBeenCalledWith(4, 42, expect.any(AbortSignal));
|
||||
});
|
||||
|
||||
it('opened without a day, offers nothing to check off and says where to', async () => {
|
||||
card({ assignmentId: null });
|
||||
await screen.findAllByTestId('walk-station');
|
||||
expect(
|
||||
screen.getByText('Open the walk from a day of the plan to check its stops off for that day.')
|
||||
).toBeInTheDocument();
|
||||
expect(screen.queryByText('Mark visited')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('checks a stop off for its day and skips another, through the store', async () => {
|
||||
const update = vi
|
||||
.spyOn(tourVisitRepo, 'update')
|
||||
.mockResolvedValueOnce({ visits: [{ assignment_id: 9, station_key: 'stop-01', status: 'visited' }] })
|
||||
.mockResolvedValueOnce({
|
||||
visits: [
|
||||
{ assignment_id: 9, station_key: 'stop-01', status: 'visited' },
|
||||
{ assignment_id: 9, station_key: 'stop-02', status: 'skipped' },
|
||||
],
|
||||
});
|
||||
card();
|
||||
|
||||
fireEvent.click(within(await rowOf('Museum')).getByText('Mark visited'));
|
||||
expect(update).toHaveBeenLastCalledWith(4, 9, 'stop-01', { status: 'visited' });
|
||||
expect(await within(await rowOf('Museum')).findByText('Visited on this day')).toBeInTheDocument();
|
||||
fireEvent.click(within(await rowOf('Stop 2')).getByText('Skip'));
|
||||
expect(update).toHaveBeenLastCalledWith(4, 9, 'stop-02', { status: 'skipped' });
|
||||
expect(await within(await rowOf('Stop 2')).findByText('Skipped on this day')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('a stop visited on that day says so and can be taken back', async () => {
|
||||
useTourVisitStore.setState({ byAssignment: { 9: { 'stop-01': 'visited' } } });
|
||||
const update = vi.spyOn(tourVisitRepo, 'update').mockResolvedValue({ visits: [] });
|
||||
card();
|
||||
|
||||
const museum = await rowOf('Museum');
|
||||
expect(within(museum).getByText('Visited on this day')).toBeInTheDocument();
|
||||
fireEvent.click(within(museum).getByText('Take back'));
|
||||
|
||||
expect(update).toHaveBeenCalledWith(4, 9, 'stop-01', { status: 'planned' });
|
||||
});
|
||||
|
||||
it('a stop without a key has nothing to check off, and without the right to plan the day no stop has', async () => {
|
||||
const { unmount } = card();
|
||||
expect(within(await rowOf('Cafe')).queryByRole('button')).not.toBeInTheDocument();
|
||||
expect(within(await rowOf('Museum')).getByText('Mark visited')).toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
card({ canMark: false });
|
||||
await screen.findAllByTestId('walk-station');
|
||||
expect(screen.queryByText('Mark visited')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Skip')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('on a day put on the plan offline, says the stops wait for the sync and offers no buttons', async () => {
|
||||
card({ assignmentId: -1700000000000 });
|
||||
await screen.findAllByTestId('walk-station');
|
||||
expect(
|
||||
screen.getByText('This walk was put on the day while offline. Its stops can be checked off once it has synced.')
|
||||
).toBeInTheDocument();
|
||||
expect(screen.queryByText('Mark visited')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Open the walk from a day of the plan to check its stops off for that day.')).toBeNull();
|
||||
});
|
||||
|
||||
it('a mark the server refuses is taken back and said in a toast', async () => {
|
||||
vi.spyOn(tourVisitRepo, 'update').mockRejectedValue(new Error('No permission'));
|
||||
card();
|
||||
|
||||
fireEvent.click(within(await rowOf('Museum')).getByText('Mark visited'));
|
||||
|
||||
expect(
|
||||
await screen.findByText('The stop could not be marked. Open the walk again and try once more.')
|
||||
).toBeInTheDocument();
|
||||
expect(within(await rowOf('Museum')).getByText('Mark visited')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('heads the stops with how many were visited on that day', async () => {
|
||||
useTourVisitStore.setState({ byAssignment: { 9: { 'stop-01': 'visited', 'stop-02': 'skipped' } } });
|
||||
card();
|
||||
expect(await screen.findByText('1 of 3 visited')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('on a day with a start, shows each arrival and what the opening hours say about it', async () => {
|
||||
card({ day });
|
||||
expect(within(await rowOf('Museum')).getByText('Arrival about 09:00')).toBeInTheDocument();
|
||||
expect(within(await rowOf('Museum')).getByTestId('walk-station-conflict')).toHaveTextContent(
|
||||
'Arrival 09:00, stay until 09:30, but it closes at 09:20'
|
||||
);
|
||||
expect(within(await rowOf('Stop 2')).getByText('Arrival about 09:40')).toBeInTheDocument();
|
||||
expect(within(await rowOf('Stop 2')).getByText('Opening hours not read here: sunrise-sunset')).toBeInTheDocument();
|
||||
expect(within(await rowOf('Cafe')).getByText('Arrival 09:50 at the earliest')).toBeInTheDocument();
|
||||
expect(within(await rowOf('Cafe')).getByTestId('walk-station-conflict')).toHaveTextContent(
|
||||
'Closed at 09:50 by its opening hours'
|
||||
);
|
||||
expect(screen.getByText(/Opening hours as OpenStreetMap has them/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('on a day without a start, asks for one and leaves the hours unsaid', async () => {
|
||||
card({ day: { ...day, start: null } });
|
||||
expect(
|
||||
await screen.findByText('Give the walk a time on this day to see arrivals and opening hours.')
|
||||
).toBeInTheDocument();
|
||||
expect(screen.queryByText(/Arrival/)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(/Opening hours as OpenStreetMap has them/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('names no source of hours when no stop has any', async () => {
|
||||
vi.mocked(tourRepo.detail).mockImplementation(() =>
|
||||
detail(waypoints.map(({ opening_hours: _hours, ...point }) => point))
|
||||
);
|
||||
card({ day });
|
||||
expect(within(await rowOf('Museum')).getByText('Arrival about 09:00')).toBeInTheDocument();
|
||||
expect(screen.queryByText(/Opening hours as OpenStreetMap has them/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('a walk whose stops cannot be read lists none, counts none and says so', async () => {
|
||||
vi.mocked(tourRepo.detail).mockRejectedValue(new Error('Tour not available offline'));
|
||||
card();
|
||||
expect(await screen.findByText(UNREAD)).toBeInTheDocument();
|
||||
expect(screen.queryAllByTestId('walk-station')).toEqual([]);
|
||||
expect(screen.queryByText(/visited/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("offline, the route's two ends read in place of the stops are no stops: no count, and it says so", async () => {
|
||||
useTourVisitStore.setState({ byAssignment: { 9: { 'stop-01': 'visited', 'stop-02': 'visited' } } });
|
||||
const ends: TourWaypoint[] = [
|
||||
{ lat: 48, lng: 11, role: 'start', sequence: 0 },
|
||||
{ lat: 48.002, lng: 11, role: 'end', sequence: 1 },
|
||||
];
|
||||
vi.mocked(tourRepo.detail).mockImplementation(() => detail(ends));
|
||||
card({ day });
|
||||
|
||||
expect(await screen.findByText(UNREAD)).toBeInTheDocument();
|
||||
expect(screen.queryAllByTestId('walk-station')).toEqual([]);
|
||||
expect(screen.queryByText(/visited/)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(/Arrival/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('a walk saved offline lists its stops before the sync gave them keys', async () => {
|
||||
const unsaved = waypoints.map(({ key: _key, ...point }) => point);
|
||||
vi.mocked(tourRepo.detail).mockImplementation(() => detail(unsaved));
|
||||
card({ tour: { ...walk, place_id: -1700000000001 }, assignmentId: -1700000000000 });
|
||||
|
||||
expect(await screen.findAllByTestId('walk-station')).toHaveLength(3);
|
||||
expect(screen.getByText('0 of 3 visited')).toBeInTheDocument();
|
||||
expect(screen.queryByText(UNREAD)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('a walk without stops lists none and misses nothing', async () => {
|
||||
vi.mocked(tourRepo.detail).mockImplementation(() => detail([]));
|
||||
card({ tour: { ...walk, station_count: 0 } });
|
||||
await vi.waitFor(() => expect(screen.queryByText('Loading...')).not.toBeInTheDocument());
|
||||
|
||||
expect(screen.queryAllByTestId('walk-station')).toEqual([]);
|
||||
expect(screen.queryByText(UNREAD)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(/visited/)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('WalkProgressPill', () => {
|
||||
it('says nothing for a hike, a walk without stops, or a day without marks', () => {
|
||||
useTourVisitStore.setState({ byAssignment: { 9: { 'stop-01': 'visited' } } });
|
||||
render(
|
||||
<>
|
||||
<WalkProgressPill tour={{ ...walk, tour_type: 'hike' }} assignmentId={9} />
|
||||
<WalkProgressPill tour={{ ...walk, station_count: 0 }} assignmentId={9} />
|
||||
<WalkProgressPill tour={walk} assignmentId={10} />
|
||||
<WalkProgressPill tour={walk} assignmentId={undefined} />
|
||||
</>
|
||||
);
|
||||
expect(screen.queryByTestId('plan-walk-progress')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the visited stops of all of them, named in full', () => {
|
||||
useTourVisitStore.setState({
|
||||
byAssignment: { 9: { a1b2c3: 'visited', d4e5f6: 'visited', g7h8i9: 'skipped' }, 10: { a1b2c3: 'skipped' } },
|
||||
});
|
||||
render(
|
||||
<>
|
||||
<WalkProgressPill tour={{ ...walk, station_count: 5 }} assignmentId={9} />
|
||||
<WalkProgressPill tour={{ ...walk, station_count: 5 }} assignmentId={10} />
|
||||
</>
|
||||
);
|
||||
const [day9, day10] = screen.getAllByTestId('plan-walk-progress');
|
||||
expect(day9).toHaveTextContent('2/5');
|
||||
expect(day9).toHaveAccessibleName('2 of 5 visited');
|
||||
expect(day10).toHaveTextContent('0/5');
|
||||
});
|
||||
});
|
||||
@@ -11,12 +11,26 @@ import { StationPills } from '../planner/stationParts';
|
||||
import { plannerWaypointsOf, type TourPlannerWaypoint } from '../planner/tourPlannerWaypoints';
|
||||
import { TourDayRowPill } from '../TourDayRowFacts';
|
||||
import { CardAction, TourNotice } from '../tourParts';
|
||||
import { useDayVisits, useWalkProgress } from './walkProgress';
|
||||
import { clockOf, minutesOf, stationArrivals, stationFit, type StationFit } from './walkSchedule';
|
||||
|
||||
let nextId = 0;
|
||||
const freshId = () => `station-${++nextId}`;
|
||||
|
||||
/** CW-03: a saved walk's stations in order, read once for the dialog; null while they load or could not be read. */
|
||||
/**
|
||||
* CW-03: a synced walk's stations all carry a key. Points without any are the
|
||||
* route's ends, which this device reads in their place while it holds none of
|
||||
* the stations, so they are not listed as the walk's. A walk saved offline has
|
||||
* no keys before it synced, and its stations stay.
|
||||
*/
|
||||
function ownStations(points: TourPlannerWaypoint[], placeId: number): TourPlannerWaypoint[] {
|
||||
return placeId < 0 || points.some((point) => point.key) ? points : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* CW-03: a saved walk's stations in order, read once for the dialog; null while
|
||||
* they load, none where they could not be read.
|
||||
*/
|
||||
function useWalkStations(tripId: number | string, placeId: number): TourPlannerWaypoint[] | null {
|
||||
const [stations, setStations] = useState<{ placeId: number; points: TourPlannerWaypoint[] } | null>(null);
|
||||
useEffect(() => {
|
||||
@@ -26,7 +40,7 @@ function useWalkStations(tripId: number | string, placeId: number): TourPlannerW
|
||||
.then((detail) => {
|
||||
if (controller.signal.aborted) return;
|
||||
const points = walkStationsOf(plannerWaypointsOf(detail.waypoints, freshId));
|
||||
setStations({ placeId, points });
|
||||
setStations({ placeId, points: ownStations(points, placeId) });
|
||||
})
|
||||
.catch(() => {
|
||||
if (!controller.signal.aborted) setStations({ placeId, points: [] });
|
||||
@@ -36,24 +50,32 @@ function useWalkStations(tripId: number | string, placeId: number): TourPlannerW
|
||||
return stations?.placeId === placeId ? stations.points : null;
|
||||
}
|
||||
|
||||
/** The day's status of each station, by its key. */
|
||||
function useDayVisits(assignmentId: number | null) {
|
||||
return useTourVisitStore((state) => (assignmentId === null ? undefined : state.byAssignment[assignmentId]));
|
||||
}
|
||||
|
||||
/**
|
||||
* CW-03: a walk's progress on one of its days, as a pill of the day row:
|
||||
* how many of its stations were visited. Nothing is shown before any is.
|
||||
*/
|
||||
export function WalkProgressPill({ tour, assignmentId }: { tour: TourListItem; assignmentId: number | undefined }) {
|
||||
const { t } = useTranslation();
|
||||
const visits = useDayVisits(assignmentId ?? null);
|
||||
const total = tour.station_count ?? 0;
|
||||
if (tour.tour_type !== 'walk' || total === 0 || !visits) return null;
|
||||
const visited = Object.values(visits).filter((status) => status === 'visited').length;
|
||||
if (visited === 0 && Object.keys(visits).length === 0) return null;
|
||||
const label = t('tours.walk.progress', { visited, total });
|
||||
return <TourDayRowPill icon={CheckCheck} value={`${visited}/${total}`} label={label} testId="plan-walk-progress" />;
|
||||
const progress = useWalkProgress(tour, assignmentId);
|
||||
if (!progress) return null;
|
||||
return (
|
||||
<TourDayRowPill
|
||||
icon={CheckCheck}
|
||||
value={`${progress.visited}/${progress.total}`}
|
||||
label={t('tours.walk.progress', progress)}
|
||||
testId="plan-walk-progress"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the stations can be checked off from here: not without a day or the
|
||||
* right to plan it, and not yet on a day put on the plan offline, which the
|
||||
* server does not know until it synced.
|
||||
*/
|
||||
function markState(canMark: boolean, assignmentId: number | null): 'none' | 'ready' | 'notSynced' {
|
||||
if (!canMark || assignmentId === null) return 'none';
|
||||
return assignmentId < 0 ? 'notSynced' : 'ready';
|
||||
}
|
||||
|
||||
function StatusActions({
|
||||
@@ -177,19 +199,26 @@ function StationRow({
|
||||
);
|
||||
}
|
||||
|
||||
/** The lines above the stations: loading, what is missing for arrivals, where the hours come from, where to check off. */
|
||||
/**
|
||||
* The lines above the stations: loading, stations that could not be read, what
|
||||
* is missing for arrivals, where the hours come from, where to check off.
|
||||
*/
|
||||
function WalkStationsNotes({
|
||||
loading,
|
||||
unread,
|
||||
any,
|
||||
noStart,
|
||||
hoursShown,
|
||||
fromDay,
|
||||
notSynced,
|
||||
}: {
|
||||
loading: boolean;
|
||||
unread: boolean;
|
||||
any: boolean;
|
||||
noStart: boolean;
|
||||
hoursShown: boolean;
|
||||
fromDay: boolean;
|
||||
notSynced: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const quiet = (text: string) => (
|
||||
@@ -200,9 +229,11 @@ function WalkStationsNotes({
|
||||
if (loading) return quiet(t('common.loading'));
|
||||
return (
|
||||
<>
|
||||
{unread && quiet(t('tours.walk.stationsUnread'))}
|
||||
{any && noStart && quiet(t('tours.walk.hours.noStart'))}
|
||||
{hoursShown && <TourNotice icon={<Clock size={13} strokeWidth={2} />}>{t('tours.walk.hours.source')}</TourNotice>}
|
||||
{any && fromDay && quiet(t('tours.walk.visit.fromDay'))}
|
||||
{any && notSynced && quiet(t('tours.walk.visit.notSynced'))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -249,29 +280,33 @@ export function WalkStationsCard({
|
||||
};
|
||||
const start = minutesOf(day?.start);
|
||||
const arrivals = stations && day?.date ? stationArrivals(stations, day.route, start, day.walkingMinutes) : null;
|
||||
const anyHours = stations?.some((station) => station.openingHours) === true;
|
||||
const visited = (stations ?? []).filter((station) => station.key && visits?.[station.key] === 'visited').length;
|
||||
const canCheck = canMark && assignmentId !== null;
|
||||
const listed = stations ?? [];
|
||||
const anyHours = listed.some((station) => station.openingHours);
|
||||
const visited = listed.filter((station) => station.key && visits?.[station.key] === 'visited').length;
|
||||
const marking = markState(canMark, assignmentId);
|
||||
return (
|
||||
<DialogSection
|
||||
className="flex-none"
|
||||
label={t('tours.walk.stations')}
|
||||
action={
|
||||
stations && assignmentId !== null ? (
|
||||
<SoftPill>{t('tours.walk.progress', { visited, total: stations.length })}</SoftPill>
|
||||
// No count where the stations could not be read: it would contradict the day row's.
|
||||
assignmentId !== null && listed.length > 0 ? (
|
||||
<SoftPill>{t('tours.walk.progress', { visited, total: listed.length })}</SoftPill>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<div data-testid="walk-stations" className="flex flex-col gap-2">
|
||||
<WalkStationsNotes
|
||||
loading={stations === null}
|
||||
any={(stations?.length ?? 0) > 0}
|
||||
unread={stations?.length === 0 && tour.station_count !== 0}
|
||||
any={listed.length > 0}
|
||||
noStart={!!day && start === null}
|
||||
hoursShown={!!arrivals && anyHours}
|
||||
fromDay={assignmentId === null}
|
||||
notSynced={marking === 'notSynced'}
|
||||
/>
|
||||
<ol className="m-0 flex list-none flex-col gap-1.5 p-0">
|
||||
{(stations ?? []).map((station, index) => (
|
||||
{listed.map((station, index) => (
|
||||
<StationRow
|
||||
key={station.id}
|
||||
station={station}
|
||||
@@ -279,7 +314,7 @@ export function WalkStationsCard({
|
||||
status={station.key ? visits?.[station.key] : undefined}
|
||||
arrival={arrivals?.[index] ?? null}
|
||||
date={day?.date ?? null}
|
||||
onMark={canCheck && station.key ? (next) => onMark(station.key ?? '', next) : null}
|
||||
onMark={marking === 'ready' && station.key ? (next) => onMark(station.key ?? '', next) : null}
|
||||
/>
|
||||
))}
|
||||
</ol>
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
// CW-03: the visits of a trip's city walks, read when the trip opens and when
|
||||
// the connection changes, and kept current by its socket through the store.
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import type { TourVisit } from '@trek/shared';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { addListener, removeListener } from '../../../api/websocket';
|
||||
import { tourVisitRepo } from '../../../repo/tourVisitRepo';
|
||||
import { useTourVisitStore } from '../../../store/tourVisitStore';
|
||||
import { setForcedOffline } from '../../../sync/networkMode';
|
||||
import { useTourVisitsSync } from './useTourVisitsSync';
|
||||
|
||||
const visit = (assignment_id: number, station_key: string): TourVisit => ({
|
||||
assignment_id,
|
||||
station_key,
|
||||
status: 'visited',
|
||||
});
|
||||
|
||||
function later<T>() {
|
||||
let settle: (value: T) => void = () => undefined;
|
||||
let fail: (reason: unknown) => void = () => undefined;
|
||||
const promise = new Promise<T>((resolve, reject) => {
|
||||
settle = resolve;
|
||||
fail = reject;
|
||||
});
|
||||
return { promise, settle, fail };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
useTourVisitStore.setState({ tripId: null, byAssignment: {} });
|
||||
vi.mocked(addListener).mockClear();
|
||||
vi.mocked(removeListener).mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
act(() => setForcedOffline(false));
|
||||
});
|
||||
|
||||
describe('useTourVisitsSync', () => {
|
||||
it('reads nothing and listens to nothing while off, without a trip, or for a trip id that is no number', () => {
|
||||
const list = vi.spyOn(tourVisitRepo, 'list');
|
||||
|
||||
renderHook(() => useTourVisitsSync(4, false));
|
||||
renderHook(() => useTourVisitsSync(undefined, true));
|
||||
renderHook(() => useTourVisitsSync('abc', true));
|
||||
|
||||
expect(list).not.toHaveBeenCalled();
|
||||
expect(addListener).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reads the trip's visits and listens to its socket, once", async () => {
|
||||
const list = vi.spyOn(tourVisitRepo, 'list').mockResolvedValue({ visits: [visit(9, 'stop-01')] });
|
||||
|
||||
renderHook(() => useTourVisitsSync(4, true));
|
||||
|
||||
await vi.waitFor(() => expect(useTourVisitStore.getState().byAssignment).toEqual({ 9: { 'stop-01': 'visited' } }));
|
||||
expect(list).toHaveBeenCalledExactlyOnceWith(4);
|
||||
expect(addListener).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('reads them again when the connection goes or comes back, without listening twice', async () => {
|
||||
const list = vi.spyOn(tourVisitRepo, 'list').mockResolvedValue({ visits: [] });
|
||||
renderHook(() => useTourVisitsSync(4, true));
|
||||
await vi.waitFor(() => expect(list).toHaveBeenCalledTimes(1));
|
||||
|
||||
act(() => setForcedOffline(true));
|
||||
await vi.waitFor(() => expect(list).toHaveBeenCalledTimes(2));
|
||||
act(() => setForcedOffline(false));
|
||||
await vi.waitFor(() => expect(list).toHaveBeenCalledTimes(3));
|
||||
|
||||
expect(addListener).toHaveBeenCalledOnce();
|
||||
expect(removeListener).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('a read that fails forgets the visits, but not once the hook is gone', async () => {
|
||||
useTourVisitStore.setState({ tripId: '4', byAssignment: { 9: { 'stop-01': 'visited' } } });
|
||||
const answer = later<{ visits: TourVisit[] }>();
|
||||
vi.spyOn(tourVisitRepo, 'list')
|
||||
.mockRejectedValueOnce(new Error('No permission'))
|
||||
.mockReturnValueOnce(answer.promise);
|
||||
|
||||
const first = renderHook(() => useTourVisitsSync(4, true));
|
||||
await vi.waitFor(() => expect(useTourVisitStore.getState().byAssignment).toEqual({}));
|
||||
first.unmount();
|
||||
|
||||
useTourVisitStore.setState({ tripId: '4', byAssignment: { 9: { 'stop-01': 'visited' } } });
|
||||
const second = renderHook(() => useTourVisitsSync(4, true));
|
||||
second.unmount();
|
||||
answer.fail(new Error('Gone'));
|
||||
await expect(answer.promise).rejects.toThrow('Gone');
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(useTourVisitStore.getState().byAssignment).toEqual({ 9: { 'stop-01': 'visited' } });
|
||||
});
|
||||
|
||||
it('stops listening when it goes, and listens to the next trip when the trip changes', () => {
|
||||
vi.spyOn(tourVisitRepo, 'list').mockResolvedValue({ visits: [] });
|
||||
const { rerender, unmount } = renderHook(({ trip }) => useTourVisitsSync(trip, true), {
|
||||
initialProps: { trip: 4 },
|
||||
});
|
||||
const [[firstListener]] = vi.mocked(addListener).mock.calls;
|
||||
|
||||
rerender({ trip: 5 });
|
||||
expect(removeListener).toHaveBeenCalledWith(firstListener);
|
||||
expect(addListener).toHaveBeenCalledTimes(2);
|
||||
const secondListener = vi.mocked(addListener).mock.calls[1][0];
|
||||
|
||||
unmount();
|
||||
expect(removeListener).toHaveBeenLastCalledWith(secondListener);
|
||||
});
|
||||
|
||||
it('a read for the trip left before answers too late to show', async () => {
|
||||
const left = later<{ visits: TourVisit[] }>();
|
||||
vi.spyOn(tourVisitRepo, 'list')
|
||||
.mockReturnValueOnce(left.promise)
|
||||
.mockResolvedValueOnce({ visits: [visit(30, 'stop-02')] });
|
||||
const { rerender } = renderHook(({ trip }) => useTourVisitsSync(trip, true), { initialProps: { trip: 4 } });
|
||||
|
||||
rerender({ trip: 5 });
|
||||
await vi.waitFor(() => expect(useTourVisitStore.getState().byAssignment).toEqual({ 30: { 'stop-02': 'visited' } }));
|
||||
left.settle({ visits: [visit(9, 'stop-01')] });
|
||||
await left.promise;
|
||||
|
||||
expect(useTourVisitStore.getState()).toMatchObject({ tripId: '5', byAssignment: { 30: { 'stop-02': 'visited' } } });
|
||||
});
|
||||
});
|
||||
@@ -1,39 +1,36 @@
|
||||
import { tourVisitSchema } from '@trek/shared';
|
||||
import { useEffect } from 'react';
|
||||
import { addListener, removeListener } from '../../../api/websocket';
|
||||
import { useTourVisitStore } from '../../../store/tourVisitStore';
|
||||
import type { WebSocketEvent } from '../../../types';
|
||||
import { useNetworkMode } from '../../../hooks/useNetworkMode';
|
||||
import { useTourVisitStore, watchTourVisits } from '../../../store/tourVisitStore';
|
||||
|
||||
/**
|
||||
* CW-03: the visits of a trip's city walks, read when the trip opens and kept
|
||||
* current by its socket, so a station another traveller checks off shows on
|
||||
* every day plan at once. Offline the day plan shows none until it is back.
|
||||
* CW-03: the visits of a trip's city walks, read when the trip opens and again
|
||||
* when the connection comes and goes, and kept current by its socket, so a
|
||||
* station another traveller checks off shows on every day plan at once. Once a
|
||||
* reconnect has sent the waiting marks, the sync reads them once more
|
||||
* (reloadTourVisits). Offline they read from this device, with the marks made
|
||||
* here still waiting to sync.
|
||||
*/
|
||||
export function useTourVisitsSync(tripId: number | string | undefined, enabled: boolean) {
|
||||
const { offline } = useNetworkMode();
|
||||
const id = enabled && tripId !== undefined && !Number.isNaN(Number(tripId)) ? tripId : null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || tripId === undefined) return;
|
||||
if (id === null) return;
|
||||
let current = true;
|
||||
useTourVisitStore
|
||||
.getState()
|
||||
.load(tripId)
|
||||
.load(id)
|
||||
.catch(() => {
|
||||
// Offline or refused, the day plan shows no progress rather than another trip's.
|
||||
if (current) useTourVisitStore.getState().reset(tripId);
|
||||
// Refused, or no copy on this device: the day plan shows no progress rather than another trip's.
|
||||
if (current) useTourVisitStore.getState().reset(id);
|
||||
});
|
||||
const onEvent = (event: WebSocketEvent) => {
|
||||
if (event?.type !== 'tours:visits' || String(event.tripId ?? '') !== String(tripId)) return;
|
||||
const visits = Array.isArray(event.visits)
|
||||
? event.visits.flatMap((raw) => {
|
||||
const parsed = tourVisitSchema.safeParse(raw);
|
||||
return parsed.success ? [parsed.data] : [];
|
||||
})
|
||||
: [];
|
||||
useTourVisitStore.getState().applyRemote(Number(event.assignmentId), visits);
|
||||
};
|
||||
addListener(onEvent);
|
||||
return () => {
|
||||
current = false;
|
||||
removeListener(onEvent);
|
||||
};
|
||||
}, [enabled, tripId]);
|
||||
}, [id, offline]);
|
||||
|
||||
useEffect(() => {
|
||||
if (id === null) return;
|
||||
return watchTourVisits(id);
|
||||
}, [id]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
// CW-03: a city walk's progress on one of its days, read alike by the day rows of the desktop and the phone.
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { useTourVisitStore } from '../../../store/tourVisitStore';
|
||||
import { useDayVisits, useWalkProgress, walkProgressOf } from './walkProgress';
|
||||
|
||||
const walk = { tour_type: 'walk', station_count: 5 } as const;
|
||||
|
||||
beforeEach(() => useTourVisitStore.setState({ tripId: null, byAssignment: {} }));
|
||||
|
||||
describe('walkProgressOf', () => {
|
||||
it('says nothing for a hike, a walk without stops, or a day without marks', () => {
|
||||
const visits = { 'stop-01': 'visited' } as const;
|
||||
expect(walkProgressOf({ tour_type: 'hike', station_count: 5 }, visits)).toBeNull();
|
||||
expect(walkProgressOf({ ...walk, station_count: 0 }, visits)).toBeNull();
|
||||
expect(walkProgressOf({ ...walk, station_count: null }, visits)).toBeNull();
|
||||
expect(walkProgressOf({ tour_type: 'walk' }, visits)).toBeNull();
|
||||
expect(walkProgressOf(walk, undefined)).toBeNull();
|
||||
expect(walkProgressOf(walk, {})).toBeNull();
|
||||
});
|
||||
|
||||
it('counts the visited stops of all of them, a skip as marked but not visited', () => {
|
||||
const visits = { 'stop-01': 'visited', 'stop-02': 'visited', 'stop-03': 'skipped' } as const;
|
||||
expect(walkProgressOf(walk, visits)).toEqual({ visited: 2, total: 5 });
|
||||
expect(walkProgressOf(walk, { 'stop-03': 'skipped' })).toEqual({ visited: 0, total: 5 });
|
||||
});
|
||||
|
||||
it('never counts more visited stops than the walk has', () => {
|
||||
const visits = { 'stop-01': 'visited', 'stop-02': 'visited', 'stop-03': 'visited' } as const;
|
||||
expect(walkProgressOf({ ...walk, station_count: 2 }, visits)).toEqual({ visited: 2, total: 2 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('useWalkProgress', () => {
|
||||
it("reads the day's visits from the store, and nothing without a day", () => {
|
||||
useTourVisitStore.setState({ byAssignment: { 9: { 'stop-01': 'visited' }, 10: { 'stop-02': 'skipped' } } });
|
||||
expect(renderHook(() => useWalkProgress(walk, 9)).result.current).toEqual({ visited: 1, total: 5 });
|
||||
expect(renderHook(() => useWalkProgress(walk, 10)).result.current).toEqual({ visited: 0, total: 5 });
|
||||
expect(renderHook(() => useWalkProgress(walk, 11)).result.current).toBeNull();
|
||||
expect(renderHook(() => useWalkProgress(walk, undefined)).result.current).toBeNull();
|
||||
expect(renderHook(() => useDayVisits(null)).result.current).toBeUndefined();
|
||||
expect(renderHook(() => useDayVisits(9)).result.current).toEqual({ 'stop-01': 'visited' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { TourListItem } from '@trek/shared';
|
||||
import { useTourVisitStore, type VisitsByStation } from '../../../store/tourVisitStore';
|
||||
|
||||
/** The day's status of each station of a walk, by its key; undefined before any is marked or without a day. */
|
||||
export function useDayVisits(assignmentId: number | null | undefined): VisitsByStation | undefined {
|
||||
return useTourVisitStore((state) => (assignmentId == null ? undefined : state.byAssignment[assignmentId]));
|
||||
}
|
||||
|
||||
/**
|
||||
* CW-03: how many of a walk's stations were visited on one day, out of all of
|
||||
* them, or null where there is nothing to say yet: not a walk, no stations, or
|
||||
* none marked on that day. A skip counts as marked but not as visited.
|
||||
*/
|
||||
export function walkProgressOf(
|
||||
tour: Pick<TourListItem, 'tour_type' | 'station_count'>,
|
||||
visits: VisitsByStation | undefined
|
||||
): { visited: number; total: number } | null {
|
||||
const total = tour.station_count ?? 0;
|
||||
if (tour.tour_type !== 'walk' || total === 0 || !visits) return null;
|
||||
const statuses = Object.values(visits);
|
||||
if (statuses.length === 0) return null;
|
||||
const visited = statuses.filter((status) => status === 'visited').length;
|
||||
return { visited: Math.min(visited, total), total };
|
||||
}
|
||||
|
||||
/** A walk's progress on the day its row stands for, shared by the day rows of the desktop and the phone. */
|
||||
export function useWalkProgress(
|
||||
tour: Pick<TourListItem, 'tour_type' | 'station_count'>,
|
||||
assignmentId: number | null | undefined
|
||||
): { visited: number; total: number } | null {
|
||||
return walkProgressOf(tour, useDayVisits(assignmentId));
|
||||
}
|
||||
Reference in New Issue
Block a user