diff --git a/client/src/components/Dawarich/DawarichSuggestionsPanel.tsx b/client/src/components/Dawarich/DawarichSuggestionsPanel.tsx index 8d9b0360f..503b699d9 100644 --- a/client/src/components/Dawarich/DawarichSuggestionsPanel.tsx +++ b/client/src/components/Dawarich/DawarichSuggestionsPanel.tsx @@ -4,6 +4,7 @@ import type { DawarichAccept, DawarichSuggestion, DawarichSuggestionTarget } fro import { useTranslation } from '../../i18n' import { useDawarichSuggestions } from '../../hooks/useDawarichSuggestions' import { useTripStore } from '../../store/tripStore' +import { useSettingsStore } from '../../store/settingsStore' import { useIsPhone } from '../../mobile/useIsPhone' import { relativeTime } from '../../utils/relativeTime' import { Tooltip } from '../shared/Tooltip' @@ -123,6 +124,9 @@ export default function DawarichSuggestionsPanel({ allowPlace: trips.length > 0, // The trip name is noise when every row is from the same trip. showTrip: tripId === undefined, + // In the trip rail the arrival is the half that places a stop; how long somebody stood + // there is a second figure on a row that already does not wrap. + showDuration: tripId === undefined, } return ( @@ -277,13 +281,21 @@ export default function DawarichSuggestionsPanel({ * The actions fade in on hover on a pointer device and stay visible on touch, * where there is no hover to reveal them. */ -function SuggestionRow({ +/** + * One stay, as a card with its actions clipped to the side. + * + * Exported because the journal draws these rows in its own timeline now — folded into a + * day rather than stacked in a panel above it — and a second copy of a row this detailed + * would be two things to keep in step, plus a straight hit on the duplication budget. + */ +export function SuggestionRow({ suggestion, busy, allowJournal = false, allowPlace = false, showTrip = false, showDate = false, + showDuration = true, phone = false, onAccept, onDismiss, @@ -295,6 +307,8 @@ function SuggestionRow({ allowPlace?: boolean showTrip?: boolean showDate?: boolean + /** How long the stay lasted. Off in the trip rail, where the arrival is the useful half. */ + showDuration?: boolean /** Rendered inside the phone shell, which has its own palette and its own reach. */ phone?: boolean onAccept?: (target: DawarichSuggestionTarget) => void @@ -302,6 +316,9 @@ function SuggestionRow({ onRestore?: () => void }): React.ReactElement { const { t, locale } = useTranslation() + // The traveller's own clock: these times used to come straight out of the timestamp, so + // a 12-hour setting got 24-hour times here and nowhere else. + const is12h = useSettingsStore(s => s.settings.time_format) === '12h' return (
@@ -348,8 +365,8 @@ function SuggestionRow({ {showDate && ( {formatDayHeading(suggestion.localDate, locale)} )} - {timeRange(suggestion.startedAt, suggestion.endedAt)} - {formatDuration(suggestion.durationMinutes, t)} + {timeRange(suggestion.startedAt, suggestion.endedAt, is12h)} + {showDuration && {formatDuration(suggestion.durationMinutes, t)}} {suggestion.state === 'accepted' && ( diff --git a/client/src/components/Dawarich/dawarichSuggestionModel.test.ts b/client/src/components/Dawarich/dawarichSuggestionModel.test.ts index 3eb967e1a..b522483c1 100644 --- a/client/src/components/Dawarich/dawarichSuggestionModel.test.ts +++ b/client/src/components/Dawarich/dawarichSuggestionModel.test.ts @@ -7,6 +7,7 @@ import { formatDayOption, formatDuration, groupByDay, + openStaysByDate, timeRange, } from './dawarichSuggestionModel' @@ -105,12 +106,22 @@ describe('clockOf / timeRange', () => { }) it('FE-DAWARICH-SUGMODEL-006: a range when both ends read, the arrival alone when the end does not', () => { - expect(timeRange('2026-09-10T10:15:00+02:00', '2026-09-10T12:40:00+02:00')).toBe('10:15 – 12:40') - expect(timeRange('2026-09-10T10:15:00+02:00', 'nonsense')).toBe('10:15') + expect(timeRange('2026-09-10T10:15:00+02:00', '2026-09-10T12:40:00+02:00', false)).toBe('10:15 – 12:40') + expect(timeRange('2026-09-10T10:15:00+02:00', 'nonsense', false)).toBe('10:15') }) it('FE-DAWARICH-SUGMODEL-007: no arrival, no range', () => { - expect(timeRange('nonsense', '2026-09-10T12:40:00+02:00')).toBe('') + expect(timeRange('nonsense', '2026-09-10T12:40:00+02:00', false)).toBe('') + }) + + it('FE-DAWARICH-SUGMODEL-012: a twelve-hour clock gets twelve-hour times, both ends of the range', () => { + // These were cut out of the timestamp and printed as they stood, so a traveller on a + // 12-hour clock read every Dawarich time in 24-hour while the rest of the app obeyed + // the setting. + expect(timeRange('2026-09-10T10:15:00+02:00', '2026-09-10T12:40:00+02:00', true)).toBe('10:15 AM – 12:40 PM') + expect(timeRange('2026-09-10T14:05:00+02:00', '2026-09-10T23:00:00+02:00', true)).toBe('2:05 PM – 11:00 PM') + // Midnight is 12 AM, not 0 AM, and noon is 12 PM. + expect(timeRange('2026-09-10T00:30:00+02:00', '2026-09-10T12:00:00+02:00', true)).toBe('12:30 AM – 12:00 PM') }) }) @@ -156,3 +167,49 @@ describe('formatDayOption', () => { expect(formatDayOption(1, null, 'en-GB', t)).toEqual({ label: 'planner.dayN:{"n":1}', badge: undefined }) }) }) + +describe('openStaysByDate', () => { + it('FE-DAWARICH-SUGMODEL-015: buckets the open stays by their own local day', () => { + // What a journal timeline asks for: it draws one day and folds that day's stays into + // it, so it looks them up by date rather than walking a flat list per day. + const byDate = openStaysByDate([ + stay({ id: 1, localDate: '2026-09-10' }), + stay({ id: 2, localDate: '2026-09-11' }), + stay({ id: 3, localDate: '2026-09-10' }), + ]) + + expect([...byDate.keys()].sort()).toEqual(['2026-09-10', '2026-09-11']) + expect(byDate.get('2026-09-10')!.map(s => s.id)).toEqual([1, 3]) + }) + + it('FE-DAWARICH-SUGMODEL-016: within a day they are in the order they were lived', () => { + // A run of stays reads as an afternoon only in that order; whatever order the server + // sent them in is not it. + const byDate = openStaysByDate([ + stay({ id: 1, localDate: '2026-09-10', startedAt: '2026-09-10T16:00:00+02:00' }), + stay({ id: 2, localDate: '2026-09-10', startedAt: '2026-09-10T08:30:00+02:00' }), + stay({ id: 3, localDate: '2026-09-10', startedAt: '2026-09-10T12:15:00+02:00' }), + ]) + + expect(byDate.get('2026-09-10')!.map(s => s.id)).toEqual([2, 3, 1]) + }) + + it('FE-DAWARICH-SUGMODEL-017: only what is still waiting', () => { + // An accepted stay is an entry on that timeline already, and a dismissed one was waved + // away on purpose; offering either again is offering to do it twice. + const byDate = openStaysByDate([ + stay({ id: 1, localDate: '2026-09-10', state: 'accepted' }), + stay({ id: 2, localDate: '2026-09-10', state: 'dismissed' }), + stay({ id: 3, localDate: '2026-09-10' }), + ]) + + expect(byDate.get('2026-09-10')!.map(s => s.id)).toEqual([3]) + }) + + it('FE-DAWARICH-SUGMODEL-018: a day whose every stay is handled is not a day at all', () => { + // An empty bucket would draw a fold saying "0 stays" on a day that has none. + const byDate = openStaysByDate([stay({ id: 1, localDate: '2026-09-10', state: 'accepted' })]) + + expect(byDate.size).toBe(0) + }) +}) diff --git a/client/src/components/Dawarich/dawarichSuggestionModel.ts b/client/src/components/Dawarich/dawarichSuggestionModel.ts index eb53eec7f..7dbfe2179 100644 --- a/client/src/components/Dawarich/dawarichSuggestionModel.ts +++ b/client/src/components/Dawarich/dawarichSuggestionModel.ts @@ -1,5 +1,6 @@ import type { DawarichSuggestion } from '@trek/shared' import { dayColor } from '../Map/dawarichTrail' +import { formatClockTime } from '../../utils/formatters' /** * Pure shaping for the suggestions panel — no React, so the grouping and the @@ -44,6 +45,30 @@ export function groupByDay(suggestions: DawarichSuggestion[]): SuggestionDay[] { .reverse() } +/** + * The stays still waiting, by the local day they happened on. + * + * What a journal timeline needs: it draws one day at a time and folds that day's stays + * into it, so it asks by date rather than walking a flat list per day. Only `new` ones — + * an accepted stay is already an entry on that timeline and a dismissed one was waved + * away on purpose — and within a day the order is the order they were lived in, which is + * what makes a run of them read as an afternoon. + * + * A Map rather than the day list `groupByDay` builds: that one is ordered newest-first for + * a panel to print, and this one is looked up by the day the timeline is already drawing. + */ +export function openStaysByDate(suggestions: DawarichSuggestion[]): Map { + const byDate = new Map(); + for (const stay of suggestions) { + if (stay.state !== 'new') continue; + const bucket = byDate.get(stay.localDate); + if (bucket) bucket.push(stay); + else byDate.set(stay.localDate, [stay]); + } + for (const stays of byDate.values()) stays.sort((a, b) => (a.startedAt < b.startedAt ? -1 : 1)); + return byDate; +} + /** `HH:MM` out of an ISO timestamp, in the offset the timestamp carries. */ export function clockOf(iso: string): string { return /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(iso) ? iso.slice(11, 16) : '' @@ -54,10 +79,15 @@ export function clockOf(iso: string): string { * * An en dash with hair spaces rather than a hyphen: this is a range, and it sits * next to times often enough that the difference is visible. + * + * `is12h` is not optional on purpose. These clocks were cut straight out of the + * timestamp and printed, so a traveller on a 12-hour clock read every Dawarich time in + * 24-hour while the rest of the app obeyed the setting. A required argument makes the + * next caller answer the question rather than inherit the bug. */ -export function timeRange(startedAt: string, endedAt: string): string { - const from = clockOf(startedAt) - const to = clockOf(endedAt) +export function timeRange(startedAt: string, endedAt: string, is12h: boolean): string { + const from = formatClockTime(clockOf(startedAt), is12h) + const to = formatClockTime(clockOf(endedAt), is12h) if (!from) return '' return to ? `${from} – ${to}` : from } diff --git a/client/src/components/Journey/JourneyDayDawarich.test.tsx b/client/src/components/Journey/JourneyDayDawarich.test.tsx new file mode 100644 index 000000000..2b20b4c75 --- /dev/null +++ b/client/src/components/Journey/JourneyDayDawarich.test.tsx @@ -0,0 +1,147 @@ +// FE-JRN-DAYDAW-001 to FE-JRN-DAYDAW-008 +/** + * The fold a journal day carries for the stays Dawarich recorded on it. + * + * The rows inside it are `SuggestionRow`, which the panel's own suite pins end to end, so + * what is worth holding here is the fold: that it says nothing on a quiet day, that the + * line reads before it is opened, and that the two actions reach the journal with the + * stay they belong to. The whole point of this component is that forty stays no longer + * stand between a reader and their first entry, and that only works while it starts shut. + */ +import { describe, it, expect, vi } from 'vitest' +import { render, screen, within } from '../../../tests/helpers/render' +import { fireEvent } from '@testing-library/react' +import type { DawarichSuggestion } from '@trek/shared' +import { useSettingsStore } from '../../store/settingsStore' +import JourneyDayDawarich from './JourneyDayDawarich' + +function stay(over: Partial & { id: number }): DawarichSuggestion { + const date = over.localDate ?? '2026-09-10' + return { + id: over.id, + sourceVisitId: String(over.id), + tripId: null, + tripTitle: null, + name: over.name ?? 'Cafe Reichard', + lat: 50.94, + lng: 6.96, + startedAt: over.startedAt ?? `${date}T10:15:00+02:00`, + endedAt: over.endedAt ?? `${date}T12:40:00+02:00`, + durationMinutes: over.durationMinutes ?? 145, + localDate: date, + sourceStatus: 'suggested', + confidence: null, + confidenceBand: null, + state: 'new', + target: null, + acceptedPlaceId: null, + acceptedJournalEntryId: null, + acceptedBucketListItemId: null, + sourceChanged: false, + sourceMissing: false, + matchedBucketListItemId: null, + matchedBucketListName: null, + countryCode: null, + firstSeenAt: `${date}T06:00:00Z`, + lastSeenAt: `${date}T06:00:00Z`, + ...over, + } as DawarichSuggestion +} + +function fold(suggestions: DawarichSuggestion[], over: Partial<{ busyId: number | null }> = {}) { + const onAccept = vi.fn() + const onDismiss = vi.fn() + const view = render( + , + ) + return { onAccept, onDismiss, ...view } +} + +const head = () => screen.getByRole('button', { expanded: false }) ?? screen.getByRole('button') + +describe('JourneyDayDawarich', () => { + it('FE-JRN-DAYDAW-001: a day with nothing pending draws nothing at all', () => { + // Not an empty row saying so: a connected, quiet integration is invisible, and this + // one would otherwise appear on every single day of the journey. + const { container } = fold([]) + + expect(container).toBeEmptyDOMElement() + }) + + it('FE-JRN-DAYDAW-002: shut, it says how many and which part of the day they cover', () => { + fold([ + stay({ id: 1, startedAt: '2026-09-10T08:00:00+02:00', endedAt: '2026-09-10T09:30:00+02:00' }), + stay({ id: 2, startedAt: '2026-09-10T14:00:00+02:00', endedAt: '2026-09-10T17:08:00+02:00' }), + ]) + + expect(screen.getByText('2 stays from Dawarich')).toBeInTheDocument() + // First arrival to last departure, not each stay's own range. + expect(screen.getByText('08:00 – 17:08')).toBeInTheDocument() + }) + + it('FE-JRN-DAYDAW-003: one stay takes the singular', () => { + // A single key with a placeholder would read "1 stays". + fold([stay({ id: 1 })]) + + expect(screen.getByText('1 stay from Dawarich')).toBeInTheDocument() + }) + + it('FE-JRN-DAYDAW-004: it starts shut, and the stays are not in the page until it opens', () => { + fold([stay({ id: 1, name: 'Cafe Reichard' })]) + + expect(screen.queryByText('Cafe Reichard')).toBeNull() + expect(head()).toHaveAttribute('aria-expanded', 'false') + + fireEvent.click(head()) + + expect(screen.getByText('Cafe Reichard')).toBeInTheDocument() + }) + + it('FE-JRN-DAYDAW-005: open, each stay is a row with its own two actions', () => { + const { onDismiss } = fold([stay({ id: 7, name: 'Cafe Reichard' })]) + fireEvent.click(head()) + + const row = screen.getByText('Cafe Reichard').closest('div')!.parentElement! + fireEvent.click(within(row).getByRole('button', { name: 'Not a place I visited' })) + + expect(onDismiss).toHaveBeenCalledTimes(1) + expect(onDismiss.mock.calls[0][0]).toMatchObject({ id: 7 }) + }) + + it('FE-JRN-DAYDAW-006: accepting hands back the stay it was asked about and where it goes', () => { + const { onAccept } = fold([stay({ id: 7, name: 'Cafe Reichard' })]) + fireEvent.click(head()) + + fireEvent.click(screen.getByRole('button', { name: /journal|journey/i })) + + expect(onAccept).toHaveBeenCalledTimes(1) + expect(onAccept.mock.calls[0][0]).toMatchObject({ id: 7 }) + expect(onAccept.mock.calls[0][1]).toBe('journal') + }) + + it('FE-JRN-DAYDAW-007: the stay a write is in flight for is the one that goes busy', () => { + fold([stay({ id: 7, name: 'Cafe Reichard' }), stay({ id: 8, name: 'Zum Treppchen' })], { busyId: 7 }) + fireEvent.click(head()) + + const busyRow = screen.getByText('Cafe Reichard').closest('div')!.parentElement! + const idleRow = screen.getByText('Zum Treppchen').closest('div')!.parentElement! + expect(within(busyRow).getAllByRole('button')[0]).toBeDisabled() + expect(within(idleRow).getAllByRole('button')[0]).not.toBeDisabled() + }) + + it('FE-JRN-DAYDAW-008: the span follows the traveller own clock', () => { + useSettingsStore.setState(s => ({ settings: { ...s.settings, time_format: '12h' } })) + fold([ + stay({ id: 1, startedAt: '2026-09-10T08:00:00+02:00', endedAt: '2026-09-10T09:30:00+02:00' }), + stay({ id: 2, startedAt: '2026-09-10T14:00:00+02:00', endedAt: '2026-09-10T17:08:00+02:00' }), + ]) + + expect(screen.getByText('8:00 AM – 5:08 PM')).toBeInTheDocument() + useSettingsStore.setState(s => ({ settings: { ...s.settings, time_format: '24h' } })) + }) +}) diff --git a/client/src/components/Journey/JourneyDayDawarich.tsx b/client/src/components/Journey/JourneyDayDawarich.tsx new file mode 100644 index 000000000..821d20b49 --- /dev/null +++ b/client/src/components/Journey/JourneyDayDawarich.tsx @@ -0,0 +1,97 @@ +import React, { useState } from 'react' +import { ChevronDown, ChevronRight } from 'lucide-react' +import type { DawarichSuggestion, DawarichSuggestionTarget } from '@trek/shared' +import { useTranslation } from '../../i18n' +import DawarichIcon from '../shared/DawarichIcon' +import { SuggestionRow } from '../Dawarich/DawarichSuggestionsPanel' +import { timeRange } from '../Dawarich/dawarichSuggestionModel' +import { useSettingsStore } from '../../store/settingsStore' + +/** + * The stays Dawarich recorded on ONE day of the journal, folded into that day. + * + * They used to be a panel above the timeline: every open stay of every day, stacked over + * the entries, so a fortnight of driving put forty rows between the reader and their own + * first entry. The list belongs where the day is (discussion with Roel, 16.09.), and a + * day of driving still produces four to eleven stays, so the day shows one line with a + * count and opens on a tap. + * + * Shut, it reads as one more card in the day: the mark says where it came from without a + * word of explanation, and the times say which part of the day it covers. Open, it is the + * same rows the panel drew, which is why `SuggestionRow` is imported rather than copied. + * + * It never appears on a day with nothing pending: an integration that is connected and + * quiet should be invisible, not a permanent empty row on every day of the journey. + */ +export default function JourneyDayDawarich({ + suggestions, + busyId, + onAccept, + onDismiss, +}: { + /** The open stays of this day, in the order they were lived. */ + suggestions: DawarichSuggestion[] + /** The stay a write is in flight for, or null. */ + busyId: number | null + onAccept: (suggestion: DawarichSuggestion, target: DawarichSuggestionTarget) => void + onDismiss: (suggestion: DawarichSuggestion) => void +}): React.ReactElement | null { + const { t } = useTranslation() + const is12h = useSettingsStore(s => s.settings.time_format) === '12h' + const [open, setOpen] = useState(false) + + if (suggestions.length === 0) return null + + // From the first arrival to the last departure: what part of the day this covers, in + // one line, so the row says something even while it is shut. Through the same formatter + // the rows use, so the summary and the stays under it cannot disagree about the clock. + const span = timeRange(suggestions[0]!.startedAt, suggestions[suggestions.length - 1]!.endedAt, is12h) + + return ( +
+ + + {open && ( +
+ {suggestions.map(suggestion => ( + onAccept(suggestion, target)} + onDismiss={() => onDismiss(suggestion)} + /> + ))} +
+ )} +
+ ) +} diff --git a/client/src/components/Journey/JourneyDetailPageSettingsDialog.test.tsx b/client/src/components/Journey/JourneyDetailPageSettingsDialog.test.tsx index 677f4240c..e16c22d4d 100644 --- a/client/src/components/Journey/JourneyDetailPageSettingsDialog.test.tsx +++ b/client/src/components/Journey/JourneyDetailPageSettingsDialog.test.tsx @@ -377,8 +377,11 @@ describe('JourneySettingsDialog', () => { it('FE-JRN-SETTINGS-023: the trip-GPX switch reads off by default and turns on in one click (#2194)', async () => { const { onRefresh, onSaved } = mountDialog() - const sw = screen.getByRole('switch', { name: /GPX/i }) - expect(sw).toHaveAttribute('aria-checked', 'false') + // The shared ToggleSwitch is a button with aria-pressed, not a role="switch" with + // aria-checked: the dialog drew its own switches by hand until they turned out to be + // white on near-white in the dark. + const sw = screen.getByRole('button', { name: /GPX/i }) + expect(sw).toHaveAttribute('aria-pressed', 'false') await userEvent.click(sw) @@ -393,8 +396,8 @@ describe('JourneySettingsDialog', () => { // The column is INTEGER, so what arrives over the wire is 1, not true. mountDialog(buildJourney({ show_trip_tracks: 1 })) - const sw = screen.getByRole('switch', { name: /GPX/i }) - expect(sw).toHaveAttribute('aria-checked', 'true') + const sw = screen.getByRole('button', { name: /GPX/i }) + expect(sw).toHaveAttribute('aria-pressed', 'true') await userEvent.click(sw) await waitFor(() => expect(updateJourney).toHaveBeenCalledWith(3, { show_trip_tracks: false })) @@ -404,7 +407,7 @@ describe('JourneySettingsDialog', () => { updateJourney.mockRejectedValueOnce(new Error('nope')) const { onClose } = mountDialog() - await userEvent.click(screen.getByRole('switch', { name: /GPX/i })) + await userEvent.click(screen.getByRole('button', { name: /GPX/i })) await waitFor(() => expect(toastSpy).toHaveBeenCalled()) expect(onClose).not.toHaveBeenCalled() diff --git a/client/src/components/Journey/JourneyDetailPageSettingsDialog.tsx b/client/src/components/Journey/JourneyDetailPageSettingsDialog.tsx index ac83ed463..ee641f212 100644 --- a/client/src/components/Journey/JourneyDetailPageSettingsDialog.tsx +++ b/client/src/components/Journey/JourneyDetailPageSettingsDialog.tsx @@ -11,6 +11,7 @@ import type { JourneyDetail } from '../../store/journeyStore' import { pickGradient } from '../../pages/journeyDetail/JourneyDetailPage.helpers' import { AddTripDialog } from './JourneyDetailPageAddTripDialog' import { normalizeImageFile } from '../../utils/convertHeic' +import ToggleSwitch from '../Settings/ToggleSwitch' export function JourneySettingsDialog({ journey, onClose, onSaved, onOpenInvite, onRefresh, onRestoreSuggestions }: { journey: JourneyDetail @@ -188,25 +189,17 @@ export function JourneySettingsDialog({ journey, onClose, onSaved, onOpenInvite, {/* Trip GPX tracks on the journey map (#2194) */}
- + { if (!savingTracks) handleTracksToggle() }} + label={t('journey.settings.showTripTracks')} + /> +
{/* The three fields a journey may put away (discussion #2299) */} @@ -221,21 +214,17 @@ export function JourneySettingsDialog({ journey, onClose, onSaved, onOpenInvite, ] as const).map(([field, label]) => { const on = journey[field] !== 0 return ( - + {label} + { if (savingField === null) handleFieldToggle(field) }} + label={label} + /> + ) })} diff --git a/client/src/components/Map/MapLayerSwitcher.test.tsx b/client/src/components/Map/MapLayerSwitcher.test.tsx index 5c66c9977..c4579c3d9 100644 --- a/client/src/components/Map/MapLayerSwitcher.test.tsx +++ b/client/src/components/Map/MapLayerSwitcher.test.tsx @@ -1,8 +1,8 @@ -// FE-COMP-MAPLAYER-001 to FE-COMP-MAPLAYER-005 +// FE-COMP-MAPLAYER-001 to FE-COMP-MAPLAYER-006 import React from 'react' import { describe, it, expect, vi } from 'vitest' import { render, screen, fireEvent } from '../../../tests/helpers/render' -import { MapLayerSwitcher } from './MapLayerSwitcher' +import { MapLayerSwitcher, MAP_ROUND_CONTROL_SIZE } from './MapLayerSwitcher' describe('MapLayerSwitcher', () => { it('FE-COMP-MAPLAYER-001: on the default layer, offers the switch to satellite', () => { @@ -41,4 +41,17 @@ describe('MapLayerSwitcher', () => { fireEvent.mouseLeave(button) expect(button.style.background).toBe('transparent') }) + + it('FE-COMP-MAPLAYER-006: the shell is as wide as the size its neighbours are placed off', () => { + render( {}} />) + const button = screen.getByRole('button') + const shell = button.parentElement as HTMLElement + + // The phone's compass stands beside the switcher at inset + size + gap. If the + // markup grew without the constant, the compass would slide back under the shell. + expect(shell.style.padding).toBe('4px') + expect(button.style.width).toBe('34px') + expect(button.style.height).toBe('34px') + expect(parseFloat(button.style.width) + 2 * parseFloat(shell.style.padding)).toBe(MAP_ROUND_CONTROL_SIZE) + }) }) diff --git a/client/src/components/Map/MapLayerSwitcher.tsx b/client/src/components/Map/MapLayerSwitcher.tsx index f9700d8dd..3dd3fb8aa 100644 --- a/client/src/components/Map/MapLayerSwitcher.tsx +++ b/client/src/components/Map/MapLayerSwitcher.tsx @@ -5,9 +5,22 @@ import { MAP_CONTROL_SHADOW } from './mapControlShadow' export type BaseLayer = 'default' | 'satellite' -// Round base-layer switcher for the Leaflet planner map (default street tiles ↔ -// satellite). Same frosted shell as MapCompassPill so it lines up with the other -// map controls; the icon shows the layer it switches to. +// Where the switcher sits and how much room it takes, so a control placed beside it +// (the phone's compass) is positioned off the same numbers instead of guessing them. +// Both map engines place the switcher with the inset, so they cannot drift apart either. + +/** Distance from the map's left edge (plus any side panel) to the switcher. */ +export const MAP_LAYER_SWITCHER_INSET = 20 +/** + * Outer size of the round shell: a 34px button in 4px of padding, the same shell as + * MapCompassPill. The markup below keeps its literals, and FE-COMP-MAPLAYER-006 holds + * them to this number. + */ +export const MAP_ROUND_CONTROL_SIZE = 42 + +// Round base-layer switcher for both planner maps, Leaflet and GL (default street +// tiles ↔ satellite). Same frosted shell as MapCompassPill so it lines up with the +// other map controls; the icon shows the layer it switches to. export function MapLayerSwitcher({ active, onToggle }: { active: BaseLayer; onToggle: () => void }) { const { t } = useTranslation() const isSatellite = active === 'satellite' diff --git a/client/src/components/Map/MapView.test.tsx b/client/src/components/Map/MapView.test.tsx index eb17a6ad5..d44923dbe 100644 --- a/client/src/components/Map/MapView.test.tsx +++ b/client/src/components/Map/MapView.test.tsx @@ -988,6 +988,22 @@ describe('MapView live location', () => { fireEvent.click(screen.getByRole('button', { name: 'Follow my location' })) expect(geoMock.cycleMode).toHaveBeenCalled() }) + + it('FE-COMP-MAPVIEW-077: the map draws no credit control of its own, on either width', () => { + const desktop = render() + // The desktop credit is Leaflet's own, in its own container; this component adds none. + expect(screen.queryByRole('button', { name: 'Map credits' })).toBeNull() + desktop.unmount() + + Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: 420 }) + const { container } = render() + // The phone used to get an (i) here that opened the credit through a class on the + // wrapper. The phone map now carries no visible credit at all (mobile.css), so neither + // the button nor the class it toggled is left behind. + expect(screen.queryByRole('button', { name: 'Map credits' })).toBeNull() + const wrapper = container.querySelector('div.w-full.h-full.relative') as HTMLElement + expect(wrapper.classList.contains('m-attrib-open')).toBe(false) + }) }) describe('MapView bounds fitting', () => { @@ -1048,6 +1064,50 @@ describe('MapView bounds fitting', () => { rerender() expect(mapMock.fitBounds).not.toHaveBeenCalled() }) + + it('FE-COMP-MAPVIEW-078: a caller padding frames the focus points instead of the phone margin, and the day fit keeps its own', () => { + // A phone shell lays a chip rail over the top of the map and a bar plus the dock over + // the bottom. The flat margin put the ends of a framed leg under either of them. + Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: 420 }) + const leg: [number, number][] = [[48.1, 2.1], [48.3, 2.4]] + const chrome = { top: 120, right: 16, bottom: 290, left: 16 } + const { rerender } = render() + expect(mapMock.fitBounds).not.toHaveBeenCalled() + + rerender() + expect(mapMock.fitBounds).toHaveBeenCalledTimes(1) + expect(mapMock.fitBounds.mock.calls[0][1]).toMatchObject({ paddingTopLeft: [16, 120], paddingBottomRight: [16, 290] }) + + // Picking a day is not the caller's frame, so that fit keeps the phone margin. + const places = [buildMapPlace({ id: 1, lat: 48, lng: 2 }), buildMapPlace({ id: 2, lat: 48.2, lng: 2.2 })] + rerender() + expect(mapMock.fitBounds).toHaveBeenCalledTimes(2) + expect(mapMock.fitBounds.mock.calls[1][1]).toMatchObject({ paddingTopLeft: [40, 20], paddingBottomRight: [40, 20] }) + + // And without one, the focus fit falls back to that margin too. + const stage: [number, number][] = [[47, 1], [47.5, 1.5]] + rerender() + expect(mapMock.fitBounds).toHaveBeenCalledTimes(3) + expect(mapMock.fitBounds.mock.calls[2][1]).toMatchObject({ paddingTopLeft: [40, 20], paddingBottomRight: [40, 20] }) + }) + + it('FE-COMP-MAPVIEW-079: the caller padding is read by value, so only new numbers refit the points on screen', () => { + const leg: [number, number][] = [[48.1, 2.1], [48.3, 2.4]] + const { rerender } = render( + , + ) + expect(mapMock.fitBounds).toHaveBeenCalledTimes(1) + + // A parent that builds the object inline hands a new one on every render. The camera + // belongs to the traveller between fits, so that alone must not take it back. + rerender() + expect(mapMock.fitBounds).toHaveBeenCalledTimes(1) + + // New numbers mean the chrome moved, so the same points are framed again around it. + rerender() + expect(mapMock.fitBounds).toHaveBeenCalledTimes(2) + expect(mapMock.fitBounds.mock.calls[1][1]).toMatchObject({ paddingTopLeft: [16, 120], paddingBottomRight: [16, 98] }) + }) }) describe('MapView photo thumbnails', () => { diff --git a/client/src/components/Map/MapView.tsx b/client/src/components/Map/MapView.tsx index 6e36b8e36..169f8bfcb 100644 --- a/client/src/components/Map/MapView.tsx +++ b/client/src/components/Map/MapView.tsx @@ -62,7 +62,7 @@ import { crsForBasemap } from './gcj02Crs' import { isGcj02Basemap, resolveBasemap } from '../../utils/tileUrl' import VectorBasemap from './VectorBasemap' import { useSettingsStore } from '../../store/settingsStore' -import { MapLayerSwitcher } from './MapLayerSwitcher' +import { MapLayerSwitcher, MAP_LAYER_SWITCHER_INSET } from './MapLayerSwitcher' import { computeMapViewport, TILE_SIZE_RASTER, type ViewportPadding } from '../../utils/mapViewport' function categoryIconSvg(iconName: string | null | undefined, size: number): string { @@ -400,15 +400,33 @@ interface BoundsControllerProps { * needs that leg on screen, which is neither the day nor the trip. */ focusPoints?: [number, number][] + /** + * What the caller's own chrome covers while `focusPoints` is framed, in pixels per edge. + * + * `paddingOpts` knows the planner's panels and nothing else, and on a phone it is a flat + * margin. A shell that lays its own bars over the map passes what they cover, so the + * frame lands in the part still visible. Only the fit on `focusPoints` reads it. + * Compared by value: the same numbers in a new object do not refit, while new numbers + * refit the points already handed over, because the chrome they must clear has moved. + */ + fitPadding?: ViewportPadding } -function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMount = false, focusPoints }: BoundsControllerProps) { +/** A padding box as Leaflet's fit options spell it, corner pairs rather than edges. */ +function leafletPadding(box: ViewportPadding): L.FitBoundsOptions { + return { + paddingTopLeft: [box.left, box.top], + paddingBottomRight: [box.right, box.bottom], + } +} + +function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMount = false, focusPoints, fitPadding }: BoundsControllerProps) { const map = useMap() const prevFitKey = useRef(-1) const awaitingRoute = useRef(false) const fitRan = useRef(false) - const fitTo = useCallback((coords: [number, number][]) => { + const fitTo = useCallback((coords: [number, number][], padding: L.FitBoundsOptions = paddingOpts) => { if (coords.length === 0) return try { const bounds = L.latLngBounds(coords) @@ -427,7 +445,7 @@ function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMo * (#1982). MapViewGL never had the nudge, so this also brings the two * renderers back into agreement. */ - map.fitBounds(bounds, { ...paddingOpts, maxZoom: 16, animate: true }) + map.fitBounds(bounds, { ...padding, maxZoom: 16, animate: true }) } } catch {} }, [map, paddingOpts]) @@ -459,14 +477,18 @@ function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMo fitTo([...places.map(p => [p.lat, p.lng] as [number, number]), ...routeCoords]) }, [routeCoords]) // eslint-disable-line react-hooks/exhaustive-deps + // The caller's padding as a value, so a parent that builds the object inline on every + // render does not move the camera each time it renders. + const fitPaddingKey = fitPadding ? [fitPadding.top, fitPadding.right, fitPadding.bottom, fitPadding.left].join(' ') : '' + // Frame whatever was handed over. Nothing happens when it empties, so closing the // picker leaves the map where the user left it rather than snapping back. useEffect(() => { if (!focusPoints?.length) return // A day fit that has not run yet must not overwrite this a moment later. awaitingRoute.current = false - fitTo(focusPoints) - }, [focusPoints]) // eslint-disable-line react-hooks/exhaustive-deps + fitTo(focusPoints, fitPadding ? leafletPadding(fitPadding) : paddingOpts) + }, [focusPoints, fitPaddingKey]) // eslint-disable-line react-hooks/exhaustive-deps return null } @@ -686,6 +708,7 @@ export const MapView = memo(function MapView({ onRemoveVia, alternativeRoutes, focusPoints, + fitPadding, clusterLoosely = false, activeAlternative, onChooseAlternative, @@ -747,10 +770,7 @@ export const MapView = memo(function MapView({ } }, [leftWidth, rightWidth, hasInspector, hasDayDetail]) - const paddingOpts = useMemo((): L.FitBoundsOptions => ({ - paddingTopLeft: [paddingBox.left, paddingBox.top], - paddingBottomRight: [paddingBox.right, paddingBox.bottom], - }), [paddingBox]) + const paddingOpts = useMemo(() => leafletPadding(paddingBox), [paddingBox]) // Open framed on the places rather than on the caller's default, so a trip in Japan shows // Japan straight away instead of the world view followed by a flight across the planet. @@ -1059,7 +1079,7 @@ export const MapView = memo(function MapView({ )} - 0 ? dayPlaces : places} routeCoords={dayPlaces.length > 0 ? routeCoords : []} fitKey={fitKey} paddingOpts={paddingOpts} framedOnMount={initialView.framed} focusPoints={focusPoints} /> + 0 ? dayPlaces : places} routeCoords={dayPlaces.length > 0 ? routeCoords : []} fitKey={fitKey} paddingOpts={paddingOpts} framedOnMount={initialView.framed} focusPoints={focusPoints} fitPadding={fitPadding} /> @@ -1222,7 +1242,7 @@ export const MapView = memo(function MapView({ top of the map, which read as the control moving house rather than as room being made: the inspector is a centred card at most 800 wide, so the corner it would have been clearing is one the card never reaches. */} -
+
diff --git a/client/src/components/Map/MapViewGL.test.tsx b/client/src/components/Map/MapViewGL.test.tsx index 059f295b9..c10a58491 100644 --- a/client/src/components/Map/MapViewGL.test.tsx +++ b/client/src/components/Map/MapViewGL.test.tsx @@ -2,7 +2,7 @@ import React from 'react' import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest' import { http, HttpResponse } from 'msw' import { render } from '../../../tests/helpers/render' -import { act, waitFor } from '@testing-library/react' +import { act, fireEvent, waitFor } from '@testing-library/react' import { resetAllStores } from '../../../tests/helpers/store' import { buildPlace } from '../../../tests/helpers/factories' import { server } from '../../../tests/helpers/msw/server' @@ -10,6 +10,7 @@ import { useSettingsStore } from '../../store/settingsStore' import { useAuthStore } from '../../store/authStore' import maplibregl from 'maplibre-gl' import { DEFAULT_MAP_ZOOM } from '../../constants/mapDefaults' +import { MAP_LAYER_SWITCHER_INSET } from './MapLayerSwitcher' import type { GeoPosition, TrackingMode } from '../../hooks/useGeolocation' import type { PluginMapLayer, PluginMapLayerFeature, PluginMapMarker } from '../../api/client' import type { Poi } from './poiCategories' @@ -254,6 +255,12 @@ beforeEach(() => { glMap.getCanvas.mockImplementation(() => document.createElement('canvas')) glMap.getBearing.mockReturnValue(0) glMap.queryTerrainElevation.mockReturnValue(null) + // 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 + // against a map that never settles. + glMap.isStyleLoaded.mockReturnValue(true) + glMap.getStyle.mockReturnValue({ layers: [] }) + glMap.addSource.mockImplementation(() => undefined) glMarkers.clear() // clearAllMocks() wipes call history but keeps implementations, so anything a // test overrides with mockReturnValue has to be put back here. @@ -2065,4 +2072,229 @@ describe('MapViewGL', () => { expect(glMap.setLayoutProperty).toHaveBeenCalledWith('trip-satellite-raster', 'visibility', 'none') }) + + // A map is busy (isStyleLoaded() false) for as long as tiles or a setData are in flight, + // which on a phone is most of the time and on the road trip stage was every tap. The + // imagery used to wait for a settled style that `styledata` never announced. + + it('FE-COMP-MAPVIEWGL-079: a stored satellite choice is drawn even while the map is still busy', async () => { + loadOnAttach() + useSettingsStore.setState({ + settings: { ...useSettingsStore.getState().settings, map_base_layer: 'satellite' }, + } as never) + glMap.getStyle.mockReturnValue({ layers: [{ id: 'background' }, { id: 'trip-route' }] }) + // Right after `load` the basemap tiles and the overlay sources are still loading. + glMap.isStyleLoaded.mockReturnValue(false) + + render() + await flushFrames() + + expect(glMap.addSource).toHaveBeenCalledWith('trip-satellite', expect.objectContaining({ type: 'raster' })) + expect(glMap.addLayer).toHaveBeenCalledWith( + expect.objectContaining({ id: 'trip-satellite-raster', type: 'raster' }), + 'trip-route', + ) + }) + + it('FE-COMP-MAPVIEWGL-080: a tap on the switcher while a source update is in flight still shows the imagery', async () => { + loadOnAttach() + glMap.getStyle.mockReturnValue({ layers: [{ id: 'background' }, { id: 'trip-route' }] }) + + const { getByRole } = render() + await flushFrames() + expect(glMap.addSource).not.toHaveBeenCalledWith('trip-satellite', expect.anything()) + + glMap.isStyleLoaded.mockReturnValue(false) + fireEvent.click(getByRole('button', { name: 'Switch to satellite view' })) + await flushFrames() + + expect(useSettingsStore.getState().settings.map_base_layer).toBe('satellite') + expect(glMap.addSource).toHaveBeenCalledWith('trip-satellite', expect.objectContaining({ type: 'raster' })) + expect(glMap.addLayer).toHaveBeenCalledWith( + expect.objectContaining({ id: 'trip-satellite-raster' }), + 'trip-route', + ) + }) + + it('FE-COMP-MAPVIEWGL-081: imagery that is already on the map flips visibility at once, busy or not', async () => { + loadOnAttach() + glMap.getSource.mockImplementation((id: string) => (id === 'trip-satellite' ? {} : null)) + glMap.getLayer.mockImplementation((id: string) => (id === 'trip-satellite-raster' ? {} : null)) + + const { getByRole } = render() + await flushFrames() + glMap.setLayoutProperty.mockClear() + + glMap.isStyleLoaded.mockReturnValue(false) + fireEvent.click(getByRole('button', { name: 'Switch to satellite view' })) + await flushFrames() + + expect(glMap.setLayoutProperty).toHaveBeenCalledWith('trip-satellite-raster', 'visibility', 'visible') + // Flipping it is all a second tap takes: nothing is built a second time. + expect(glMap.addSource).not.toHaveBeenCalledWith('trip-satellite', expect.anything()) + expect(glMap.addLayer).not.toHaveBeenCalledWith(expect.objectContaining({ id: 'trip-satellite-raster' }), expect.anything()) + }) + + it('FE-COMP-MAPVIEWGL-082: a style that is not in yet keeps the plain basemap until styledata brings it', async () => { + loadOnAttach() + useSettingsStore.setState({ + settings: { ...useSettingsStore.getState().settings, map_base_layer: 'satellite' }, + } as never) + glMap.getStyle.mockReturnValue({ layers: [{ id: 'background' }, { id: 'trip-route' }] }) + // What both engines do when the style document itself has not loaded. + let styleIn = false + glMap.addSource.mockImplementation((id: string) => { + if (id === 'trip-satellite' && !styleIn) throw new Error('Style is not done loading.') + }) + + render() + await flushFrames() + expect(glMap.addLayer).not.toHaveBeenCalledWith(expect.objectContaining({ id: 'trip-satellite-raster' }), expect.anything()) + + styleIn = true + const subscribed = glMap.on.mock.calls.filter(c => c[0] === 'styledata') + const styledata = subscribed[subscribed.length - 1]?.[1] as (() => void) | undefined + expect(styledata).toBeDefined() + act(() => { styledata!() }) + + expect(glMap.addLayer).toHaveBeenCalledWith( + expect.objectContaining({ id: 'trip-satellite-raster' }), + 'trip-route', + ) + }) + + it('FE-COMP-MAPVIEWGL-083: the switcher sits the shared inset off the map edge, past any side panel', async () => { + const { getByRole, rerender } = render() + await flushFrames() + // Button, then its frosted shell, then the positioned wrapper. + const wrapper = () => getByRole('button', { name: 'Switch to satellite view' }).parentElement!.parentElement! + + // The phone's compass is placed off the same inset, so the two cannot drift apart. + expect(wrapper().style.left).toBe(`${MAP_LAYER_SWITCHER_INSET}px`) + + rerender() + await flushFrames() + expect(wrapper().style.left).toBe(`${240 + MAP_LAYER_SWITCHER_INSET}px`) + }) + + it('FE-COMP-MAPVIEWGL-084: a source left behind without its layer still gets the layer', async () => { + loadOnAttach() + useSettingsStore.setState({ + settings: { ...useSettingsStore.getState().settings, map_base_layer: 'satellite' }, + } as never) + glMap.getStyle.mockReturnValue({ layers: [{ id: 'background' }, { id: 'trip-route' }] }) + // An earlier pass that got the source in and then failed on the layer. + glMap.getSource.mockImplementation((id: string) => (id === 'trip-satellite' ? {} : null)) + + render() + await flushFrames() + + // Guarded on the source, the pass would have seen it and built nothing, for good. + expect(glMap.addLayer).toHaveBeenCalledWith( + expect.objectContaining({ id: 'trip-satellite-raster', type: 'raster' }), + 'trip-route', + ) + expect(glMap.addSource).not.toHaveBeenCalledWith('trip-satellite', expect.anything()) + }) + + it('FE-COMP-MAPVIEWGL-085: a caller padding frames the focus points instead of the phone margin, and the day fit keeps its own', async () => { + // A phone shell lays a chip rail over the top of the map and a bar plus the dock over + // the bottom. The flat 40px margin put the ends of a framed leg under either of them. + const original = window.innerWidth + Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: 420 }) + try { + const leg: [number, number][] = [[48.1, 2.1], [48.3, 2.4]] + const chrome = { top: 120, right: 16, bottom: 290, left: 16 } + const { rerender } = render() + await act(async () => {}) + expect(glMap.fitBounds).not.toHaveBeenCalled() + + rerender() + await act(async () => {}) + expect(glMap.fitBounds).toHaveBeenCalledTimes(1) + expect(glMap.fitBounds.mock.calls[0][1]).toMatchObject({ padding: chrome, maxZoom: 15 }) + + // Picking a day is not the caller's frame, so that fit keeps the phone margin. + const places = [buildMapPlace({ id: 88, lat: 48.1, lng: 2.1 }), buildMapPlace({ id: 89, lat: 48.2, lng: 2.2 })] + rerender() + await act(async () => {}) + expect(glMap.fitBounds).toHaveBeenCalledTimes(2) + expect(glMap.fitBounds.mock.calls[1][1]).toMatchObject({ padding: { top: 40, right: 20, bottom: 40, left: 20 } }) + + // And without one, the focus fit falls back to that margin too. + const stage: [number, number][] = [[47, 1], [47.5, 1.5]] + rerender() + await act(async () => {}) + expect(glMap.fitBounds).toHaveBeenCalledTimes(3) + expect(glMap.fitBounds.mock.calls[2][1]).toMatchObject({ padding: { top: 40, right: 20, bottom: 40, left: 20 } }) + } finally { + Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: original }) + } + }) + + it('FE-COMP-MAPVIEWGL-086: the caller padding is read by value, so only new numbers refit the points on screen', async () => { + const leg: [number, number][] = [[48.1, 2.1], [48.3, 2.4]] + const { rerender } = render( + , + ) + await act(async () => {}) + expect(glMap.fitBounds).toHaveBeenCalledTimes(1) + + // A parent that builds the object inline hands a new one on every render. The camera + // belongs to the traveller between fits, so that alone must not take it back. + rerender() + await act(async () => {}) + expect(glMap.fitBounds).toHaveBeenCalledTimes(1) + + // New numbers mean the chrome moved, so the same points are framed again around it. + rerender() + await act(async () => {}) + expect(glMap.fitBounds).toHaveBeenCalledTimes(2) + expect(glMap.fitBounds.mock.calls[1][1]).toMatchObject({ padding: { top: 120, right: 16, bottom: 98, left: 16 } }) + }) +}) +describe('MapViewGL attribution', () => { + const flushFrames = () => act(async () => { await new Promise(resolve => setTimeout(resolve, 40)) }) + + /** The compact control as maplibre leaves it on a narrow map: collapsed class, open. */ + function compactAttribution(container: HTMLElement): HTMLElement { + const el = document.createElement('details') + el.className = 'maplibregl-ctrl maplibregl-ctrl-attrib maplibregl-compact maplibregl-compact-show' + el.setAttribute('open', '') + // Inside the map container itself, where maplibre puts its controls. + container.querySelectorAll('div')[1]?.appendChild(el) + return el + } + + it('FE-COMP-MAPVIEWGL-077: the credit starts as the little button, not as a ribbon', async () => { + const { container } = render() + await flushFrames() + const attrib = compactAttribution(container) + + const idle = glMap.once.mock.calls.find(c => c[0] === 'idle')?.[1] as (() => void) | undefined + expect(idle).toBeDefined() + act(() => { idle!() }) + + // Both engines open theirs on a phone and only tuck it away on the first drag, so + // the first thing on a screen the map fills is a two-line band across the bottom. + expect(attrib.classList.contains('maplibregl-compact-show')).toBe(false) + expect(attrib.hasAttribute('open')).toBe(false) + // Still there, still one tap away: nothing about the credit is removed. + expect(attrib.classList.contains('maplibregl-ctrl-attrib')).toBe(true) + }) + + it('FE-COMP-MAPVIEWGL-078: a map wide enough to show the credit in full is left alone', async () => { + const { container } = render() + await flushFrames() + const el = document.createElement('details') + // No `compact-show`, which is what a map over 640px reports. + el.className = 'maplibregl-ctrl maplibregl-ctrl-attrib' + el.setAttribute('open', '') + container.querySelectorAll('div')[1]?.appendChild(el) + + const idle = glMap.once.mock.calls.find(c => c[0] === 'idle')?.[1] as (() => void) | undefined + act(() => { idle!() }) + + expect(el.hasAttribute('open')).toBe(true) + }) }) diff --git a/client/src/components/Map/MapViewGL.tsx b/client/src/components/Map/MapViewGL.tsx index f21dddf04..e72b138ef 100644 --- a/client/src/components/Map/MapViewGL.tsx +++ b/client/src/components/Map/MapViewGL.tsx @@ -9,7 +9,7 @@ import { renderIconMarkup } from '../../utils/iconMarkup' import type mapboxgl from 'mapbox-gl' import { useSettingsStore } from '../../store/settingsStore' import { useTranslation } from '../../i18n/TranslationContext' -import { MapLayerSwitcher, type BaseLayer } from './MapLayerSwitcher' +import { MapLayerSwitcher, MAP_LAYER_SWITCHER_INSET, type BaseLayer } from './MapLayerSwitcher' import { useAuthStore } from '../../store/authStore' import { getCached, isLoading, fetchPhoto, onThumbReady, getAllThumbs } from '../../services/photoService' import { isCustomPlaceImage, photoCacheKey } from './placePhoto' @@ -40,7 +40,7 @@ import { resolveTrackColor, hasManualTrackColor } from './trackColors' import { buildPoiPopupHtml } from './placePopup' import { pluginsApi, type PluginMapMarker, type PluginMapLayer } from '../../api/client' import { DEFAULT_MAP_CENTER, DEFAULT_MAP_ZOOM, SATELLITE_TILE_URL, SATELLITE_TILE_ATTRIBUTION, SATELLITE_TILE_MAXZOOM } from '../../constants/mapDefaults' -import { computeMapViewport, TILE_SIZE_GL } from '../../utils/mapViewport' +import { computeMapViewport, TILE_SIZE_GL, type ViewportPadding } from '../../utils/mapViewport' function categoryIconSvg(iconName: string | null | undefined, size: number): string { const IconComponent = (iconName && CATEGORY_ICON_MAP[iconName]) || CATEGORY_ICON_MAP['MapPin'] @@ -185,6 +185,16 @@ interface Props { * needs that leg on screen, which is neither the day nor the trip. */ focusPoints?: [number, number][] + /** + * What the caller's own chrome covers while `focusPoints` is framed, in pixels per edge. + * + * The default padding knows this component's panels and nothing else, and on a phone it + * is a flat margin. A shell that lays its own bars over the map passes what they cover, + * so the frame lands in the part still visible. Only the fit on `focusPoints` reads it. + * Compared by value: the same numbers in a new object do not refit, while new numbers + * refit the points already handed over, because the chrome they must clear has moved. + */ + fitPadding?: ViewportPadding /** * Let markers stay apart longer than usual. * @@ -277,15 +287,30 @@ function addPlaceClusterLayers(map: any): void { * Puts the imagery on the map, or takes it off again. * * Built on demand rather than once at load: a style change drops every source the map - * had, and a hot reload does the same. Guarded on its own absence, so the usual pass is - * a no-op and only the visibility flips. + * had, and a hot reload does the same. Visibility comes first: a layer that is already + * there only needs flipping, so the usual pass is one call and a tap answers at once. + * + * Deliberately not gated on `isStyleLoaded()`. That reports false for as long as any + * source has tiles or a setData in flight (see useDawarichTrailGL), which on a phone is + * the usual state, and the only retry here is `styledata`, which fires on style edits + * and not when those finish. Behind that gate a stored choice met a busy map on load, + * and a tap on the road trip stage met the sources the same render had just set again, + * so the imagery was never drawn. The gate was also the wrong question: this only runs + * after `load`, and addSource and addLayer refuse only a style document that is not in + * yet. The catch covers that case, and `styledata` brings the pass back once it is in. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function applySatellite(map: any, on: boolean): void { try { - if (!map.isStyleLoaded?.()) return + if (map.getLayer(SATELLITE_LAYER_ID)) { + map.setLayoutProperty(SATELLITE_LAYER_ID, 'visibility', on ? 'visible' : 'none') + return + } + if (!on) return // Nothing to build while it is switched off. + // The layer is what is missing, not necessarily the source: a pass that got the + // source in and then failed on the layer would otherwise leave a source that stops + // every later pass from ever building the layer. if (!map.getSource(SATELLITE_SOURCE_ID)) { - if (!on) return // Nothing to build while it is switched off. map.addSource(SATELLITE_SOURCE_ID, { type: 'raster', tiles: [SATELLITE_TILE_URL], @@ -293,21 +318,18 @@ function applySatellite(map: any, on: boolean): void { maxzoom: SATELLITE_TILE_MAXZOOM, attribution: SATELLITE_TILE_ATTRIBUTION, }) - // Under the first thing TREK draws, over everything the basemap style draws. - // Without the anchor the imagery lands on top and buries the route. - const layers = map.getStyle?.()?.layers ?? [] - const firstOwn = layers.find((l: { id: string }) => - OWN_LAYER_PREFIXES.some(prefix => l.id.startsWith(prefix))) - map.addLayer({ - id: SATELLITE_LAYER_ID, - type: 'raster', - source: SATELLITE_SOURCE_ID, - paint: { 'raster-opacity': 1 }, - }, firstOwn?.id) - } - if (map.getLayer(SATELLITE_LAYER_ID)) { - map.setLayoutProperty(SATELLITE_LAYER_ID, 'visibility', on ? 'visible' : 'none') } + // Under the first thing TREK draws, over everything the basemap style draws. + // Without the anchor the imagery lands on top and buries the route. + const layers = map.getStyle?.()?.layers ?? [] + const firstOwn = layers.find((l: { id: string }) => + OWN_LAYER_PREFIXES.some(prefix => l.id.startsWith(prefix))) + map.addLayer({ + id: SATELLITE_LAYER_ID, + type: 'raster', + source: SATELLITE_SOURCE_ID, + paint: { 'raster-opacity': 1 }, + }, firstOwn?.id) } catch { /* a style that refuses the layer keeps the plain basemap */ } } @@ -644,6 +666,7 @@ export function MapViewGL({ zoom = DEFAULT_MAP_ZOOM, fitKey = 0, focusPoints, + fitPadding, clusterLoosely = false, hazards, dawarichTrack = null, @@ -1170,6 +1193,23 @@ export function MapViewGL({ maxWidth: '240px', className: 'trek-map-popup', }) + /* + * The credit starts as the little (i), not as a ribbon across the map. + * + * Both engines collapse their attribution below 640px, and both then open it + * anyway and wait for a drag before tucking it away. On a phone, where the map IS + * the screen, that means the first thing anybody sees is a two-line grey band + * over the bottom of it. Dragging is exactly what maplibre does on its own + * `drag` handler; this only starts where that would have ended up, so the credit + * is one tap away and nothing about it is removed. + */ + map.once('idle', () => { + const attrib = containerRef.current?.querySelector('.maplibregl-ctrl-attrib.maplibregl-compact-show') + ?? containerRef.current?.querySelector('.mapboxgl-ctrl-attrib.mapboxgl-compact-show') + attrib?.classList.remove('maplibregl-compact-show', 'mapboxgl-compact-show') + attrib?.removeAttribute('open') + }) + // Hand the map out so the trip planner can render its own compass pill next to // the POI pill (a custom round control instead of Mapbox's default top-right one). onMapReadyRef.current?.(map) @@ -2177,6 +2217,10 @@ export function MapViewGL({ if (routeArrivedForPendingFit) pendingRouteFitRef.current = null }, [fitKey, routeFitKey]) // eslint-disable-line react-hooks/exhaustive-deps + // The caller's padding as a value, so a parent that builds the object inline on every + // render does not move the camera each time it renders. + const fitPaddingKey = fitPadding ? [fitPadding.top, fitPadding.right, fitPadding.bottom, fitPadding.left].join(' ') : '' + // Frame whatever was handed over. Nothing happens when it empties, so closing the // picker leaves the map where the user left it rather than snapping back. useEffect(() => { @@ -2188,13 +2232,13 @@ export function MapViewGL({ pendingRouteFitRef.current = null try { map.fitBounds(bounds, { - padding: paddingOpts, + padding: fitPadding ?? paddingOpts, maxZoom: 15, pitch: enableMapbox3d ? 45 : 0, duration: 400, }) } catch { /* noop */ } - }, [focusPoints]) // eslint-disable-line react-hooks/exhaustive-deps + }, [focusPoints, fitPaddingKey]) // eslint-disable-line react-hooks/exhaustive-deps // flyTo selected place useEffect(() => { @@ -2264,7 +2308,9 @@ export function MapViewGL({ // Satellite, the same setting the Leaflet map reads, so switching it on one renderer // and reloading into the other keeps the choice. `styledata` is subscribed because a - // basemap change rebuilds the style from scratch and takes the imagery with it. + // basemap change rebuilds the style from scratch and takes the imagery with it. It is + // the retry for a style that is not in yet, never for a busy one: it fires on style + // edits, not when tiles arrive, which is why applySatellite does not wait for those. useEffect(() => { const map = mapRef.current if (!map || !mapReady) return @@ -2314,7 +2360,7 @@ export function MapViewGL({ card too, and used to send the pill to the top of the map for a corner it never covers. */}
)} - {/* Stays Dawarich recorded on these dates, waiting to be reviewed (#2279). - Above the list because that is what they become, and the panel renders - nothing at all when there is nothing pending — an integration that is - connected and quiet should be invisible rather than a permanent empty - card. */} -
- days.map(day => ({ - id: day.id, - ...formatDayOption(day.day_number, day.date, locale, t), - }))} - // The place it just created belongs on the map and in the list - // now, not after a reload. - onAccepted={() => { void refreshTripAfterAccept(tripId) }} - initiallyCollapsed - /> -
- - {/* Liste */} - + {/* Liste, with the Dawarich stays riding on top of it inside the same scroller — + see the `header` prop for why they are not a band of their own. */} + + days.map(day => ({ + id: day.id, + ...formatDayOption(day.day_number, day.date, locale, t), + }))} + // The place it just created belongs on the map and in the list + // now, not after a reload. + onAccepted={() => { void refreshTripAfterAccept(tripId) }} + initiallyCollapsed + /> +
+ )} + /> {dayPickerPlace && } {listImportOpen && } diff --git a/client/src/components/Planner/PlacesSidebarList.tsx b/client/src/components/Planner/PlacesSidebarList.tsx index 1c0f60799..ccc1843ff 100644 --- a/client/src/components/Planner/PlacesSidebarList.tsx +++ b/client/src/components/Planner/PlacesSidebarList.tsx @@ -1,10 +1,21 @@ -import { Fragment } from 'react' +import { Fragment, type ReactNode } from 'react' import EmptyState from '../shared/EmptyState' import { MemoPlaceRow } from './PlacesSidebarRow' import type { SidebarState } from './usePlacesSidebar' import { usePluginViewContributions, PluginCardFooter } from '../Plugins/PluginContributions' -export function PlacesList(S: SidebarState) { +export function PlacesList({ header, ...S }: SidebarState & { + /** + * A block that sits above the places and scrolls WITH them. + * + * The Dawarich panel lives here rather than in a band of its own above the list. As its + * own band it could not grow: the list is the flex child that scrolls, so a panel with + * ten stays in it squeezed the list to nothing and took the rail's scrolling with it, + * and capping the panel left half its stays below a fold with no way to reach them. + * Inside the scroller it simply opens to its full height and the rail scrolls past it. + */ + header?: ReactNode +}) { const { filtered, scrollContainerRef, onScrollTopChange, filter, t, canEditPlaces, onAddPlace, categories, selectedPlaceId, plannedIds, inDaySet, selectedIds, selectMode, selectedDayId, @@ -14,6 +25,7 @@ export function PlacesList(S: SidebarState) { const contribFor = usePluginViewContributions('places', tripId) return (
onScrollTopChange?.((e.currentTarget as HTMLElement).scrollTop)}> + {header} {filtered.length === 0 ? ( /* The mascot and one line, the shape every other empty state in TREK has. The add link stays as the state's action: an empty list of places is diff --git a/client/src/components/Roadtrip/RoadtripAlternativesBar.tsx b/client/src/components/Roadtrip/RoadtripAlternativesBar.tsx index 7b9ce1473..02cb319be 100644 --- a/client/src/components/Roadtrip/RoadtripAlternativesBar.tsx +++ b/client/src/components/Roadtrip/RoadtripAlternativesBar.tsx @@ -4,9 +4,8 @@ import { useTranslation } from '../../i18n/TranslationContext' import { Tooltip } from '../shared/Tooltip' import { useSettingsStore } from '../../store/settingsStore' import { formatDistance } from '../../utils/units' -import { formatDurationShort } from './roadtripModel' import type { LegAlternatives } from './useRouteAlternatives' -import type { AlternativeOverlay } from './alternativeOverlays' +import { alternativesPhase, alternativeSubline, type AlternativeOverlay } from './alternativeOverlays' interface RoadtripAlternativesBarProps { open: LegAlternatives | null @@ -35,6 +34,7 @@ export default function RoadtripAlternativesBar({ const { t } = useTranslation() const distanceUnit = useSettingsStore(s => s.settings.distance_unit) if (!open) return null + const phase = alternativesPhase(open, overlays) return (
@@ -53,14 +53,14 @@ export default function RoadtripAlternativesBar({
- {open.loading ? ( + {phase === 'loading' ? (

{t('roadtrip.alt.loading')}

- ) : open.error ? ( + ) : phase === 'failed' ? (

{t('roadtrip.alt.failed')}

- ) : overlays.length < 2 ? ( + ) : phase === 'onlyOne' ? ( // One route back means there is genuinely only one sensible way to drive it.

{t('roadtrip.alt.onlyOne')}

) : ( @@ -88,9 +88,7 @@ export default function RoadtripAlternativesBar({ {formatDistance(alt.distance / 1000, distanceUnit)} - {alt.note - ? alt.note - : t('roadtrip.alt.slower', { time: formatDurationShort(alt.slowerThanQuickest) })} + {alternativeSubline(alt, time => t('roadtrip.alt.slower', { time }))} {/* Only where the drive time on the map came from the other engine. The diff --git a/client/src/components/Roadtrip/RoadtripCorridorPanel.test.tsx b/client/src/components/Roadtrip/RoadtripCorridorPanel.test.tsx index 840f2a623..fdf90b226 100644 --- a/client/src/components/Roadtrip/RoadtripCorridorPanel.test.tsx +++ b/client/src/components/Roadtrip/RoadtripCorridorPanel.test.tsx @@ -53,7 +53,7 @@ const day = (dayId: number, dayNumber: number): RoadtripDay => ({ const routes = (days: RoadtripDay[]): RoadtripRoutes => ({ days, - lines: [], lineDays: [], + lines: [], lineDays: [], lineJoins: [], accessLines: [], vias: [], segments: [], diff --git a/client/src/components/Roadtrip/RoadtripCorridorPanel.tsx b/client/src/components/Roadtrip/RoadtripCorridorPanel.tsx index dabd0fca5..505b5f82c 100644 --- a/client/src/components/Roadtrip/RoadtripCorridorPanel.tsx +++ b/client/src/components/Roadtrip/RoadtripCorridorPanel.tsx @@ -12,6 +12,7 @@ import { formatDistance } from '../../utils/units' import CustomSelect from '../shared/CustomSelect' import RoadtripCategoryPicker from './RoadtripCategoryPicker' import { serviceColor } from './roadtripModel' +import { alongLabel, offRouteLabel } from './corridorSearchModel' import { CORRIDOR_CATEGORY_BY_KEY } from './stopKinds' import { FS } from './typeScale' import { CORRIDOR_CATEGORY_KEYS, CORRIDOR_SECTION_KM, CORRIDOR_WIDTHS_KM, type RoadtripCorridor } from './useRoadtripCorridor' @@ -154,14 +155,11 @@ function ResultRow({ poi, onAdd, onFocus }: { poi: CorridorPoi; onAdd?: () => vo row still wraps cleanly at a narrow width because nothing has to break around a separator. */}
- - {t('roadtrip.poi.offRoute', { distance: formatDistance(poi.offRouteKm, distanceUnit) })} - - - {poi.alongKm < 0.5 - ? t('roadtrip.poi.atStart') - : t('roadtrip.poi.alongRoute', { distance: formatDistance(poi.alongKm, distanceUnit) })} - + {/* Written by the shared model rather than here: the phone says the same two + things in one line, and the wording of a hit should not depend on which + shell is reading it. */} + {offRouteLabel(poi.offRouteKm, distanceUnit, t)} + {alongLabel(poi.alongKm, distanceUnit, t)} {/* What the charger offers, where OSM says. Socket names are proper nouns and stay as they are; the numbers around them are what decides whether a car can use it at all. A station that says nothing shows nothing rather than a row @@ -455,7 +453,9 @@ export default function RoadtripCorridorPanel({
- {open && refuel.loading ? ( + {band.loading ? ( {t('roadtrip.refuel.looking')} ) : null} - {settled ? ( - refuel.results.length ? ( + {band.offers.length ? (
    {/* Three at most. This is an offer beside a plan, not a list to browse; the corridor panel is where somebody goes to see all of them. @@ -569,7 +566,7 @@ function RefuelBand({ dry, refuel, dayId, onAsk, onAccept }: { not enough to tell them apart — measured on a real day the top three came back as "Vattenfall InCharge" three times over, identical but for a number nobody could see the meaning of. */} - {refuel.results.slice(0, 3).map(poi => { + {band.offers.map(poi => { const kind = STOP_KIND_BY_KEY[poi.category] const KindIcon = kind?.Icon ?? Fuel return ( @@ -632,11 +629,11 @@ function RefuelBand({ dry, refuel, dayId, onAsk, onAccept }: { {onAccept ? ( - +
- ) : ( - /* Three different sentences for three different facts. "Nothing on this - stretch" after a request that failed or was cut short states something - that was never checked, which is worse than saying nothing. */ - - {refuel.outcome === 'none' - ? t('roadtrip.refuel.none') - : refuel.outcome === 'incomplete' - ? t('roadtrip.refuel.incomplete') - : t('roadtrip.refuel.failed')} - - ) + ) : null} + + {/* Three different sentences for three different facts. "Nothing on this + stretch" after a request that failed or was cut short states something + that was never checked, which is worse than saying nothing. */} + {band.empty ? ( + + {t(REFUEL_EMPTY_KEY[band.empty])} + ) : null}
@@ -1423,7 +1417,7 @@ function DaySection({ day, selectedAssignmentId, onSelectStop, onReorderStop, on {i < last && (!day.stops[i + 1].automaticNight || day.legs[i]?.distance !== 0) ? ( onAskAlternatives(day.dayId, i) : undefined} + onAskAlternatives={onAskAlternatives && legReroutable(day, i) ? () => onAskAlternatives(day.dayId, i) : undefined} alternativesOpen={openAlternatives?.dayId === day.dayId && openAlternatives.index === i} /> ) : null} diff --git a/client/src/components/Roadtrip/alternativeOverlays.test.ts b/client/src/components/Roadtrip/alternativeOverlays.test.ts index 3a2a78a44..18bb4cc70 100644 --- a/client/src/components/Roadtrip/alternativeOverlays.test.ts +++ b/client/src/components/Roadtrip/alternativeOverlays.test.ts @@ -1,10 +1,11 @@ import { describe, it, expect } from 'vitest' -import { buildAlternativeOverlays } from './alternativeOverlays' +import { alternativeSubline, alternativesPhase, buildAlternativeOverlays, type AlternativeOverlay } from './alternativeOverlays' +import { formatDurationShort } from './roadtripModel' import { ALT_PRIMARY, ALT_SECONDARY, ALT_LABEL_PRIMARY_BG, ALT_LABEL_SECONDARY_BG } from './alternativeColors' import type { RouteAlternative } from '../Map/RouteCalculator' /** - * FE-ALTOVL-001..010 — turning the router's answers into something drawable. + * FE-ALTOVL-001..017: turning the router's answers into something drawable. * * Two decisions live here and neither is cosmetic: which of the offered roads is * drawn as the one you are on, and where each label hangs. A label anchored on a @@ -221,3 +222,36 @@ describe('buildAlternativeOverlays', () => { expect(out[1].color).toBe(ALT_SECONDARY) }) }) + +describe('alternativesPhase', () => { + const two = buildAlternativeOverlays([alt({ coordinates: line(20, 0) }), alt({ coordinates: line(20, 1) })], LABELS) + + it('FE-ALTOVL-016: asking beats a failure, a failure beats an empty list, and only two roads are a choice', () => { + // A new question replaces the old answer and its error with it. + expect(alternativesPhase({ loading: true, error: true }, two)).toBe('loading') + expect(alternativesPhase({ loading: true, error: false }, [])).toBe('loading') + // A router that will not answer is not a leg with one sensible way. + expect(alternativesPhase({ loading: false, error: true }, [])).toBe('failed') + expect(alternativesPhase({ loading: false, error: true }, two)).toBe('failed') + expect(alternativesPhase({ loading: false, error: false }, [])).toBe('onlyOne') + expect(alternativesPhase({ loading: false, error: false }, two.slice(0, 1))).toBe('onlyOne') + expect(alternativesPhase({ loading: false, error: false }, two)).toBe('choose') + }) +}) + +describe('alternativeSubline', () => { + const overlay = (over: Partial): AlternativeOverlay => ({ + ...buildAlternativeOverlays([alt({ coordinates: line(20, 0) }), alt({ coordinates: line(20, 1) })], LABELS)[1], + ...over, + }) + + it('FE-ALTOVL-017: an offer is named by what it is, and only a plain one by how much slower it is', () => { + const slower = (time: string) => `${time} slower` + for (const note of ['No motorway', 'Current', 'Fastest']) { + expect(alternativeSubline(overlay({ note, slowerThanQuickest: 1800 }), slower)).toBe(note) + } + // The caller words the difference; the figure is the same short duration the map prints. + expect(alternativeSubline(overlay({ note: '', slowerThanQuickest: 1800 }), slower)) + .toBe(`${formatDurationShort(1800)} slower`) + }) +}) diff --git a/client/src/components/Roadtrip/alternativeOverlays.ts b/client/src/components/Roadtrip/alternativeOverlays.ts index 5171a99ab..8f03e5530 100644 --- a/client/src/components/Roadtrip/alternativeOverlays.ts +++ b/client/src/components/Roadtrip/alternativeOverlays.ts @@ -1,6 +1,7 @@ import { formatDurationShort } from './roadtripModel' import { ALT_PRIMARY, ALT_SECONDARY, ALT_LABEL_PRIMARY_BG, ALT_LABEL_SECONDARY_BG } from './alternativeColors' import type { RouteAlternative } from '../Map/RouteCalculator' +import type { LegAlternatives } from './useRouteAlternatives' /** One offered route, ready to draw: the line, its colour, and where its label sits. */ export interface AlternativeOverlay { @@ -154,3 +155,39 @@ export function buildAlternativeOverlays( } }) } + +/** What a picker has to say about one leg, whichever shell draws it. */ +export type AlternativesPhase = 'loading' | 'failed' | 'onlyOne' | 'choose' + +/** + * Which of its four states a picker is in. + * + * Both bars branch on this, so the desk and the phone cannot disagree about when a leg has + * a choice. Asking wins over a failure, because a new question replaces the old answer + * and its error with it. A failure wins over an empty list, so a router that will not + * answer is never read as a leg with only one sensible way. Fewer than two overlays is + * that single way: `buildAlternativeOverlays` draws nothing for one answer, and one road + * is not a choice. + */ +export function alternativesPhase( + open: Pick, + overlays: readonly AlternativeOverlay[], +): AlternativesPhase { + if (open.loading) return 'loading' + if (open.error) return 'failed' + return overlays.length < 2 ? 'onlyOne' : 'choose' +} + +/** + * The second line an offer is listed with: what this way is, or else how much slower. + * + * Its own note wins, for the reason the note exists: a road offered because the motorway + * was left out of it is taken for that, not for its minutes. Without one the line is the + * difference to the quickest, worded by the caller (a translation this module stays free + * of). The desk bar's docstring tells what two copies of one figure once did, the driven + * road called "Fastest" beside an offer called quicker, so both bars read this line here + * instead of each keeping its own. + */ +export function alternativeSubline(alt: AlternativeOverlay, slower: (time: string) => string): string { + return alt.note || slower(formatDurationShort(alt.slowerThanQuickest)) +} diff --git a/client/src/components/Roadtrip/corridorSearchModel.test.ts b/client/src/components/Roadtrip/corridorSearchModel.test.ts new file mode 100644 index 000000000..5e28d91be --- /dev/null +++ b/client/src/components/Roadtrip/corridorSearchModel.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, it } from 'vitest' +import { + alongLabel, + anchorKmFor, + corridorHitLabel, + corridorWindow, + DESKTOP_CORRIDOR_BUDGET, + offRouteLabel, + PHONE_CORRIDOR_BUDGET, + PHONE_CORRIDOR_OPTIONS, + PHONE_REACH_KM, +} from './corridorSearchModel' +import type { TranslationFn } from '../../types' + +// FE-ROADTRIP-CORWIN-001 to FE-ROADTRIP-CORWIN-012 + +/** Echoes the key and its parameters, so assertions stay off the copy. */ +const t: TranslationFn = (key, params) => + params ? `${key}:${Object.values(params).join(',')}` : key + +describe('corridorWindow', () => { + it('FE-ROADTRIP-CORWIN-001: a stage search has no window, which is the whole day', () => { + expect(corridorWindow(120, 'stage')).toBeNull() + }) + + it('FE-ROADTRIP-CORWIN-002: an ahead search starts at the anchor and runs one reach', () => { + expect(corridorWindow(120, 'ahead')).toEqual({ fromKm: 120, toKm: 120 + PHONE_REACH_KM }) + }) + + it('FE-ROADTRIP-CORWIN-003: never starts behind the beginning of the drive', () => { + // A negative anchor cannot come from `anchorKmFor`, but a window that started at + // -20 would ask the slicer for road that does not exist. + expect(corridorWindow(-20, 'ahead')).toEqual({ fromKm: 0, toKm: PHONE_REACH_KM }) + }) + + it('FE-ROADTRIP-CORWIN-004: takes a reach of its own, so the figure is not baked in', () => { + expect(corridorWindow(10, 'ahead', 25)).toEqual({ fromKm: 10, toKm: 35 }) + }) +}) + +describe('anchorKmFor', () => { + const stops = [0, 40, 95, 180] + + it('FE-ROADTRIP-CORWIN-005: without a next stop it is the start of the stage', () => { + // No position source and no clock reading: the honest answer is the beginning of + // the day, not a guess dressed up as a location. + expect(anchorKmFor(stops, null)).toBe(0) + }) + + it('FE-ROADTRIP-CORWIN-006: the first stop is also the start, not a step back', () => { + expect(anchorKmFor(stops, 0)).toBe(0) + }) + + it('FE-ROADTRIP-CORWIN-007: otherwise it is the stop already behind the traveller', () => { + // Heading for the third stop means the second is behind: that is where the road + // still to drive begins. + expect(anchorKmFor(stops, 2)).toBe(40) + }) + + it('FE-ROADTRIP-CORWIN-008: an index the stop list cannot answer falls back to the start', () => { + expect(anchorKmFor(stops, 99)).toBe(0) + expect(anchorKmFor([0, Number.NaN, 95], 2)).toBe(0) + }) +}) + +describe('the labels a hit carries', () => { + it('FE-ROADTRIP-CORWIN-009: anything under half a kilometre in is "at the start"', () => { + expect(alongLabel(0.2, 'metric', t)).toBe('roadtrip.poi.atStart') + expect(alongLabel(0.5, 'metric', t)).toBe('roadtrip.poi.alongRoute:500 m') + }) + + it('FE-ROADTRIP-CORWIN-010: the detour is stated in the trip’s own unit', () => { + expect(offRouteLabel(1.5, 'metric', t)).toBe('roadtrip.poi.offRoute:1.5 km') + expect(offRouteLabel(1.5, 'imperial', t)).toBe('roadtrip.poi.offRoute:0.9 mi') + }) + + it('FE-ROADTRIP-CORWIN-011: the phone joins both into the one line a row has room for', () => { + expect(corridorHitLabel({ alongKm: 82, offRouteKm: 0.4 }, 'metric', t)) + .toBe('roadtrip.poi.alongRoute:82 km · roadtrip.poi.offRoute:400 m') + }) +}) + +describe('the budgets', () => { + it('FE-ROADTRIP-CORWIN-012: the desk keeps its old behaviour, the phone is capped', () => { + // The desktop budget IS today's behaviour written down: no deadline, every failed + // box retried. Loosening the phone's numbers is a product decision, not a tidy-up, + // so they are pinned. + expect(DESKTOP_CORRIDOR_BUDGET).toEqual({ maxTiles: 16, maxRetries: null, deadlineMs: null }) + expect(PHONE_CORRIDOR_BUDGET).toEqual({ maxTiles: 10, maxRetries: 2, deadlineMs: 25_000 }) + // Handed down by identity so the search callback underneath is not rebuilt. + expect(PHONE_CORRIDOR_OPTIONS.budget).toBe(PHONE_CORRIDOR_BUDGET) + }) +}) diff --git a/client/src/components/Roadtrip/corridorSearchModel.ts b/client/src/components/Roadtrip/corridorSearchModel.ts new file mode 100644 index 000000000..024e1bab4 --- /dev/null +++ b/client/src/components/Roadtrip/corridorSearchModel.ts @@ -0,0 +1,117 @@ +import { formatDistance } from '../../utils/units' +import type { CorridorPoi, CorridorWindow } from './useCorridorPois' +import type { DistanceUnit } from '@trek/shared/roadtrip' +import type { TranslationFn } from '../../types' + +/** + * What a corridor search is allowed to cost, and how far along the drive it looks. + * + * The search is already scoped to one day. What it is NOT scoped to is a stretch of + * that day, and that is where the money is: at roughly one request per 20km of driving, + * a 300km day is 15 boxes, while the 50km ahead of the driver is three. A phone in a + * cell is not a desk, so it asks for the stretch it is about to drive and offers the + * whole stage as the second tap. + * + * Deliberately NOT narrowed: the categories. They all travel in one comma-separated + * query per box, so a second category costs zero extra requests. Restricting the phone + * to one at a time would have made three searches out of one, which is three times the + * traffic for less choice. + */ +export interface CorridorBudget { + /** Boxes one search may ask for. Past this it stops and says so. */ + maxTiles: number + /** Boxes the follow-up pass may retry, or null for all of them (the desktop's way). */ + maxRetries: number | null + /** No new box is started after this, or null for no limit. */ + deadlineMs: number | null +} + +/** Unchanged behaviour: this is what the panel has always done. */ +export const DESKTOP_CORRIDOR_BUDGET: CorridorBudget = { + maxTiles: 16, + maxRetries: null, + deadlineMs: null, +} + +/** + * The phone's ceiling. + * + * `deadlineMs` exists only here, and it answers a conflict the desktop lives with: the + * client gives a box 20 seconds, the server's Overpass fallback allows itself 25. A slow + * box therefore always times out on the client first and gets retried while the first + * attempt is still running. On a phone that is the difference between a search that + * ends and one that keeps the radio warm. + */ +export const PHONE_CORRIDOR_BUDGET: CorridorBudget = { + maxTiles: 10, + maxRetries: 2, + deadlineMs: 25_000, +} + +/** Passed by identity, so the search callback below it is not rebuilt every render. */ +export const PHONE_CORRIDOR_OPTIONS = { budget: PHONE_CORRIDOR_BUDGET } + +/** How far ahead "ahead" means, in kilometres of driving. */ +export const PHONE_REACH_KM = 50 + +export type CorridorReach = 'ahead' | 'stage' + +/** + * The stretch of the drive a search covers, in kilometres along the day's line. + * + * Null means the whole stage, which is what the caller passes straight through to the + * existing behaviour. The window is applied to the tile line only: the spine keeps its + * full length, so `alongKm`, `offRouteKm` and the insert position of a hit stay measured + * against the day rather than against the window. + */ +export function corridorWindow( + anchorKm: number, + reach: CorridorReach, + reachKm: number = PHONE_REACH_KM, +): CorridorWindow | null { + if (reach === 'stage') return null + const from = Math.max(0, anchorKm) + return { fromKm: from, toKm: from + reachKm } +} + +/** + * Where "ahead" starts. + * + * The stop the traveller is heading for, measured in kilometres along the day. Without + * one (a stage that is not today, or a day already driven) it is the start of the stage, + * which is the honest answer: there is no position source, and a guess dressed up as a + * location is worse than the beginning of the day. + */ +export function anchorKmFor(stopsAlongKm: readonly number[], upNextIndex: number | null): number { + if (upNextIndex == null || upNextIndex <= 0) return 0 + const previous = stopsAlongKm[upNextIndex - 1] + return Number.isFinite(previous) ? Math.max(0, previous as number) : 0 +} + +/** + * How far into the drive a hit sits. + * + * Shared with the desktop panel rather than written twice. The two shells already mirror + * each other closely and the duplication budget is three percent of new code, so the + * phrases that describe a hit are written once and read in both: the desktop puts them + * in two chips, the phone joins them into one line, and neither owns the wording. + */ +export function alongLabel(alongKm: number, unit: DistanceUnit, t: TranslationFn): string { + return alongKm < 0.5 + ? t('roadtrip.poi.atStart') + : t('roadtrip.poi.alongRoute', { distance: formatDistance(alongKm, unit) }) +} + +/** How far off the road it sits. */ +export function offRouteLabel(offRouteKm: number, unit: DistanceUnit, t: TranslationFn): string { + return t('roadtrip.poi.offRoute', { distance: formatDistance(offRouteKm, unit) }) +} + +/** Both of them, as the one line a phone row has room for. */ +export function corridorHitLabel( + poi: Pick, + unit: DistanceUnit, + t: TranslationFn, +): string { + return `${alongLabel(poi.alongKm, unit, t)} · ${offRouteLabel(poi.offRouteKm, unit, t)}` +} diff --git a/client/src/components/Roadtrip/refuelSuggestion.test.ts b/client/src/components/Roadtrip/refuelSuggestion.test.ts index 886518769..d4a7769d8 100644 --- a/client/src/components/Roadtrip/refuelSuggestion.test.ts +++ b/client/src/components/Roadtrip/refuelSuggestion.test.ts @@ -1,5 +1,8 @@ import { describe, it, expect } from 'vitest' -import { reachableRefuels, outcomeOf } from './refuelSuggestion' +import { + reachableRefuels, outcomeOf, refuelBandState, refuelKey, REFUEL_EMPTY_KEY, REFUEL_OFFER_LIMIT, REFUEL_WORDS, + type RefuelCandidate, type RefuelOutcome, type RefuelSearchView, +} from './refuelSuggestion' import type { LatLng } from './corridor' import type { Poi } from '../Map/poiCategories' @@ -122,3 +125,67 @@ describe('reachableRefuels — one entry per station', () => { expect(out.map(p => p.name).sort()).toEqual(['Aral', 'Shell']) }) }) + +describe('refuelBandState', () => { + const candidate = (name: string): RefuelCandidate => + ({ ...poi(name, 52, 13.5), alongKm: 40, offRouteKm: 0.4, spareKm: 30 }) + const search = (over: Partial = {}): RefuelSearchView => + ({ openFor: null, loading: false, outcome: null, results: [], ...over }) + + it('FE-ROADTRIP-REFUEL-013: a search filed under another leg leaves this band alone', () => { + // One search is open at a time and it names the dry point it belongs to, so a band + // three legs down the chain must not light up for a question asked about this one. + expect(refuelKey(7, 1)).toBe('7:1') + const band = refuelBandState(search({ openFor: '7:4', outcome: 'found', results: [candidate('a')] }), 7, 1) + expect(band).toEqual({ open: false, loading: false, offers: [], empty: null, control: 'find' }) + }) + + it('FE-ROADTRIP-REFUEL-014: while the request runs the lamp steps aside for the way out', () => { + const band = refuelBandState(search({ openFor: '7:1', loading: true }), 7, 1) + expect(band).toEqual({ open: true, loading: true, offers: [], empty: null, control: 'close' }) + }) + + it('FE-ROADTRIP-REFUEL-015: an answer lists three at most, in the order the search ranked them', () => { + const results = ['a', 'b', 'c', 'd', 'e'].map(candidate) + const band = refuelBandState(search({ openFor: '7:1', outcome: 'found', results }), 7, 1) + expect(REFUEL_OFFER_LIMIT).toBe(3) + expect(band.offers.map(o => o.name)).toEqual(['a', 'b', 'c']) + expect(band.control).toBe('close') + expect(band.empty).toBeNull() + }) + + it.each>(['none', 'incomplete', 'failed'])( + 'FE-ROADTRIP-REFUEL-016: an empty answer (%s) says which nothing it was and leaves a retry', + outcome => { + // A retry rather than a dead end: the place search is a shared service that does + // time out, and no answer with no way to ask again reads as broken. + const band = refuelBandState(search({ openFor: '7:1', outcome }), 7, 1) + expect(band).toEqual({ open: true, loading: false, offers: [], empty: outcome, control: 'again' }) + expect(REFUEL_EMPTY_KEY[outcome]).toBe(`roadtrip.refuel.${outcome}`) + }, + ) + + it('FE-ROADTRIP-REFUEL-017: asked but nothing back yet keeps the lamp and says nothing', () => { + const band = refuelBandState(search({ openFor: '7:1' }), 7, 1) + expect(band).toEqual({ open: true, loading: false, offers: [], empty: null, control: 'find' }) + }) + + it('FE-ROADTRIP-REFUEL-018: the battery never borrows the tank\'s words', () => { + expect(REFUEL_WORDS.fuel).toEqual({ + dry: 'roadtrip.refuel.dry', find: 'roadtrip.refuel.find', add: 'roadtrip.refuel.add', + }) + expect(REFUEL_WORDS.electric).toEqual({ + dry: 'roadtrip.refuel.dryElectric', find: 'roadtrip.refuel.findElectric', add: 'roadtrip.refuel.addElectric', + }) + }) + + it('FE-ROADTRIP-REFUEL-019: results that arrive before their outcome already offer the way out', () => { + // The close control follows the results rather than the outcome, which is how the + // desktop rail always decided it: once there is something on the map to dismiss, + // the band offers to dismiss it. + const band = refuelBandState(search({ openFor: '7:1', results: [candidate('a')] }), 7, 1) + expect(band.control).toBe('close') + expect(band.offers).toEqual([]) + expect(band.empty).toBeNull() + }) +}) diff --git a/client/src/components/Roadtrip/refuelSuggestion.ts b/client/src/components/Roadtrip/refuelSuggestion.ts index 9daf24b80..0a9d548e6 100644 --- a/client/src/components/Roadtrip/refuelSuggestion.ts +++ b/client/src/components/Roadtrip/refuelSuggestion.ts @@ -121,3 +121,103 @@ function oneEach(sorted: RefuelCandidate[]): RefuelCandidate[] { } return kept } + +/** + * How many answers a band lists, on the desktop rail and on the phone alike. + * + * Three at most. This is an offer beside a plan, not a list to browse; the corridor + * search is where somebody goes to see all of them. Named once so the two bands can never + * disagree about what "the offers" are. + */ +export const REFUEL_OFFER_LIMIT = 3 + +/** + * The name a search is filed under: the card day the band is drawn on and the leg. + * + * One search is open at a time and it names the dry point it belongs to, so a band three + * legs down the chain does not light up for a question asked about this one. The card + * day rather than the day a borrowed stop is stored on, because the answer has to arrive + * under a key the band that asked is watching. + */ +export function refuelKey(dayId: number, legIndex: number): string { + return `${dayId}:${legIndex}` +} + +/** What sits in the band's trailing slot: the lamp that goes looking, a retry, or a close. */ +export type RefuelControl = 'find' | 'again' | 'close' + +/** + * The part of the search a band reads. + * + * Structural rather than the hook's own type, because useRefuelSearch.ts imports this + * module and the pure half should not have to know about the half with the network in it. + */ +export interface RefuelSearchView { + openFor: string | null + loading: boolean + outcome: RefuelOutcome | null + results: readonly RefuelCandidate[] +} + +/** Everything a band shows that is not markup, decided once for both shells. */ +export interface RefuelBandState { + /** The open search belongs to this band. */ + open: boolean + /** This band's question is out and has not come back yet. */ + loading: boolean + /** The answers to list, already capped at REFUEL_OFFER_LIMIT; empty until there are some. */ + offers: RefuelCandidate[] + /** Which kind of nothing came back, or null while there is no empty answer to report. */ + empty: Exclude | null + /** What fills the trailing slot; `refuelBandState` says why each one wins when it does. */ + control: RefuelControl +} + +/** + * The state of one dry band, given the one search that may be open. + * + * The lamp steps aside while a request runs or offers are showing, for the way to close + * the answer: every press is a real request against a shared service, and a lamp still + * standing there invites a second one nobody asked for. An answer that found nothing + * leaves a retry rather than a dead end, because the place search is a public service + * that does time out, and "it did not answer" with no way to ask again reads as broken + * rather than as busy. + * + * The empty answer keeps three different sentences for three different facts. "Nothing + * on this stretch" after a request that failed or was cut short states something that was + * never checked, which is worse than saying nothing, so anything that is not a plain + * `none` or `incomplete` reads as `failed`. + */ +export function refuelBandState(search: RefuelSearchView, dayId: number, legIndex: number): RefuelBandState { + const open = search.openFor === refuelKey(dayId, legIndex) + const loading = open && search.loading + const settled = open && !search.loading && search.outcome != null + const offers = settled && search.results.length > 0 ? search.results.slice(0, REFUEL_OFFER_LIMIT) : [] + let empty: RefuelBandState['empty'] = null + if (settled && offers.length === 0) { + empty = search.outcome === 'none' || search.outcome === 'incomplete' ? search.outcome : 'failed' + } + let control: RefuelControl = 'find' + if (loading || (open && search.results.length > 0)) control = 'close' + else if (settled && search.outcome !== 'found') control = 'again' + return { open, loading, offers, empty, control } +} + +/** Which sentence each kind of empty answer gets. */ +export const REFUEL_EMPTY_KEY: Record, string> = { + none: 'roadtrip.refuel.none', + incomplete: 'roadtrip.refuel.incomplete', + failed: 'roadtrip.refuel.failed', +} + +/** + * The band's words for a tank and for a battery. + * + * An electric car does not run out of TANK, and a battery band that talks about fuel is + * the kind of detail that makes the rest look careless. Kept as one table so the title, + * the lamp's label and the offer's label never mix the two vocabularies. + */ +export const REFUEL_WORDS = { + fuel: { dry: 'roadtrip.refuel.dry', find: 'roadtrip.refuel.find', add: 'roadtrip.refuel.add' }, + electric: { dry: 'roadtrip.refuel.dryElectric', find: 'roadtrip.refuel.findElectric', add: 'roadtrip.refuel.addElectric' }, +} as const diff --git a/client/src/components/Roadtrip/roadtripRowModel.test.ts b/client/src/components/Roadtrip/roadtripRowModel.test.ts new file mode 100644 index 000000000..c254ccfcd --- /dev/null +++ b/client/src/components/Roadtrip/roadtripRowModel.test.ts @@ -0,0 +1,505 @@ +import { describe, expect, it } from 'vitest' +import { + destinationCount, + firstStopOfPlace, + legReroutable, + pickWarning, + roadtripRows, + stageClocks, + stageEnd, + stageOf, + upNextStop, + type RoadtripRow, + type StopRow, +} from './roadtripRowModel' +import type { ScheduleEntry, ScheduleWarning } from './roadtripModel' +import type { RoadtripDay, RoadtripStop, RouteSegment } from '@trek/shared/roadtrip' + +// FE-RTROW-001 to FE-RTROW-039 + +function stop(name: string, over: Partial = {}): RoadtripStop { + return { + assignmentId: name.length, + ownerDayId: 7, + ownerIndex: 0, + placeId: 100, + name, + lat: 48.1, + lng: 11.2, + time: null, + dwellMinutes: null, + legMode: null, + incomingLegMode: null, + stopType: null, + ...over, + } +} + +function entry(arrival: string | null, over: Partial = {}): ScheduleEntry { + return { arrival, departure: arrival, anchored: false, dayOffset: 0, ...over } +} + +function seg(index: number): RouteSegment { + return { + mid: [48, 11], + from: [48, 11], + to: [49, 12], + distance: 1000 * (index + 1), + duration: 600, + walkingText: '2 h', + drivingText: '10 min', + distanceText: `${index + 1} km`, + } +} + +function day(stops: RoadtripStop[], over: Partial = {}): RoadtripDay { + return { + dayId: 7, + dayNumber: 1, + date: '2026-06-01', + title: null, + stops, + legs: stops.slice(0, -1).map((_, i) => seg(i)), + schedule: { entries: stops.map(() => entry(null)), warnings: [] }, + legVias: [], + geometry: [], + distance: 0, + duration: 0, + driveWarnings: [], + dayWarning: null, + ...over, + } +} + +const night = (phase: 'start' | 'end' = 'end') => + stop('Nacht', { automaticNight: { phase, fromDayNumber: 1 }, dwellMinutes: 480 }) + +const stopRows = (rows: RoadtripRow[]) => rows.filter((r): r is StopRow => r.kind === 'stop') + +/** Ziel, Tankstelle, Ziel, automatische Nacht, Ziel. */ +const mixedDay = () => + day([stop('Bremen'), stop('Aral', { stopType: 'fuel' }), stop('Kassel'), night(), stop('Fulda')]) + +describe('roadtripRows numbering', () => { + it('FE-RTROW-001: only destinations take a number, a service stop and a night do not advance it', () => { + // Nummerierung ueber den Array-Index machte aus Kassel die drei und aus Fulda die fuenf. + const numbers = stopRows(roadtripRows(mixedDay())).map((r) => [r.stop.name, r.number]) + expect(numbers).toEqual([ + ['Bremen', 1], + ['Aral', null], + ['Kassel', 2], + ['Fulda', 3], + ]) + }) + + it('FE-RTROW-002: the service stop is a stop row, the automatic night is not', () => { + const rows = roadtripRows(mixedDay()) + expect(rows.map((r) => r.kind)).toEqual(['stop', 'leg', 'stop', 'leg', 'stop', 'leg', 'auto', 'leg', 'stop']) + expect(stopRows(rows).map((r) => r.stop.name)).not.toContain('Nacht') + }) + + it('FE-RTROW-040: the placeholder leg into an automatic night is not a row at all', () => { + // `dayWindow.stationary()` puts one of these between the last stop of a day and the + // night that closes it: same coordinate at both ends, nothing measured. It is + // bookkeeping, not a drive, and as a pill it read "No route" under a stop the + // traveller had simply arrived at (and, before that was guarded, a bare " in "). + const stops = [stop('Hamburg'), night()] + const at: [number, number] = [53.54, 10.01] + const stationary: RouteSegment = { + mid: at, from: at, to: at, distance: 0, duration: 0, + walkingText: '', drivingText: '', distanceText: '', + } + const rows = roadtripRows(day(stops, { legs: [stationary] })) + + expect(rows.map((r) => r.kind)).toEqual(['stop', 'auto']) + }) + + it('FE-RTROW-041: a night the traveller drove to keeps its leg', () => { + // A boundary dragged down the road ends the day somewhere else, and that IS a drive. + const stops = [stop('Hamburg'), night()] + const rows = roadtripRows(day(stops, { legs: [seg(0)] })) + + expect(rows.map((r) => r.kind)).toEqual(['stop', 'leg', 'auto']) + }) + + it('FE-RTROW-042: a leg nothing has routed yet still gets its row, so it can say it is pending', () => { + const stops = [stop('Hamburg'), stop('Bremen')] + const rows = roadtripRows(day(stops, { legs: [undefined] })) + + expect(rows.map((r) => r.kind)).toEqual(['stop', 'leg', 'stop']) + }) + + it('FE-RTROW-003: the automatic night carries no dwell and takes its time from the schedule', () => { + // Die Nacht traegt dwellMinutes 480, aber keine Zeile, die eine Aufenthaltsdauer zeigen koennte. + const rows = roadtripRows( + day([stop('Kassel'), night(), stop('Fulda')], { + schedule: { entries: [entry('18:00'), entry('22:30'), entry('09:15')], warnings: [] }, + }), + ) + expect(rows.find((r) => r.kind === 'auto')).toEqual({ kind: 'auto', phase: 'end', time: '22:30' }) + expect(JSON.stringify(rows)).not.toContain('480') + }) + + it('FE-RTROW-004: a night that starts a day resumes it, anything else ends it', () => { + expect(roadtripRows(day([night('start'), stop('Fulda')])).find((r) => r.kind === 'auto')).toMatchObject({ + phase: 'resume', + }) + expect(roadtripRows(day([night('end'), stop('Fulda')])).find((r) => r.kind === 'auto')).toMatchObject({ + phase: 'end', + }) + }) + + it('FE-RTROW-005: exactly one leg between two stops and none after the last', () => { + const rows = roadtripRows(day([stop('A'), stop('B'), stop('C')])) + expect(rows.filter((r) => r.kind === 'leg')).toEqual([ + { kind: 'leg', index: 0, seg: seg(0), mode: null }, + { kind: 'leg', index: 1, seg: seg(1), mode: null }, + ]) + expect(rows[rows.length - 1].kind).toBe('stop') + }) + + it('FE-RTROW-006: a leg is driven in the next stop incoming mode, else in this one own', () => { + const rows = roadtripRows( + day([ + stop('A', { legMode: 'car' }), + stop('B', { incomingLegMode: 'ferry', legMode: 'train' }), + stop('C'), + stop('D'), + ]), + ) + const modes = rows.flatMap((r) => (r.kind === 'leg' ? [r.mode] : [])) + expect(modes).toEqual(['ferry', 'train', null]) + }) +}) + +describe('roadtripRows dry points and spills', () => { + it('FE-RTROW-007: a dry point makes one row, directly after the leg it falls on', () => { + const rows = roadtripRows( + day([stop('A'), stop('B'), stop('C')], { + dryPoints: [{ legIndex: 1, intoLegKm: 42, sinceKm: 610, drivenMeters: 42000, lat: 48, lng: 11 }], + }), + ) + expect(rows.map((r) => r.kind)).toEqual(['stop', 'leg', 'stop', 'leg', 'dry', 'stop']) + expect(rows[4]).toEqual({ kind: 'dry', legIndex: 1, intoLegKm: 42, sinceKm: 610 }) + }) + + it('FE-RTROW-008: a dry point past the last leg is not drawn', () => { + // Nach dem letzten Stopp gibt es kein Bein, an dem die Warnung haengen koennte. + const rows = roadtripRows( + day([stop('A'), stop('B')], { + dryPoints: [{ legIndex: 1, intoLegKm: 5, sinceKm: 600, drivenMeters: 5000, lat: 48, lng: 11 }], + }), + ) + expect(rows.some((r) => r.kind === 'dry')).toBe(false) + }) + + it('FE-RTROW-009: a spill sits before the stop it hangs on, with the day it came from', () => { + const rows = roadtripRows( + day([stop('A'), stop('B')], { + spills: [ + { at: 1, count: 1, fromDayNumber: 3, departure: '23:40', leg: undefined, fromStop: undefined, line: [] }, + ], + }), + ) + expect(rows.map((r) => r.kind)).toEqual(['stop', 'leg', 'spill', 'stop']) + expect(rows[2]).toEqual({ kind: 'spill', fromDayNumber: 3, departs: '23:40', stops: [] }) + }) +}) + +describe('roadtripRows stop detail', () => { + it('FE-RTROW-010: the clock and the pin come from the schedule entry', () => { + const rows = stopRows( + roadtripRows( + day([stop('A'), stop('B'), stop('C')], { + schedule: { + entries: [entry('08:00'), entry('09:40', { departure: '10:10', anchored: true }), entry(null)], + warnings: [], + }, + }), + ), + ) + expect(rows.map((r) => [r.time, r.pinned])).toEqual([ + ['08:00', false], + ['09:40', true], + [null, false], + ]) + expect(rows[1].entry?.departure).toBe('10:10') + }) + + it('FE-RTROW-011: a stop shows only its own findings, and only the strongest of them', () => { + const rows = stopRows( + roadtripRows( + day([stop('A'), stop('B')], { + driveWarnings: [ + { index: 0, code: 'overnight' }, + { index: 1, code: 'leg', overMinutes: 20 }, + { index: 1, code: 'late', minutes: 15 }, + ], + }), + ), + ) + expect(rows[0].warning).toEqual({ index: 0, code: 'overnight' }) + expect(rows[1].warning).toEqual({ index: 1, code: 'late', minutes: 15 }) + }) + + it('FE-RTROW-012: dwell and the walk in from the road pass through, absent means null', () => { + const rows = stopRows(roadtripRows(day([stop('A', { dwellMinutes: 90, offRoadMeters: 240 }), stop('B')]))) + expect([rows[0].dwellMinutes, rows[0].offRoadMeters]).toEqual([90, 240]) + expect([rows[1].dwellMinutes, rows[1].offRoadMeters]).toEqual([null, null]) + }) +}) + +describe('pickWarning', () => { + it('FE-RTROW-013: late beats range beats leg beats overnight', () => { + const all: ScheduleWarning[] = [ + { index: 0, code: 'overnight' }, + { index: 0, code: 'leg', overMinutes: 30 }, + { index: 0, code: 'range', sinceKm: 700 }, + { index: 0, code: 'late', minutes: 20 }, + ] + expect(pickWarning(all)?.code).toBe('late') + expect(pickWarning(all.slice(0, 3))?.code).toBe('range') + expect(pickWarning(all.slice(0, 2))?.code).toBe('leg') + expect(pickWarning(all.slice(0, 1))?.code).toBe('overnight') + }) + + it('FE-RTROW-028: the order the findings arrive in does not decide', () => { + // Sonst haengt die Marke davon ab, in welcher Reihenfolge deriveDriveWarnings sie anhaengt. + const all: ScheduleWarning[] = [ + { index: 0, code: 'late', minutes: 20 }, + { index: 0, code: 'range', sinceKm: 700 }, + { index: 0, code: 'overnight' }, + ] + expect(pickWarning(all)?.code).toBe('late') + expect(pickWarning([...all].reverse())?.code).toBe('late') + }) + + it('FE-RTROW-014: nothing to report is null, not a placeholder', () => { + expect(pickWarning([])).toBeNull() + }) +}) + +describe('stageOf', () => { + const days = [day([stop('A')], { dayId: 11, dayNumber: 1 }), day([stop('B')], { dayId: 22, dayNumber: 2 })] + + it('FE-RTROW-015: finds the day by its id, not by its position', () => { + expect(stageOf(days, 22)?.dayNumber).toBe(2) + }) + + it('FE-RTROW-016: no selection and an id that is gone both give null', () => { + expect(stageOf(days, null)).toBeNull() + expect(stageOf(days, 999)).toBeNull() + expect(stageOf([], 11)).toBeNull() + }) +}) + +describe('destinationCount', () => { + it('FE-RTROW-017: agrees with the highest number the rows handed out', () => { + const d = mixedDay() + const highest = stopRows(roadtripRows(d)).reduce((max, r) => Math.max(max, r.number ?? 0), 0) + expect(destinationCount(d)).toBe(3) + expect(destinationCount(d)).toBe(highest) + }) + + it('FE-RTROW-018: a day of nothing but services and nights counts none', () => { + expect(destinationCount(day([stop('Aral', { stopType: 'fuel' }), night()]))).toBe(0) + }) +}) + +const timedDay = (arrivals: (string | null)[], stops: RoadtripStop[]) => + day(stops, { schedule: { entries: arrivals.map((a) => entry(a)), warnings: [] } }) + +describe('upNextStop', () => { + const threeStops = () => + timedDay(['09:00', '11:00', '13:00'], [stop('A'), stop('Aral', { stopType: 'fuel' }), stop('C')]) + + it('FE-RTROW-019: says nothing on a day that is not today, and nothing without a day', () => { + expect(upNextStop(threeStops(), 10 * 60, false)).toBeNull() + expect(upNextStop(null, 10 * 60, true)).toBeNull() + }) + + it('FE-RTROW-020: passes over the petrol stop and names the next destination', () => { + // Die Tankstelle um 11:00 liegt vor dem Ziel um 13:00 und ist trotzdem nie das naechste. + const next = upNextStop(threeStops(), 10 * 60, true) + expect(next?.row.stop.name).toBe('C') + expect(next?.minutesUntil).toBe(180) + }) + + it('FE-RTROW-021: a stop without a readable time is passed over', () => { + const d = timedDay([null, 'irgendwann', '13:00'], [stop('A'), stop('B'), stop('C')]) + expect(upNextStop(d, 8 * 60, true)?.row.stop.name).toBe('C') + }) + + it('FE-RTROW-022: a stop due this very minute is still ahead', () => { + expect(upNextStop(threeStops(), 13 * 60, true)?.minutesUntil).toBe(0) + }) + + it('FE-RTROW-023: a stop whose time has just passed comes back as a delay', () => { + // Es gibt keine Positionsquelle, also ist "der Plan sagte 13:00, es ist 13:20" + // die staerkste ehrliche Aussage. Sie kommt als negatives minutesUntil. + expect(upNextStop(threeStops(), 13 * 60 + 20, true)?.minutesUntil).toBe(-20) + }) + + it('FE-RTROW-024: an hour past the last stop the day is over and nothing is next', () => { + expect(upNextStop(threeStops(), 14 * 60 + 1, true)).toBeNull() + }) + + it('FE-RTROW-025: a delay is only ever reported for the last stop, never a passed one', () => { + // 09:00 ist lange vorbei, 13:00 auch, gemeldet wird der Verzug auf den letzten. + const late = upNextStop(threeStops(), 13 * 60 + 30, true) + expect(late?.row.stop.name).toBe('C') + expect(late?.minutesUntil).toBe(-30) + }) + + it('FE-RTROW-026: another day, no day and a day without any clock name nothing', () => { + expect(upNextStop(timedDay(['09:00'], [stop('A')]), 12 * 60, false)).toBeNull() + expect(upNextStop(null, 12 * 60, true)).toBeNull() + expect(upNextStop(timedDay([null], [stop('A')]), 12 * 60, true)).toBeNull() + expect(upNextStop(timedDay(['nachmittags'], [stop('A')]), 12 * 60, true)).toBeNull() + }) + + it('FE-RTROW-027: a service stop is never the one named, even when it is next in line', () => { + // Die Tankstelle um 10:00 laege vorne, genannt wird trotzdem das Ziel um 11:00. + const d = timedDay(['09:00', '10:00', '11:00'], [stop('A'), stop('Aral', { stopType: 'fuel' }), stop('B')]) + expect(upNextStop(d, 9 * 60 + 30, true)?.row.stop.name).toBe('B') + }) +}) + +describe('stageClocks', () => { + it('FE-RTROW-029: starts at the first stop arrival and arrives at the last one, neither departure', () => { + // The reported stage: a pin at 10:00 with an hour and a half there headed the card as + // 11:30, a clock no row prints. The last stop leaves at 21:33, which is not an arrival either. + const d = day([stop('Hamburg Speicherstadt', { dwellMinutes: 90, time: '10:00' }), stop('Sanssouci', { dwellMinutes: 120 })], { + schedule: { + entries: [entry('10:00', { departure: '11:30', anchored: true }), entry('19:33', { departure: '21:33' })], + warnings: [], + }, + }) + const clocks = stageClocks(roadtripRows(d)) + expect(clocks).toEqual({ start: '10:00', arrive: '19:33' }) + expect(Object.values(clocks)).not.toContain('11:30') + expect(Object.values(clocks)).not.toContain('21:33') + }) + + it('FE-RTROW-030: a morning after an automatic night starts at the resume point, and a day end point arrives nowhere', () => { + const d = day([night('start'), stop('Fulda'), stop('Kassel'), night('end')], { + schedule: { entries: [entry('08:00'), entry('09:10', { departure: '10:00' }), entry('12:40'), entry('22:00')], warnings: [] }, + }) + expect(stageClocks(roadtripRows(d))).toEqual({ start: '08:00', arrive: '12:40' }) + }) + + it('FE-RTROW-031: a spill band departure belongs to the day before and does not start this one', () => { + const d = day([stop('A'), stop('B')], { + spills: [{ at: 0, count: 1, fromDayNumber: 1, departure: '23:10', leg: undefined, fromStop: undefined, line: [] }], + schedule: { entries: [entry('00:40'), entry('02:00')], warnings: [] }, + }) + expect(stageClocks(roadtripRows(d))).toEqual({ start: '00:40', arrive: '02:00' }) + }) + + it('FE-RTROW-032: untimed stops are skipped at both ends, deliberately, and a day with no clock at all gives nulls', () => { + // Skipping rather than dashing is a choice: a day whose first leg has no route yet still + // has one clock worth heading the card with, even when start and arrival are that one. + const partly = timedDay([null, '11:00', null], [stop('A'), stop('B'), stop('C')]) + expect(stageClocks(roadtripRows(partly))).toEqual({ start: '11:00', arrive: '11:00' }) + + const untimed = timedDay([null, null], [stop('A'), stop('B')]) + expect(stageClocks(roadtripRows(untimed))).toEqual({ start: null, arrive: null }) + expect(stageClocks([])).toEqual({ start: null, arrive: null }) + + // A petrol stop is a place you drive to, so its arrival counts like any other. + const fuelFirst = timedDay(['07:50', '09:00'], [stop('Aral', { stopType: 'fuel' }), stop('B')]) + expect(stageClocks(roadtripRows(fuelFirst))).toEqual({ start: '07:50', arrive: '09:00' }) + }) + + it('FE-RTROW-033: follows the row order rather than the clock, for a missed pin and for an unsplit card past midnight', () => { + // A pin the drive cannot make keeps its own clock, so the last row can read earlier + // than the one above it. The arrival is still that last row's clock, not the latest one. + const missed = timedDay( + ['11:00', '10:00'], + [stop('Harbour', { dwellMinutes: 60, time: '11:00' }), stop('Ferry', { time: '10:00' })], + ) + expect(stageClocks(roadtripRows(missed))).toEqual({ start: '11:00', arrive: '10:00' }) + + // When a daily window cannot be kept, each stored day is timed on its own and never + // split: an evening stay can then head a card that ends on a pin the next morning. The + // figures still name the first and the last clock the chain prints. + const unsplit = timedDay(['18:30', '10:00'], [stop('Hotel', { dwellMinutes: 900 }), stop('Museum')]) + expect(stageClocks(roadtripRows(unsplit))).toEqual({ start: '18:30', arrive: '10:00' }) + }) +}) + +describe('stageEnd', () => { + it('FE-RTROW-034: names the last stop the chain draws with its own arrival, not the automatic day end after it', () => { + // The reported bar: Kyoto Station reached at 12:40 sat beside 22:00, where the window closed. + const d = day([stop('Bremen'), stop('Aral', { stopType: 'fuel' }), stop('Kyoto Station'), night()], { + schedule: { entries: [entry('09:00'), entry('10:30'), entry('12:40'), entry('22:00')], warnings: [] }, + }) + const end = stageEnd(roadtripRows(d)) + expect(end?.stop.name).toBe('Kyoto Station') + expect(end?.time).toBe('12:40') + + // A service stop is still a stop the drive ends at, so it is the one named. + const fuelLast = timedDay(['09:00', '11:00'], [stop('A'), stop('Aral', { stopType: 'fuel' })]) + expect(stageEnd(roadtripRows(fuelLast))?.stop.name).toBe('Aral') + }) + + it('FE-RTROW-035: a stage drawn with nothing but its night markers, and no rows at all, end nowhere', () => { + expect(stageEnd(roadtripRows(day([night('start'), night('end')])))).toBeNull() + expect(stageEnd([])).toBeNull() + }) +}) + +describe('firstStopOfPlace', () => { + it('FE-RTROW-036: on one card, a place visited twice answers with its first visit and a night on it never does', () => { + // A loop day: out of the hotel in the morning, back to it at night. + const loop = day([ + stop('Nacht', { placeId: 300, assignmentId: 90, automaticNight: { phase: 'start', fromDayNumber: 1 } }), + stop('Hotel', { placeId: 300, assignmentId: 1 }), + stop('Museum', { placeId: 301, assignmentId: 2 }), + stop('Hotel', { placeId: 300, assignmentId: 3 }), + ]) + expect(firstStopOfPlace([loop], 300)?.assignmentId).toBe(1) + expect(firstStopOfPlace([loop], 301)?.assignmentId).toBe(2) + }) + + it('FE-RTROW-037: across days it keeps day order, a card handed alone ignores the days before it, and no stop gives null', () => { + const monday = day([stop('Town', { placeId: 301, assignmentId: 11 })], { dayId: 7 }) + const tuesday = day([stop('Town', { placeId: 301, assignmentId: 21 }), stop('Lake', { placeId: 302, assignmentId: 22 })], { dayId: 8 }) + expect(firstStopOfPlace([monday, tuesday], 301)?.assignmentId).toBe(11) + expect(firstStopOfPlace([tuesday], 301)?.assignmentId).toBe(21) + expect(firstStopOfPlace([monday, tuesday], 302)?.assignmentId).toBe(22) + + expect(firstStopOfPlace([monday, tuesday], 999)).toBeNull() + expect(firstStopOfPlace([], 301)).toBeNull() + // Only an automatic night sits on this position, which is not a stop anybody chose. + expect(firstStopOfPlace([day([stop('Nacht', { placeId: 303, automaticNight: { phase: 'end', fromDayNumber: 1 } })])], 303)).toBeNull() + }) +}) + +describe('legReroutable', () => { + it('FE-RTROW-038: a routed leg between two stops anybody chose can be offered other ways, a service stop included', () => { + const d = day([stop('Bremen'), stop('Aral', { stopType: 'fuel' }), stop('Kassel')]) + expect(legReroutable(d, 0)).toBe(true) + expect(legReroutable(d, 1)).toBe(true) + }) + + it('FE-RTROW-039: no leg into or out of an automatic night, none without a route, none past either end', () => { + // Bremen, Kassel, automatic night, Fulda: the rail offers the first leg only. + const withNight = day([stop('Bremen'), stop('Kassel'), night(), stop('Fulda')]) + expect(legReroutable(withNight, 0)).toBe(true) + // Into the marker where the window closed, and out of it again the morning after. + expect(legReroutable(withNight, 1)).toBe(false) + expect(legReroutable(withNight, 2)).toBe(false) + expect(legReroutable(day([night('start'), stop('Fulda')]), 0)).toBe(false) + + // A leg the router has not answered for yet has nothing to weigh an offer against. + const unrouted = day([stop('A'), stop('B'), stop('C')], { legs: [seg(0)] }) + expect(legReroutable(unrouted, 0)).toBe(true) + expect(legReroutable(unrouted, 1)).toBe(false) + + // The last stop has no leg after it, whatever the legs array happens to hold. + const extra = day([stop('A'), stop('B')], { legs: [seg(0), seg(1)] }) + expect(legReroutable(extra, 1)).toBe(false) + expect(legReroutable(extra, -1)).toBe(false) + }) +}) diff --git a/client/src/components/Roadtrip/roadtripRowModel.ts b/client/src/components/Roadtrip/roadtripRowModel.ts new file mode 100644 index 000000000..4a51c8cc3 --- /dev/null +++ b/client/src/components/Roadtrip/roadtripRowModel.ts @@ -0,0 +1,321 @@ +import { isServiceStopType, type ScheduleEntry, type ScheduleWarning } from './roadtripModel' +import type { RoadtripDay, RoadtripStop, RouteSegment } from '@trek/shared/roadtrip' + +/** + * A road trip day, flattened into the rows a screen draws, with no React in sight. + * + * The rail builds its rows inline while it renders, which is fine for a panel that only + * ever exists once. The phone draws the same chain in a second shell, and the two would + * drift the first time a rule changed, and the duplication budget does not stretch to + * the same forty lines of branching twice. So the branching lives here: what is a row, + * in which order, and which of a stop's findings survives the two marks a 375px line can + * carry. + * + * Deliberately free of React, translations and formatting. It answers "what is on this + * line", never "how does it read", so it can be unit tested on its own and so the same + * answer can be drawn twice in two different design languages. + */ + +export type RoadtripRow = + | { kind: 'spill'; fromDayNumber: number; departs: string | null; stops: StopRow[] } + | StopRow + | { kind: 'leg'; index: number; seg: RouteSegment | undefined; mode: string | null } + | { kind: 'dry'; legIndex: number; intoLegKm: number; sinceKm: number } + | { kind: 'auto'; phase: 'end' | 'resume'; time: string | null } + +export interface StopRow { + kind: 'stop' + stop: RoadtripStop + /** Position in the day's numbering, or null for a service stop and an automatic night. */ + number: number | null + service: boolean + entry: ScheduleEntry | undefined + /** The clock this row shows on the right: when the traveller gets there. */ + time: string | null + /** When they leave again, which is arrival plus the stay. Null without a schedule. */ + departure: string | null + /** True when a person pinned that time, which is what the pin in front of it means. */ + pinned: boolean + /** At most two marks fit a 375px row. This is the one warning that earned the second. */ + warning: ScheduleWarning | null + dwellMinutes: number | null + offRoadMeters: number | null +} + +/** + * Which finding wins when a stop has several. + * + * The desktop stacks all of them, which is honest on a 420px rail and unreadable on a + * phone. The order is by what changes the next decision soonest: being late moves every + * arrival after it, running dry strands the car, and an over-long leg is a planning + * remark you can act on tonight. + */ +const WARNING_RANK: Record = { + late: 0, + range: 1, + leg: 2, + overnight: 3, +} + +export function pickWarning(warnings: readonly ScheduleWarning[]): ScheduleWarning | null { + let best: ScheduleWarning | null = null + for (const w of warnings) { + if (!best || WARNING_RANK[w.code] < WARNING_RANK[best.code]) best = w + } + return best +} + +/** The one day a phone screen shows, picked from what the routing round produced. */ +export function stageOf(days: readonly RoadtripDay[], dayId: number | null): RoadtripDay | null { + if (dayId == null) return null + return days.find(d => d.dayId === dayId) ?? null +} + +function stopRow( + stop: RoadtripStop, + index: number, + number: number | null, + schedule: RoadtripDay['schedule'], + driveWarnings: readonly ScheduleWarning[], +): StopRow { + // Only ever called for a real stop: an automatic night is the shell's own marker + // for "the day ended here" and `roadtripRows` turns it into an 'auto' row instead. + const entry = schedule.entries[index] + const mine = driveWarnings.filter(w => w.index === index) + return { + kind: 'stop', + stop, + number, + service: isServiceStopType(stop.stopType), + entry, + time: entry?.arrival ?? null, + departure: entry?.departure ?? null, + pinned: !!entry?.anchored, + warning: pickWarning(mine), + dwellMinutes: stop.dwellMinutes, + offRoadMeters: stop.offRoadMeters ?? null, + } +} + +/** + * The rows of one day, in the order they are drawn. + * + * Two things here are easy to get wrong and both have a test: + * + * 1. Numbering counts destinations only. A petrol station between stop two and stop + * three does not make the next one four, and neither does the marker that ends the + * day. Numbering off the array index gets both wrong. + * 2. `ownerDayId` is the day a stop is STORED on, which after a night drive is not the + * card it is drawn on. The rows follow the card, because that is what the traveller + * reads, and anything writing back has to use `ownerDayId` instead. + */ +/** + * Whether a leg is the model's placeholder for "the day ended where you were standing". + * + * `dayWindow.stationary()` puts one of these between the last stop of a day and the + * automatic night that closes it: same coordinate at both ends, nothing measured, no + * texts. It is bookkeeping, not a drive, and drawn as a pill it said either " in " (the + * separator of `roadtrip.leg.driveText` with both slots empty) or, once that was guarded, + * "No route" under a stop the traveller had simply arrived at. + * + * Matched on the shape rather than on the next stop being an automatic night, because + * what makes it not a drive is that it goes nowhere. A night the traveller moved to a + * point down the road HAS a leg, with a distance, and that one keeps its pill. + */ +function isStationary(seg: RouteSegment | undefined): boolean { + return !!seg + && seg.distance === 0 + && seg.from[0] === seg.to[0] + && seg.from[1] === seg.to[1] +} + +export function roadtripRows(day: RoadtripDay): RoadtripRow[] { + const rows: RoadtripRow[] = [] + const spills = day.spills ?? [] + + let number = 0 + day.stops.forEach((stop, i) => { + const spill = spills.find(s => s.at === i) + if (spill) { + rows.push({ + kind: 'spill', + fromDayNumber: spill.fromDayNumber, + departs: spill.departure, + stops: [], + }) + } + + const automatic = !!stop.automaticNight + if (automatic) { + rows.push({ + kind: 'auto', + phase: stop.automaticNight?.phase === 'start' ? 'resume' : 'end', + time: day.schedule.entries[i]?.arrival ?? null, + }) + } else { + if (!isServiceStopType(stop.stopType)) number += 1 + rows.push(stopRow(stop, i, isServiceStopType(stop.stopType) ? null : number, day.schedule, day.driveWarnings)) + } + + // The leg AFTER this stop, plus the dry point that falls on it. Both belong + // between two stops, so they are emitted here rather than in their own pass. + const seg = day.legs[i] + if (i < day.stops.length - 1 && !isStationary(seg)) { + rows.push({ kind: 'leg', index: i, seg, mode: day.stops[i + 1]?.incomingLegMode ?? stop.legMode ?? null }) + const dry = (day.dryPoints ?? []).find(p => p.legIndex === i) + if (dry) { + rows.push({ kind: 'dry', legIndex: i, intoLegKm: dry.intoLegKm, sinceKm: dry.sinceKm }) + } + } + }) + + return rows +} + +/** + * Whether the leg leaving stop `index` can be offered other ways of driving it. + * + * The desktop rail's rule, kept here so the phone chain offers the button on exactly the + * legs the rail does. A leg needs a route, because an unrouted one has nothing to weigh an + * offer against. And neither of its ends may be an automatic night: that point is the + * shell's own marker for where the daily window closed, a spot somewhere along the road + * rather than a stop anyone chose. The router's offers from or to it would reshape a + * stretch of a longer drive, and the via a choice writes is filed by the position of a + * stored stop, which the marker is not. The rail draws the band out of that marker + * without the control for the same reason. + */ +export function legReroutable(day: RoadtripDay, index: number): boolean { + return index >= 0 + && index < day.stops.length - 1 + && !!day.legs[index] + && !day.stops[index].automaticNight + && !day.stops[index + 1].automaticNight +} + +/** Stops that carry a number, for a count that agrees with the numbering above. */ +export function destinationCount(day: RoadtripDay): number { + return day.stops.filter(s => !s.automaticNight && !isServiceStopType(s.stopType)).length +} + +/** + * The two clocks a stage is headed with: when it starts, and when you reach its last place. + * + * Both are read off the clock the rows print on the right, which is an arrival all the way + * down (the desktop rail keeps the same rule and spells a departure out in words where it + * needs one). So each figure is one the chain below repeats, and the start is the first + * stop's ARRIVAL rather than the moment you leave it. A first stop is a place you get to, + * often at a time somebody pinned, and heading the card with its departure hid that + * appointment behind its own stay: a stop pinned at 10:00 with an hour and a half there + * read as leaving at 11:30, a clock no row shows. + * + * A resume point is a start, because the morning after an automatic night begins there. A + * day end point is not an arrival: it marks where the window closed, not a place. A spill + * band is passed over, because the departure it carries belongs to the day before. + * + * Stops without a clock are skipped at both ends instead of dashing the figure. That only + * happens while a leg between them and the timed stops has no route yet, and a partly timed + * day still has a first and a last clock worth reading, even when both are the same stop's. + * + * First and last mean row order, not the earliest and the latest clock, because the column + * is not guaranteed to run forwards. A pin the drive cannot make keeps its own clock, so it + * can read earlier than the stop above it. And when a daily window cannot be kept, each + * stored day is timed on its own without being split, so a card can open on an evening stay + * and end on a pin the next morning. The figures follow the rows in both cases, so they + * never name a clock the chain does not. + */ +export function stageClocks(rows: readonly RoadtripRow[]): { start: string | null; arrive: string | null } { + let start: string | null = null + let arrive: string | null = null + for (const row of rows) { + if (row.kind === 'stop' && row.time) { + start ??= row.time + arrive = row.time + } else if (row.kind === 'auto' && row.phase === 'resume' && row.time) { + start ??= row.time + } + } + return { start, arrive } +} + +/** + * The stop a stage ends on: the last one the chain draws, a service stop included. + * + * The map half names it in its bar and opens it on a tap, so the name, the clock beside it + * and the sheet the tap brings up all come off this one row and cannot name three different + * things. The clock used to be read off the schedule on its own, which found the automatic + * day end whenever the window closed after the last stop: a station reached at 12:40 sat + * beside 22:00, the moment the day ran out rather than anything that happens there. + * + * Null for a stage without a single stop, one drawn with nothing but its night markers. + * There is nothing for a tap to open then, and the bar says so by not being a button. + */ +export function stageEnd(rows: readonly RoadtripRow[]): StopRow | null { + for (let i = rows.length - 1; i >= 0; i--) { + const row = rows[i] + if (row.kind === 'stop') return row + } + return null +} + +/** + * The stop a place's pin stands for on the road trip map: its first visit in the days given. + * + * A pin is drawn once per place, while a place can be several stops, like the hotel a loop + * day leaves in the morning and comes back to at night, or a town the drive passes on two + * days. Over a stage the caller hands in that one card, so a pin opens the visit on the + * stage being looked at, however many days before it stop at the same place. Over the + * whole drive it hands in every routed day, and the first visit in day order is the one a + * traveller reading the drive from its start reaches first. + * + * An automatic night can sit on a place's position, but nobody chose to stop there, so it + * never answers. Null when none of the days stops at the place, which is a pin the road + * trip cannot explain and the caller hands to the plan's own place inspector instead. + */ +export function firstStopOfPlace(days: readonly RoadtripDay[], placeId: number): RoadtripStop | null { + for (const day of days) { + const stop = day.stops.find(s => !s.automaticNight && s.placeId === placeId) + if (stop) return stop + } + return null +} + +/** + * The next destination the plan still owes you, measured against the clock. + * + * Only for today: a countdown on a day in March is noise. `minutesUntil` goes + * NEGATIVE once that stop's planned time has passed, and that negative number is + * the only honest statement about running late this screen can make. There is no + * position source, so the app cannot know whether the stop was reached; what it + * can say is that the plan said 10:45 and it is now 11:21. + * + * Null once the last stop's time is past: a screen still saying "next" after the + * driving is done is worse than one saying nothing. + */ +export function upNextStop( + day: RoadtripDay | null, + nowMinutes: number, + isToday: boolean, +): { row: StopRow; minutesUntil: number } | null { + if (!day || !isToday) return null + const timed = roadtripRows(day) + .filter((r): r is StopRow => r.kind === 'stop' && !r.service) + .map(row => ({ row, at: clockMinutes(row.time) })) + .filter((x): x is { row: StopRow; at: number } => x.at != null) + if (!timed.length) return null + + const ahead = timed.find(x => x.at >= nowMinutes) + if (ahead) return { row: ahead.row, minutesUntil: ahead.at - nowMinutes } + + // Everything is past. The last one is only still "next" while the day has not + // run out entirely, which we take as its planned time plus the hour after it. + const last = timed[timed.length - 1] + const overdue = nowMinutes - last.at + return overdue <= 60 ? { row: last.row, minutesUntil: -overdue } : null +} + +function clockMinutes(time: string | null): number | null { + if (!time) return null + const [h, m] = time.split(':').map(Number) + if (!Number.isFinite(h) || !Number.isFinite(m)) return null + return h * 60 + m +} diff --git a/client/src/components/Roadtrip/stageMap.test.ts b/client/src/components/Roadtrip/stageMap.test.ts new file mode 100644 index 000000000..529ac81b8 --- /dev/null +++ b/client/src/components/Roadtrip/stageMap.test.ts @@ -0,0 +1,250 @@ +import { describe, expect, it } from 'vitest' +import { dayColor } from './dayColors' +import { stageMapData, stagePlaceIds, stagePoints } from './stageMap' +import type { AccessSpur, RoadtripDay, RoadtripRoutes, RoadtripStop } from '@trek/shared/roadtrip' + +// FE-RTSTAGE-001 to FE-RTSTAGE-015 + +function stop(name: string, over: Partial = {}): RoadtripStop { + return { + assignmentId: 1, + ownerDayId: 7, + ownerIndex: 0, + placeId: 100, + name, + lat: 48.1, + lng: 11.2, + time: null, + dwellMinutes: null, + legMode: null, + incomingLegMode: null, + stopType: null, + ...over, + } +} + +function day(stops: RoadtripStop[], over: Partial = {}): RoadtripDay { + return { + dayId: 7, + dayNumber: 2, + date: '2026-06-02', + title: null, + stops, + legs: [], + schedule: { entries: [], warnings: [] }, + legVias: [], + geometry: [], + distance: 0, + duration: 0, + driveWarnings: [], + dayWarning: null, + ...over, + } +} + +const spur = (stopKey: string): AccessSpur => ({ + line: [ + [48, 11], + [48.001, 11.001], + ], + meters: 120, + stopKey, +}) + +/** Der Schluessel, den assemble baut: Position auf fuenf Stellen plus beide Fahrtarten. */ +const keyFor = (s: RoadtripStop) => + `${s.lat.toFixed(5)},${s.lng.toFixed(5)},${s.legMode ?? ''},${s.incomingLegMode ?? ''}` + +const LINES: [number, number][][] = [ + [ + [48, 11], + [48.1, 11.1], + ], + [ + [48.1, 11.1], + [48.2, 11.2], + ], + [ + [48.2, 11.2], + [48.3, 11.3], + ], + [ + [48.3, 11.3], + [48.4, 11.4], + ], +] + +function routes(over: Partial = {}): RoadtripRoutes { + return { + days: [], + quietDays: [], + lines: LINES, + lineDays: [1, 2, 2, 3], + lineJoins: [false, false, false, false], + accessLines: [], + vias: [], + segments: [], + totalDistance: 0, + totalDuration: 0, + totalStops: 0, + loading: false, + ...over, + } +} + +describe('stageMapData without a stage', () => { + it('FE-RTSTAGE-001: draws every line of the drive, none filtered away', () => { + expect(stageMapData(routes(), null, true).lines).toEqual(LINES) + }) + + it('FE-RTSTAGE-002: gives each line the colour of the day it belongs to', () => { + const colors = stageMapData(routes(), null, true).lineColors + expect(colors).toEqual([dayColor(1), dayColor(2), dayColor(2), dayColor(3)]) + expect(colors).toHaveLength(LINES.length) + }) + + it('FE-RTSTAGE-003: keeps every spur and filters no markers', () => { + // Ohne Auswahl gibt es nichts zu verstecken: leere placeIds heisst "kein Filter". + const data = stageMapData(routes({ accessLines: [spur('a'), spur('b')] }), null, true) + expect(data.accessLines).toHaveLength(2) + expect(data.placeIds.size).toBe(0) + expect(data.focusPoints).toEqual([]) + }) + + it('FE-RTSTAGE-004: day colours off leaves the paint to the map', () => { + expect(stageMapData(routes(), null, false).lineColors).toBeUndefined() + }) +}) + +describe('stageMapData with a stage', () => { + const stage = day([stop('Kassel', { placeId: 11 }), stop('Fulda', { placeId: 22, lat: 50.55, lng: 9.68 })], { + dayNumber: 2, + }) + + it('FE-RTSTAGE-005: keeps only the lines of that day', () => { + expect(stageMapData(routes(), stage, true).lines).toEqual([LINES[1], LINES[2]]) + }) + + it('FE-RTSTAGE-016: the drive into the next day is left off the stage', () => { + // With "connect the days" on, that leg is drawn in the colour of the day it leaves, so + // filtering by day number alone handed the stage a line running off it to a place the + // day never visits. On a phone, where the stage IS the map, it was the longest thing + // on screen and read as the day's own route. + const withJoin = routes({ lineJoins: [false, false, true, false] }) + + expect(stageMapData(withJoin, stage, true).lines).toEqual([LINES[1]]) + }) + + it('FE-RTSTAGE-020: a day that is nothing but driving keeps its connection rather than going blank', () => { + // Night to night, no stop of its own: the connection is the only line the day has, and + // the line IS the day. Better a map that shows the drive than an empty one. + const onlyJoin = routes({ lineDays: [1, 2, 3, 3], lineJoins: [false, true, false, false] }) + + expect(stageMapData(onlyJoin, stage, true).lines).toEqual([LINES[1]]) + }) + + it('FE-RTSTAGE-017: the colours still line up once a join has been dropped', () => { + const data = stageMapData(routes({ lineJoins: [false, false, true, false] }), stage, true) + + expect(data.lineColors).toHaveLength(data.lines.length) + expect(data.lineColors).toEqual([dayColor(2)]) + }) + + it('FE-RTSTAGE-018: the all-days view keeps the joins, which is the view they are for', () => { + // The setting draws the whole drive as one connected line; that is what it is for, and + // on this map the connection has the other days beside it. + expect(stageMapData(routes({ lineJoins: [false, false, true, false] }), null, true).lines).toEqual(LINES) + }) + + it('FE-RTSTAGE-019: routes from before the flag existed are drawn as they were', () => { + // `lineJoins` arrives with this change, and a RoadtripRoutes read back from an older + // cache has none. Without the marks nothing is known to be a join, so nothing is + // dropped: the day is drawn the way it was drawn before. + const legacy = { ...routes(), lineJoins: undefined } as unknown as Parameters[0] + + expect(stageMapData(legacy, stage, true).lines).toEqual([LINES[1], LINES[2]]) + }) + + it('FE-RTSTAGE-006: the colours stay lined up with the lines that are left', () => { + const data = stageMapData(routes(), stage, true) + expect(data.lineColors).toHaveLength(data.lines.length) + expect(data.lineColors).toEqual([dayColor(2), dayColor(2)]) + }) + + it('FE-RTSTAGE-007: a day the routing round drew nothing for keeps no lines', () => { + expect(stageMapData(routes(), day([stop('Kassel')], { dayNumber: 9 }), true).lines).toEqual([]) + }) + + it('FE-RTSTAGE-008: day colours off leaves the paint to the map here too', () => { + expect(stageMapData(routes(), stage, false).lineColors).toBeUndefined() + }) + + it('FE-RTSTAGE-009: the stage names its places and its fit points', () => { + const data = stageMapData(routes(), stage, true) + expect([...data.placeIds]).toEqual([11, 22]) + expect(data.focusPoints).toEqual([ + [48.1, 11.2], + [50.55, 9.68], + ]) + }) + + it('FE-RTSTAGE-010: before the routing round has any line, the stage still gets places and fit', () => { + // Sonst springt die Karte beim ersten Oeffnen ins Nichts, bis die Route da ist. + const data = stageMapData(routes({ lines: [], lineDays: [] }), stage, true) + expect(data.lines).toEqual([]) + expect(data.lineColors).toBeUndefined() + expect(data.accessLines).toEqual([]) + expect(data.placeIds.size).toBe(2) + expect(data.focusPoints).toHaveLength(2) + }) +}) + +describe('stageMapData access spurs', () => { + const onStage = stop('Kassel', { lat: 51.31627, lng: 9.49797, legMode: 'car', incomingLegMode: null }) + const stage = day([onStage]) + + it('FE-RTSTAGE-011: a spur comes along exactly when its stop does', () => { + const mine = spur(keyFor(onStage)) + const elsewhere = spur(keyFor(stop('Bremen', { lat: 53.07, lng: 8.8 }))) + expect(stageMapData(routes({ accessLines: [mine, elsewhere] }), stage, true).accessLines).toEqual([mine]) + }) + + it('FE-RTSTAGE-012: a stop with no mode on one side still finds its spur', () => { + // Der letzte Stopp des Tages faehrt nirgends mehr hin, der erste kommt von nirgends her. + const last = stop('Fulda', { lat: 50.55221, lng: 9.6752, legMode: null, incomingLegMode: 'car' }) + const spurs = [spur(keyFor(onStage)), spur(keyFor(last))] + expect(stageMapData(routes({ accessLines: spurs }), day([onStage, last]), true).accessLines).toEqual(spurs) + }) + + it('FE-RTSTAGE-013: the key carries both leg modes, so the same spot in another mode is a different stop', () => { + // Zwei Stopps auf demselben Parkplatz unterscheiden sich nur hier. + const ferry = spur(`${onStage.lat.toFixed(5)},${onStage.lng.toFixed(5)},ferry,`) + expect(stageMapData(routes({ accessLines: [ferry] }), stage, true).accessLines).toEqual([]) + }) +}) + +describe('stagePlaceIds', () => { + it('FE-RTSTAGE-014: leaves the automatic night out, it has no place behind it', () => { + const stage = day([ + stop('Kassel', { placeId: 11 }), + stop('Nacht', { placeId: 0, automaticNight: { phase: 'end', fromDayNumber: 1 } }), + stop('Fulda', { placeId: 22 }), + ]) + expect([...stagePlaceIds(stage)]).toEqual([11, 22]) + }) +}) + +describe('stagePoints', () => { + it('FE-RTSTAGE-015: keeps order and drops what cannot be put on a map', () => { + const stage = day([ + stop('Kassel', { lat: 51.31, lng: 9.49 }), + stop('Ohne', { lat: Number.NaN, lng: 9.5 }), + stop('Auch ohne', { lat: 50.5, lng: Number.NaN }), + stop('Fulda', { lat: 50.55, lng: 9.68 }), + ]) + expect(stagePoints(stage)).toEqual([ + [51.31, 9.49], + [50.55, 9.68], + ]) + }) +}) diff --git a/client/src/components/Roadtrip/stageMap.ts b/client/src/components/Roadtrip/stageMap.ts new file mode 100644 index 000000000..51b45d4e3 --- /dev/null +++ b/client/src/components/Roadtrip/stageMap.ts @@ -0,0 +1,107 @@ +import { dayColor } from './dayColors' +import type { AccessSpur, RoadtripDay, RoadtripRoutes } from '@trek/shared/roadtrip' + +/** + * What the map draws for ONE stage of a drive. + * + * The rail hides a folded day by filtering the whole trip's lines; a phone shows one + * day and hides the rest, which is the same filter read from the other end. Rather + * than a second `collapsedRoadtripDays` set built backwards from the selection (a + * set that would then have to be kept out of the desktop's own folding), the + * selection picks its lines here, and the untouched whole-trip arrays stay available + * for the "all days" view. + * + * `lineDays` runs parallel to `lines`, so both are filtered in one pass and the + * colours stay lined up with what is left. Same rule the desktop follows. + */ +export interface StageMapData { + lines: [number, number][][] + lineColors: { line: string; casing: string }[] | undefined + accessLines: AccessSpur[] + /** Place ids on this stage, for the marker filter. Empty means "no filter". */ + placeIds: Set + focusPoints: [number, number][] +} + +const EMPTY: StageMapData = { + lines: [], + lineColors: undefined, + accessLines: [], + placeIds: new Set(), + focusPoints: [], +} + +export function stageMapData( + routes: RoadtripRoutes, + stage: RoadtripDay | null, + dayColorsOn: boolean, +): StageMapData { + // No stage selected is the "whole drive" view, which is every line in its own + // colour, the best overview the addon has on a phone, and it costs nothing + // because the routing round has already produced all of it. + if (!stage) { + return { + lines: routes.lines, + lineColors: dayColorsOn ? routes.lineDays.map(n => dayColor(n)) : undefined, + accessLines: routes.accessLines, + placeIds: new Set(), + focusPoints: [], + } + } + if (!routes.lines.length) return { ...EMPTY, placeIds: stagePlaceIds(stage), focusPoints: stagePoints(stage) } + + // A stage is ONE day, so the drive into the next day is left off it. + // + // With "connect the days" on, that leg is drawn in the colour of the day it leaves, so + // on the whole-drive map it reads as that day carrying on. Filtering by day number + // alone therefore handed a stage a line that runs off it to a place the day never + // visits: on a phone, where the stage IS the map, that read as the day's own route and + // was the longest thing on screen. The desktop has the same connection, but it has it + // beside every other day, which is the view the setting exists for; here that view is + // the "all days" one, a tap away on the same map. + const ofDay: number[] = [] + routes.lineDays.forEach((n, i) => { if (n === stage.dayNumber) ofDay.push(i) }) + const own = ofDay.filter(i => !routes.lineJoins?.[i]) + // A day that is nothing but driving — no stop of its own, night to night — has only the + // connection to show. Dropping it there would leave the map blank on the very day the + // line IS the day, so the filter gives way rather than emptying the screen. + const keep = own.length ? own : ofDay + const placeIds = stagePlaceIds(stage) + + return { + lines: keep.map(i => routes.lines[i]), + lineColors: dayColorsOn ? keep.map(() => dayColor(stage.dayNumber)) : undefined, + // A spur belongs to a stop, so it comes along exactly when its stop does. + accessLines: routes.accessLines.filter(spur => spurOnStage(spur, stage)), + placeIds, + focusPoints: stagePoints(stage), + } +} + +/** + * The places drawn on this stage. + * + * Automatic nights are left out: they are the shell's own marker for where a day + * ended, not somewhere anybody stops, and they have no place row behind them. + */ +export function stagePlaceIds(stage: RoadtripDay): Set { + return new Set(stage.stops.filter(s => !s.automaticNight).map(s => s.placeId)) +} + +/** The stage's stops as coordinates, for the fit. */ +export function stagePoints(stage: RoadtripDay): [number, number][] { + return stage.stops + .filter(s => Number.isFinite(s.lat) && Number.isFinite(s.lng)) + .map(s => [s.lat, s.lng] as [number, number]) +} + +/** + * A spur's key is the one `assemble` builds: position to five decimals plus both + * leg modes. Rebuilt here rather than imported because it is assemble's private + * detail, and the five decimals are what make it exact enough to tell two stops in + * the same car park apart. + */ +function spurOnStage(spur: AccessSpur, stage: RoadtripDay): boolean { + return stage.stops.some(s => + `${s.lat.toFixed(5)},${s.lng.toFixed(5)},${s.legMode ?? ''},${s.incomingLegMode ?? ''}` === spur.stopKey) +} diff --git a/client/src/components/Roadtrip/useCorridorPois.test.ts b/client/src/components/Roadtrip/useCorridorPois.test.ts index 62103fce9..ecf2c2032 100644 --- a/client/src/components/Roadtrip/useCorridorPois.test.ts +++ b/client/src/components/Roadtrip/useCorridorPois.test.ts @@ -30,6 +30,9 @@ const hit = (id: string, lat: number, lng: number, category = 'fuel') => ({ source: 'openstreetmap', }) +/** Long enough to tile into a handful of boxes, so a cap and a window can bite. */ +const LONG: LatLng[] = Array.from({ length: 12 }, (_, i) => ({ lat: 53.55 - i * 0.05, lng: 9.99 - i * 0.2 })) + const answer = (...items: ReturnType[]) => ({ pois: items, sources: ['openstreetmap'], failedSources: [], truncated: false, clamped: false }) beforeEach(() => { @@ -192,4 +195,70 @@ describe('useCorridorPois', () => { unmount() expect(seen!.aborted).toBe(true) }) + it('FE-ROADTRIP-CORRIDOR-013: a window cuts the boxes, not the line the hits are measured on', async () => { + const full = renderHook(() => useCorridorPois(LONG, ['fuel'], 10)) + act(() => { full.result.current.search() }) + await waitFor(() => expect(full.result.current.loading).toBe(false)) + const whole = pois.mock.calls.length + const spine = full.result.current.spine.length + + pois.mockClear() + const part = renderHook(() => useCorridorPois(LONG, ['fuel'], 10)) + act(() => { part.result.current.search({ fromKm: 0, toKm: 20 }) }) + await waitFor(() => expect(part.result.current.loading).toBe(false)) + + // Fewer requests, which is the whole point of asking about a stretch... + expect(pois.mock.calls.length).toBeLessThan(whole) + // ...and the same spine, which is what keeps `alongKm` meaning the same thing. A + // cut spine would renumber every hit and every stop the moment the reach moved. + expect(part.result.current.spine.length).toBe(spine) + }) + + it('FE-ROADTRIP-CORRIDOR-014: the window belongs to the search, so the last answer survives the next question', async () => { + pois.mockResolvedValue(answer(hit('a', 53.5, 9.81))) + const { result } = renderHook(() => useCorridorPois(LINE, ['fuel'], 10)) + + act(() => { result.current.search({ fromKm: 0, toKm: 20 }) }) + await waitFor(() => expect(result.current.results.length).toBeGreaterThan(0)) + + // Re-rendering with a different reach in mind must not empty the list: only + // asking again does. The window is an argument, never a dependency. + expect(result.current.results.map(r => r.osm_id)).toEqual(['a']) + }) + + it('FE-ROADTRIP-CORRIDOR-015: a budget caps the boxes and says the tail was left out', async () => { + const { result } = renderHook(() => + useCorridorPois(LONG, ['fuel'], 10, { budget: { maxTiles: 2, maxRetries: null, deadlineMs: null } })) + act(() => { result.current.search() }) + await waitFor(() => expect(result.current.loading).toBe(false)) + + expect(pois.mock.calls.length).toBe(2) + expect(result.current.capped).toBe(true) + }) + + it('FE-ROADTRIP-CORRIDOR-016: a capped retry pass reports the boxes it did not ask again', async () => { + pois.mockRejectedValue(new Error('mirror down')) + const { result } = renderHook(() => + useCorridorPois(LONG, ['fuel'], 10, { budget: { maxTiles: 4, maxRetries: 1, deadlineMs: null } })) + act(() => { result.current.search() }) + await waitFor(() => expect(result.current.loading).toBe(false)) + + // Four boxes, four failures, one retried: the three never asked again are still + // failures, because "we did not look" is the honest reading either way. + expect(pois.mock.calls.length).toBe(5) + expect(result.current.failedAreas).toBe(4) + expect(result.current.error).toBe(true) + }) + + it('FE-ROADTRIP-CORRIDOR-017: a deadline stops starting boxes and files the rest as unsearched', async () => { + // Every box answers, slowly. The deadline is what ends the run, not the answers. + pois.mockImplementation(() => new Promise(resolve => setTimeout(() => resolve(answer()), 40))) + const { result } = renderHook(() => + useCorridorPois(LONG, ['fuel'], 10, { budget: { maxTiles: 16, maxRetries: 0, deadlineMs: 1 } })) + act(() => { result.current.search() }) + await waitFor(() => expect(result.current.loading).toBe(false), { timeout: 4000 }) + + expect(result.current.failedAreas).toBeGreaterThan(0) + expect(pois.mock.calls.length).toBeLessThan(result.current.progress.total + 1) + }) }) diff --git a/client/src/components/Roadtrip/useCorridorPois.ts b/client/src/components/Roadtrip/useCorridorPois.ts index f7b951c74..69c12ede8 100644 --- a/client/src/components/Roadtrip/useCorridorPois.ts +++ b/client/src/components/Roadtrip/useCorridorPois.ts @@ -1,7 +1,8 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { roadtripSearchRepo } from '../../repo/roadtripSearchRepo' import { useTranslation } from '../../i18n' -import { corridorTiles, projectOntoRoute, simplifyLine, type Bbox, type LatLng } from './corridor' +import { corridorTiles, projectOntoRoute, simplifyLine, sliceAtMeters, type Bbox, type LatLng } from './corridor' +import { DESKTOP_CORRIDOR_BUDGET, type CorridorBudget } from './corridorSearchModel' import type { Poi } from '../Map/poiCategories' /** A POI that is actually on the way, with the two numbers that make it one. */ @@ -30,16 +31,24 @@ export interface CorridorSearch { error: boolean /** The thinned line every `alongKm` above is measured along. */ spine: LatLng[] - search: () => void + /** + * Asks, optionally only about a stretch of the line. + * + * The window is an argument rather than hook state because it belongs to the question: + * one traveller asks about the fifty kilometres ahead and the next about the whole day, + * off the same route and the same categories, and neither should make the other's + * answer disappear before it was read. + */ + search: (window?: CorridorWindow | null) => void clear: () => void } -/** - * How many bounding boxes one search may ask Overpass for. A German-to-Italian drive - * would otherwise be dozens of requests against a shared public mirror; past this the - * search stops and says so rather than quietly covering half the route. - */ -const MAX_TILES = 16 +/** A stretch of the drive, in kilometres along the spine. */ +export interface CorridorWindow { + fromKm: number + toKm: number +} + /** Gap after a request before the same worker starts the next — the mirrors are shared. */ const REQUEST_SPACING_MS = 250 /** How many boxes are in flight at once. */ @@ -64,7 +73,21 @@ const sleep = (ms: number, signal: AbortSignal): Promise => * every route change, because each run is several Overpass requests and the mirrors are * shared. Results stay until the categories or the route change. */ -export function useCorridorPois(line: LatLng[], categories: string[], widthKm: number): CorridorSearch { +export function useCorridorPois( + line: LatLng[], + categories: string[], + widthKm: number, + /** + * What one search may cost. + * + * Absent means the desktop's behaviour, unchanged: every box of the whole day, every + * failed box retried, no deadline. The phone passes a smaller ceiling, because a cell + * is not a desk and a search that keeps the radio warm for a minute is a search that + * costs battery somebody is navigating on. + */ + options?: { budget?: CorridorBudget }, +): CorridorSearch { + const budget = options?.budget ?? DESKTOP_CORRIDOR_BUDGET const { locale } = useTranslation() const [results, setResults] = useState([]) const [progress, setProgress] = useState({ done: 0, total: 0 }) @@ -104,15 +127,22 @@ export function useCorridorPois(line: LatLng[], categories: string[], widthKm: n const catKey = categories.join(',') useEffect(() => { clear() }, [routeKey, catKey, widthKm, clear]) - const search = useCallback(() => { + const search = useCallback((window?: CorridorWindow | null) => { abortRef.current?.abort() if (spine.length < 2 || categories.length === 0) return const controller = new AbortController() abortRef.current = controller const runId = ++runIdRef.current - const allTiles = corridorTiles(spine, widthKm) - const tiles = allTiles.slice(0, MAX_TILES) + // Only the TILE line is cut, never the spine: every `alongKm` in a result is a + // distance along the spine, and so is every entry in `stopsAlongKm`. Cutting the + // spine would renumber both the moment the window moved, and a hit would land at the + // wrong position in the day's chain. + const tileLine = window ? sliceAtMeters(spine, window.fromKm * 1000, window.toKm * 1000) : spine + const allTiles = corridorTiles(tileLine, widthKm) + const tiles = allTiles.slice(0, budget.maxTiles) + const startedAt = Date.now() + const outOfTime = (): boolean => budget.deadlineMs != null && Date.now() - startedAt > budget.deadlineMs setCapped(allTiles.length > tiles.length) setFailedSources([]) @@ -180,6 +210,9 @@ export function useCorridorPois(line: LatLng[], categories: string[], widthKm: n const worker = async (): Promise => { while (next < jobs.length) { if (controller.signal.aborted || runId !== runIdRef.current) return + // Out of time stops STARTING boxes; whatever answered stays on screen and the + // rest reports itself as unsearched, the same way a failed box does. + if (outOfTime()) { failures += jobs.length - next; setFailedAreas(failures); return } const job = jobs[next++] if (!(await collect(job))) retryable.push(job) done++ @@ -195,8 +228,11 @@ export function useCorridorPois(line: LatLng[], categories: string[], widthKm: n // One more pass over what did not answer. Overpass mirrors time out under load far // more often than they are truly empty, and reporting "4 stretches went unsearched" // when a second ask would have answered them is the wrong end of the trade. - for (const job of retryable) { + const retries = budget.maxRetries == null ? retryable : retryable.slice(0, budget.maxRetries) + failures += retryable.length - retries.length + for (const job of retries) { if (controller.signal.aborted || runId !== runIdRef.current) return + if (outOfTime()) { failures += retries.length - retries.indexOf(job); break } if (await collect(job)) continue failures++ setFailedAreas(failures) @@ -205,7 +241,7 @@ export function useCorridorPois(line: LatLng[], categories: string[], widthKm: n setError(failures === jobs.length && failures > 0) setLoading(false) })() - }, [spine, categories, widthKm, locale]) + }, [spine, categories, widthKm, locale, budget.maxTiles, budget.maxRetries, budget.deadlineMs]) useEffect(() => () => abortRef.current?.abort(), []) diff --git a/client/src/components/Roadtrip/useFollowTrack.test.ts b/client/src/components/Roadtrip/useFollowTrack.test.ts index f26463f9b..e207e6e30 100644 --- a/client/src/components/Roadtrip/useFollowTrack.test.ts +++ b/client/src/components/Roadtrip/useFollowTrack.test.ts @@ -41,7 +41,7 @@ function day(over: Partial = {}): RoadtripDay { } const routes = (days: RoadtripDay[]): RoadtripRoutes => ({ - days, lines: [], lineDays: [], segments: [], accessLines: [], vias: [], totalDistance: 0, totalDuration: 0, totalStops: 0, quietDays: [], loading: false, + days, lines: [], lineDays: [], lineJoins: [], segments: [], accessLines: [], vias: [], totalDistance: 0, totalDuration: 0, totalStops: 0, quietDays: [], loading: false, }) function viasStub(over: Partial = {}): RoadtripVias { diff --git a/client/src/components/Roadtrip/useRoadtripCorridor.test.ts b/client/src/components/Roadtrip/useRoadtripCorridor.test.ts index 0b1fbc798..9baec57a7 100644 --- a/client/src/components/Roadtrip/useRoadtripCorridor.test.ts +++ b/client/src/components/Roadtrip/useRoadtripCorridor.test.ts @@ -40,7 +40,7 @@ function day(over: Partial = {}): RoadtripDay { } const routes = (days: RoadtripDay[]): RoadtripRoutes => ({ - days, lines: [], lineDays: [], segments: [], accessLines: [], vias: [], totalDistance: 0, totalDuration: 0, totalStops: 0, quietDays: [], loading: false, + days, lines: [], lineDays: [], lineJoins: [], segments: [], accessLines: [], vias: [], totalDistance: 0, totalDuration: 0, totalStops: 0, quietDays: [], loading: false, }) /** The search state the mocked hook hands back, results included. */ diff --git a/client/src/components/Roadtrip/useRoadtripCorridor.ts b/client/src/components/Roadtrip/useRoadtripCorridor.ts index 691756e37..2b922cfec 100644 --- a/client/src/components/Roadtrip/useRoadtripCorridor.ts +++ b/client/src/components/Roadtrip/useRoadtripCorridor.ts @@ -1,5 +1,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useCorridorPois, type CorridorPoi, type CorridorSearch } from './useCorridorPois' +import type { CorridorBudget } from './corridorSearchModel' import { sectionAnchors, insertIndexForAlong } from './roadtripModel' import type { SectionAnchor } from './roadtripModel' import { projectOntoRoute, type LatLng } from './corridor' @@ -74,7 +75,16 @@ export interface RoadtripCorridor { * answer if you cannot see which one is on your side of the road — so the results have to * live above both the panel and the map rather than inside the panel. */ -export function useRoadtripCorridor(routes: RoadtripRoutes, tripId?: number | string | null): RoadtripCorridor { +export function useRoadtripCorridor( + routes: RoadtripRoutes, + tripId?: number | string | null, + /** + * What one search may cost. Absent is the desktop's ceiling; the phone hands down a + * smaller one. Not a window: which stretch of the day to ask about is decided per + * search, by whoever presses the button, and travels as an argument to `search`. + */ + options?: { budget?: CorridorBudget }, +): RoadtripCorridor { const [dayId, setDayId] = useState('') const [categories, setCategories] = useState(['fuel']) const [widthKm, setWidthKm] = useState(5) @@ -109,7 +119,7 @@ export function useRoadtripCorridor(routes: RoadtripRoutes, tripId?: number | st return day.stops.map(s => ({ lat: s.lat, lng: s.lng })) }, [day]) - const search = useCorridorPois(line, categories, widthKm) + const search = useCorridorPois(line, categories, widthKm, options) /** * Whether what the panel looks for has been decided yet. diff --git a/client/src/components/Roadtrip/useRouteAlternatives.test.ts b/client/src/components/Roadtrip/useRouteAlternatives.test.ts index 4b2db3f24..4b43f35ec 100644 --- a/client/src/components/Roadtrip/useRouteAlternatives.test.ts +++ b/client/src/components/Roadtrip/useRouteAlternatives.test.ts @@ -12,7 +12,7 @@ import type { RoadtripStop } from './useRoadtripRoutes' import type { RoadtripVia } from '@trek/shared' /** - * FE-ALTHOOK-001..009 — asking for other ways of driving one leg. + * FE-ALTHOOK-001..010: asking for other ways of driving one leg. * * The case that carries the feature: when the leg already carries vias, the road * actually being driven is NOT among what the router offers for the two bare @@ -147,4 +147,25 @@ describe('useRouteAlternatives', () => { expect(signals[1].aborted).toBe(true) expect(result.current.open).toBeNull() }) + + it('FE-ALTHOOK-010: the state keeps its identity until the picker itself changes', async () => { + // The planner keys its close gate on this object. A new one per render ran that + // effect on every render, so any render at all was a chance to close the picker. + const { result, rerender } = renderHook(() => useRouteAlternatives()) + const idle = result.current + rerender() + expect(result.current).toBe(idle) + + act(() => { result.current.ask(4, 1, from, to, 'driving', []) }) + const asking = result.current + expect(asking).not.toBe(idle) + // The functions themselves never change, only the object carrying the new `open`. + expect(asking.ask).toBe(idle.ask) + expect(asking.close).toBe(idle.close) + + await waitFor(() => expect(result.current.open?.loading).toBe(false)) + const answered = result.current + rerender() + expect(result.current).toBe(answered) + }) }) diff --git a/client/src/components/Roadtrip/useRouteAlternatives.ts b/client/src/components/Roadtrip/useRouteAlternatives.ts index e1bee3b84..9d4c5fd67 100644 --- a/client/src/components/Roadtrip/useRouteAlternatives.ts +++ b/client/src/components/Roadtrip/useRouteAlternatives.ts @@ -1,4 +1,4 @@ -import { useCallback, useRef, useState } from 'react' +import { useCallback, useMemo, useRef, useState } from 'react' import { calculateAlternatives, calculateRoute, type RouteAlternative } from '../Map/RouteCalculator' import type { RoadtripStop } from './useRoadtripRoutes' import type { RoadtripVia } from '@trek/shared' @@ -108,5 +108,11 @@ export function useRouteAlternatives(): RouteAlternativesState { }) }, []) - return { open, ask, close } + // One object for as long as nothing in it changes. The planner keys its close gate and + // the callbacks that ask, choose and focus on this state as a whole, so a fresh object + // per render re-ran that gate and rebuilt those callbacks on every render of the + // planner, whatever had caused it. Whether the picker stays open is still the gate's own + // condition to decide (a new `open` runs it either way); the memo only stops that work + // from repeating on renders that changed nothing about the picker. + return useMemo(() => ({ open, ask, close }), [open, ask, close]) } diff --git a/client/src/components/SystemNotices/SystemNoticeHost.test.tsx b/client/src/components/SystemNotices/SystemNoticeHost.test.tsx index 84afad95a..e6db29e82 100644 --- a/client/src/components/SystemNotices/SystemNoticeHost.test.tsx +++ b/client/src/components/SystemNotices/SystemNoticeHost.test.tsx @@ -1,4 +1,4 @@ -// FE-W4SNH-001 to FE-W4SNH-008 +// FE-W4SNH-001 to FE-W4SNH-012 import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { render, screen, act } from '../../../tests/helpers/render' import { useSystemNoticeStore, type SystemNoticeDTO } from '../../store/systemNoticeStore' @@ -152,4 +152,92 @@ describe('SystemNoticeHost', () => { expect(screen.getByTestId('modals')).toHaveTextContent('thanks') }) + // The deploy window: the server already serves the new release notice, the browser is + // still running the bundle the service worker cached, and the keys that notice names do + // not exist in it. See hasCopy in SystemNoticeHost. + it('FE-W4SNH-009: a notice made only of keys this build cannot resolve waits instead of showing them', () => { + useSystemNoticeStore.setState({ + loaded: true, + notices: [notice({ + id: 'release-notes', + display: 'modal', + titleKey: 'system_notice.release_notes.title', + bodyKey: 'system_notice.release_notes.body', + })], + }) + + render() + + expect(screen.getByTestId('modals')).toBeEmptyDOMElement() + }) + + it('FE-W4SNH-010: a release notice is judged by the strings its own layout draws', () => { + // The release panel never shows the generic title and body, so a resolvable pair there + // would vouch for a panel that is still all keys. The keys name a release this build + // knows nothing about, which is exactly the position an old bundle is in. + const release = { + version: '5.0.0', + eyebrowKey: 'system_notice.release_notes_5_0_0.eyebrow', + headlineKey: 'system_notice.release_notes_5_0_0.headline', + introKey: 'system_notice.release_notes_5_0_0.intro', + featuresLabelKey: 'system_notice.release_notes_5_0_0.features_label', + features: [], + note: { + eyebrowKey: 'system_notice.release_notes_5_0_0.note_eyebrow', + titleKey: 'system_notice.release_notes_5_0_0.note_title', + bodyKey: 'system_notice.release_notes_5_0_0.note_body', + promiseLabelKey: 'system_notice.release_notes_5_0_0.promise_label', + promiseLeadKey: 'system_notice.release_notes_5_0_0.promise_lead', + promiseTextKey: 'system_notice.release_notes_5_0_0.promise_text', + bodyAfterKey: 'system_notice.release_notes_5_0_0.note_body_after', + closingKey: 'system_notice.release_notes_5_0_0.note_closing', + }, + supportLeadKey: 'system_notice.release_notes_5_0_0.support_lead', + supportTextKey: 'system_notice.release_notes_5_0_0.support_text', + } + useSystemNoticeStore.setState({ + loaded: true, + notices: [notice({ id: 'release-notes', display: 'modal', titleKey: 'Update', bodyKey: 'Installed', release })], + }) + + render() + + expect(screen.getByTestId('modals')).toBeEmptyDOMElement() + }) + + it('FE-W4SNH-011: a notice written out in words is shown, keys or no keys', () => { + // An instance's own announcement carries literal copy, and t() hands back anything it + // does not know — so the shape of the string is what tells the two apart. + useSystemNoticeStore.setState({ + loaded: true, + notices: [notice({ + id: 'outage', + display: 'modal', + titleKey: 'Maintenance tonight', + bodyKey: 'The server restarts at 22:00.', + })], + }) + + render() + + expect(screen.getByTestId('modals')).toHaveTextContent('outage') + }) + + it('FE-W4SNH-012: one resolved string is enough to show the notice', () => { + // Generous on purpose: half a translation is still readable, and a notice hidden by + // mistake is the worse failure. 'common.save' is in every build. + useSystemNoticeStore.setState({ + loaded: true, + notices: [notice({ + id: 'half', + display: 'modal', + titleKey: 'common.save', + bodyKey: 'system_notice.not.in.this.build', + })], + }) + + render() + + expect(screen.getByTestId('modals')).toHaveTextContent('half') + }) }) diff --git a/client/src/components/SystemNotices/SystemNoticeHost.tsx b/client/src/components/SystemNotices/SystemNoticeHost.tsx index 8c86040a7..d622d3148 100644 --- a/client/src/components/SystemNotices/SystemNoticeHost.tsx +++ b/client/src/components/SystemNotices/SystemNoticeHost.tsx @@ -1,5 +1,6 @@ import { useEffect, useState } from 'react'; -import { useSystemNoticeStore } from '../../store/systemNoticeStore.js'; +import { useSystemNoticeStore, type SystemNoticeDTO } from '../../store/systemNoticeStore.js'; +import { useTranslation } from '../../i18n/index.js'; import { ModalRenderer } from './SystemNoticeModal.js'; import { BannerRenderer, ToastRenderer } from './SystemNoticeBanner.js'; @@ -18,8 +19,44 @@ function useIsMobile() { return isMobile; } +/** + * A key by its shape: dotted, no spaces, `system_notice.release_notes.headline`. + * + * A notice may carry literal copy instead of a key — an instance's own announcement is + * written out, not translated — and `t()` hands any string it does not know straight back, + * so the test below cannot tell "no translation" from "this IS the text" on its own. The + * shape can: a sentence has spaces and no dots between words. + */ +const KEY_SHAPE = /^[a-z0-9_-]+(\.[a-z0-9_-]+)+$/i; + +/** + * Whether a notice has words to show, rather than the names of strings this build lacks. + * + * The keys come from the server's registry, the copy from the bundle in the browser, and a + * deploy parts the two for as long as it takes the page to reload: the service worker keeps + * serving the old app while `/api/config` already reports the new version, and the release + * notice for that very version arrives naming keys the old bundle never had. What is drawn + * is then `system_notice.release_notes.headline` where the headline belongs, on the one + * notice whose whole job is to be read once per release. Worse, a dismissal in that window + * is a real one: it is `per-version`, so whoever closes the gibberish never sees the notes. + * + * So a notice made only of unresolved keys waits. Nothing is spent by waiting — a notice is + * used up by `POST /dismiss` and by nothing else — and `App.tsx` reloads the page as soon + * as the new worker takes over, after which this returns true and the modal opens for real. + * + * Deliberately generous: one resolved key is enough. Half a translation is still readable, + * and a notice hidden by mistake is a worse failure than an ugly one. + */ +function hasCopy(notice: SystemNoticeDTO, t: (key: string) => string): boolean { + const keys = notice.release + ? [notice.release.headlineKey, notice.release.introKey, notice.release.note.titleKey] + : [notice.titleKey, notice.bodyKey]; + return keys.some(key => !KEY_SHAPE.test(key) || t(key) !== key); +} + export function SystemNoticeHost() { const { notices, loaded } = useSystemNoticeStore(); + const { t } = useTranslation(); const isMobile = useIsMobile(); // Notices are fetched by authStore after login (see App.tsx / authStore modification). @@ -33,8 +70,10 @@ export function SystemNoticeHost() { if (!loaded) return null; - // desktopOnly notices (e.g. the thank-you/support modal) are hidden on mobile. - const visible = isMobile ? notices.filter(n => !n.desktopOnly) : notices; + // desktopOnly notices (e.g. the thank-you/support modal) are hidden on mobile, and a + // notice whose copy this build does not have yet waits for the reload (see hasCopy). + const readable = notices.filter(n => hasCopy(n, t)); + const visible = isMobile ? readable.filter(n => !n.desktopOnly) : readable; const modals = visible.filter(n => n.display === 'modal'); const banners = visible.filter(n => n.display === 'banner'); diff --git a/client/src/constants/tripTabs.ts b/client/src/constants/tripTabs.ts index a5fd8d54e..62e734fc6 100644 --- a/client/src/constants/tripTabs.ts +++ b/client/src/constants/tripTabs.ts @@ -12,6 +12,7 @@ */ export const TRIP_TAB_IDS = [ 'plan', + 'roadtrip', 'transports', 'buchungen', 'listen', @@ -30,6 +31,7 @@ export type TripTabId = (typeof TRIP_TAB_IDS)[number] */ export const TRIP_TAB_LABEL_KEYS: Record = { plan: 'trip.tabs.plan', + roadtrip: 'roadtrip.title', transports: 'trip.tabs.transports', buchungen: 'trip.tabs.reservations', listen: 'trip.tabs.lists', diff --git a/client/src/mobile/components/MBadge.test.tsx b/client/src/mobile/components/MBadge.test.tsx new file mode 100644 index 000000000..5ad7defba --- /dev/null +++ b/client/src/mobile/components/MBadge.test.tsx @@ -0,0 +1,74 @@ +// FE-COMP-MBADGE-001 to FE-COMP-MBADGE-006 +import { describe, expect, it } from 'vitest' +import { render, screen } from '@testing-library/react' +import { Route } from 'lucide-react' +import MBadge from './MBadge' + +describe('MBadge', () => { + it('FE-COMP-MBADGE-001: renders its label in a span and is no control', () => { + render(3 stops) + + const badge = screen.getByText('3 stops') + expect(badge.tagName).toBe('SPAN') + // It sits inside buttons, and a button inside a button is invalid markup. + expect(screen.queryByRole('button')).toBeNull() + }) + + it('FE-COMP-MBADGE-002: is neutral by default on the resting chip tokens, and strong on the active ones', () => { + render(neutral) + const neutral = screen.getByText('neutral') + expect(neutral.className).toContain('bg-[color:var(--m-ic)]') + expect(neutral.className).toContain('border-[color:var(--m-rowbr)]') + expect(neutral.className).not.toContain('bg-m-act') + + render(strong) + const strong = screen.getByText('strong') + expect(strong.className).toContain('bg-m-act') + expect(strong.className).toContain('text-m-actfg') + expect(strong.className).not.toContain('bg-[color:var(--m-ic)]') + }) + + it('FE-COMP-MBADGE-003: sets words in caps by default and leaves a unit symbol alone when asked', () => { + render(Sat 2) + expect(screen.getByText('Sat 2').className).toContain('uppercase') + + render(300 m) + // Uppercase would turn metres into megametres. + expect(screen.getByText('300 m').className).not.toContain('uppercase') + }) + + it('FE-COMP-MBADGE-004: is 18px at xs, the default, and 22px at sm', () => { + render(small) + expect(screen.getByText('small').className).toContain('h-[18px]') + + render(larger) + const larger = screen.getByText('larger') + expect(larger.className).toContain('h-[22px]') + expect(larger.className).toContain('ms-auto') + }) + + it('FE-COMP-MBADGE-005: draws an icon before the label, inside the same pill and out of its name', () => { + render(}>412 km) + + const badge = screen.getByText('412 km') + const icon = badge.firstElementChild as HTMLElement + expect(icon.querySelector('svg')).not.toBeNull() + expect(icon).toHaveAttribute('aria-hidden', 'true') + expect(badge.lastChild?.textContent).toBe('412 km') + }) + + it('FE-COMP-MBADGE-006: keeps a figure on one line, and lets a sentence wrap inside the width it is given', () => { + render(412 km) + const figure = screen.getByText('412 km') + expect(figure.className).toContain('whitespace-nowrap') + expect(figure.className).toContain('h-[18px]') + + render(Still working out the rest of the drive) + const sentence = screen.getByText('Still working out the rest of the drive') + expect(sentence.className).toContain('whitespace-normal') + expect(sentence.className).toContain('max-w-full') + expect(sentence.className).toContain('min-h-[22px]') + expect(sentence.className).not.toContain('whitespace-nowrap') + expect(sentence.className).not.toMatch(/(^|\s)h-\[22px\]/) + }) +}) diff --git a/client/src/mobile/components/MBadge.tsx b/client/src/mobile/components/MBadge.tsx new file mode 100644 index 000000000..f5c52fa01 --- /dev/null +++ b/client/src/mobile/components/MBadge.tsx @@ -0,0 +1,66 @@ +import type { ReactNode } from 'react' + +interface MBadgeProps { + /** + * `neutral` is MChip's resting look and the one to reach for. `strong` is MChip's active + * look, for the single figure a surface is about, and never inside something tappable: + * a filled pill in a button reads as a second control sitting in the first. + */ + tone?: 'neutral' | 'strong' + /** `xs` is 18px, for a second line under a title. `sm` is 22px, for a 34px pill. */ + size?: 'xs' | 'sm' + /** + * Caps with tracking by default, for words. A figure with a unit symbol passes false, + * because m and M are different units, and so does a clock, which has no case to change. + */ + caps?: boolean + /** + * Lets a long sentence break inside the pill instead of running past its container. A + * figure keeps to one line, which is why this is off by default: the pill then stops at + * the width it is given and grows in height with the text. + */ + wrap?: boolean + icon?: ReactNode + className?: string + children: ReactNode +} + +/** + * The non-interactive sibling of MChip: a fact, not a control. + * + * A span, because every place a badge sits in the road trip chrome is itself a button, and + * a button inside a button is markup that no browser and no screen reader agree on. Caps + * with tracking are the desktop day card's DAY_BADGE, set for a phone. + * + * Pills side by side lose the space between them when a screen reader builds a name out of + * them, so a button made of badges carries its own aria-label (see stageBadges.badgeLabel). + */ +export default function MBadge({ + tone = 'neutral', + size = 'xs', + caps = true, + wrap = false, + icon, + className = '', + children, +}: MBadgeProps) { + return ( + + {/* The icon only repeats what the label says, so it stays out of the name. */} + {icon && } + {children} + + ) +} diff --git a/client/src/mobile/components/MChip.tsx b/client/src/mobile/components/MChip.tsx index eee99f143..414a61e91 100644 --- a/client/src/mobile/components/MChip.tsx +++ b/client/src/mobile/components/MChip.tsx @@ -3,17 +3,26 @@ import { ReactNode } from 'react' interface MChipProps { active?: boolean onClick?: () => void + /** + * `sm` is the 30px chip a form sheet packs six of into a row; `tap` is 38px, for a + * chip that IS the control rather than a setting beside one. Apple's own floor is + * 44px and a chip cannot be that and still fit a row of categories, so `tap` buys + * back what it can: the chips that start a search are the ones worth the height. + */ + size?: 'sm' | 'tap' className?: string children: ReactNode } /** Small pill chip: --m-act when active, neutral --m-ic surface otherwise. */ -export default function MChip({ active = false, onClick, className = '', children }: MChipProps) { +export default function MChip({ active = false, onClick, size = 'sm', className = '', children }: MChipProps) { return ( @@ -487,7 +513,7 @@ export default function MJourneyDetail() { nothing between the cards and it; two pixels keeps a hair of daylight and gives the strip the rest. */} {view === 'timeline' && entries.length > 0 && ( -
+
export type MTripView = 'plan' | 'map' export type MTripMode = 'go' | 'edit' | 'browse' +/** The road trip tab's own two halves: the chain, or the same map showing the stage. */ +export type MRtView = 'list' | 'map' export type MTripListsTab = 'packing' | 'todo' export type MTripCollabTab = 'chat' | 'notes' | 'links' | 'polls' @@ -60,6 +67,27 @@ export interface MTripSheetState { export interface MTripShellApi { /** 'plan' = list chrome, 'map' = fullscreen map. Plan tab only. */ view: MTripView + /** The road trip tab's own list ⇄ map switch, independent of `view`. */ + rtView: MRtView + /** + * True whenever the map is the front layer, in either tab. + * + * The map is one instance shared by the plan tab and the road trip tab, so + * everything floating over it (POI pill, compass, pills) keys off this rather + * than off `view`, which only ever meant the plan tab. + */ + mapFront: boolean + /** Road trip tab: chain ⇄ map, on the same instance, without moving the camera. */ + toggleRtView: () => void + /** + * How much of the stage the corridor search asks about. + * + * Shell state rather than sheet state, because two surfaces ask the same question: + * the bar over the stage says what the next search will cover, and the sheet is where + * it is chosen. Kept here they cannot disagree, and it survives the sheet closing. + */ + rtReach: CorridorReach + setRtReach: (value: CorridorReach) => void /** Travel/Plan/Places segment: go | edit | browse. */ mode: MTripMode /** Legacy tab ids: plan · transports · buchungen · listen · finanzplan · dateien · collab · plugin:* */ @@ -150,14 +178,8 @@ interface MTripShellProps { Sheets?: ComponentType } -/** The 5 dock tabs in demo order; files/collab/plugins live in the Mehr sheet. */ -const DOCK_TABS: { id: string; icon: LucideIcon }[] = [ - { id: 'plan', icon: MapIcon }, - { id: 'transports', icon: TrainFront }, - { id: 'buchungen', icon: Ticket }, - { id: 'finanzplan', icon: Wallet }, - { id: 'listen', icon: PackageCheck }, -] +/** The two tabs that share the map instance. Everything else is a full overlay. */ +const MAP_TABS = new Set(['plan', 'roadtrip']) function dayChipLabel(day: Day, language: string, fallback: string): string { if (day.date) { @@ -182,8 +204,14 @@ export default function MTripShell({ // Per-day colours from the dayTintProvider plugin hook — the mobile counterpart // of the desktop day-card wash, carried on the day chips. Empty without a plugin. const dayTints = usePluginDayTints(tripId) + const distanceUnit = useSettingsStore(s => s.settings.distance_unit) const [view, setView] = useState('plan') + // Its own state rather than a share of `view`: the two tabs carry different + // things on the same map, and forcing one into the other's half is the kind of + // coupling nobody can predict from the outside. + const [rtView, setRtView] = useState('list') + const [rtReach, setRtReach] = useState('ahead') const [mode, setMode] = useState('go') const [browseFromEdit, setBrowseFromEdit] = useState(false) const [sheet, setSheet] = useState(null) @@ -318,6 +346,24 @@ export default function MTripShell({ } } + /** + * The road trip tab's own list ⇄ map switch. + * + * Deliberately quieter than `toggleView`: no reframe on the way in and no day + * restore on the way out. The stage is always one day, the chain and the map show + * the same one, and the camera belongs to whoever looked at it last. What does + * reframe is a stage change, through the day chips, which both halves share. + */ + const toggleRtView = () => { + setRtView(prev => { + const next = prev === 'list' ? 'map' : 'list' + if (next === 'map') planner.autoShowRoute() + return next + }) + } + + const mapFront = (trTab === 'plan' && view === 'map') || (trTab === 'roadtrip' && rtView === 'map') + const setListsTab = (tab: MTripListsTab) => { setListsTabState(tab) sessionStorage.setItem(`trip-lists-subtab-${tripId}`, tab) @@ -327,7 +373,7 @@ export default function MTripShell({ const closeSheet = () => setSheet(null) const shell: MTripShellApi = { - view, mode, trTab, setTrTab, setTravelMode, toggleView, browseFromEdit, + view, rtView, mapFront, toggleRtView, rtReach, setRtReach, mode, trTab, setTrTab, setTravelMode, toggleView, browseFromEdit, sheet, openSheet, closeSheet, listsTab, setListsTab, collabTab, setCollabTab, transportsCompact, bookingsCompact, @@ -341,7 +387,7 @@ export default function MTripShell({ if (!trip) return null const enabledTabIds = new Set(planner.TRIP_TABS.map(tab => tab.id)) - const dockTabs = DOCK_TABS.filter(d => enabledTabIds.has(d.id)) + const dockTabs = pickDockTabs(enabledTabIds) const tabLabel = (id: string) => planner.TRIP_TABS.find(tab => tab.id === id)?.label ?? id const onDayChipTap = (dayId: number) => { @@ -355,25 +401,62 @@ export default function MTripShell({ const packedCount = packingItems.filter(i => i.checked).length const todoOpenCount = todoItems.filter(i => !i.checked).length + // The stage header: the day on screen and what it costs, or the whole drive while + // the day filter is off. A figure nothing has measured yet is left out rather than + // printed as 0 m, and with neither figure the pill falls back to the addon's own name, + // so it never reads as an empty one. + const rtStage = stageOf(planner.roadtripRoutes.days, planner.selectedDayId) + const rtStageDay = rtStage ? days.find(d => d.id === rtStage.dayId) : undefined + let rtHeaderDay: string | null = null + if (rtStage) { + const dayN = t('planner.dayN', { n: rtStage.dayNumber }) + rtHeaderDay = rtStageDay ? dayChipLabel(rtStageDay, language, dayN) : dayN + } + const rtHeaderDistance = distanceBadge( + rtStage ? rtStage.distance : planner.roadtripRoutes.totalDistance, + distanceUnit, + ) + const rtHeaderLabel = badgeLabel([rtHeaderDay, rtHeaderDistance]) + return (
{/* ── Content layers ─────────────────────────────────────────────── */} - {trTab === 'plan' && ( + {/* + One expression for both map tabs, and it has to stay one: written as two + (`{trTab === 'plan' && }{trTab === 'roadtrip' && }`) + React sees two positions and remounts the map on every tab switch, which + tears down the WebGL context and reloads every tile. The symptom is a flash + on the device, not a failing test. + */} + {MAP_TABS.has(trTab) && (
- {view === 'plan' && mode !== 'browse' && ( + {trTab === 'plan' && view === 'plan' && mode !== 'browse' && (
)} - {mode === 'browse' && ( + {trTab === 'plan' && mode === 'browse' && (
)} + {/* + The stage lives at z-20, below the day chips at z-25, which is the whole + of the stage picker: the chips belong to the shell and were only ever + hidden because non-plan panels cover them at z-30. + */} + {trTab === 'roadtrip' && rtView === 'list' && ( +
+ +
+ )} + {trTab === 'roadtrip' && rtView === 'map' && ( + + )}
)} - {trTab !== 'plan' && ( + {!MAP_TABS.has(trTab) && (
@@ -411,10 +494,11 @@ export default function MTripShell({ })}
{/* Drop the day filter and show the whole trip (#2257). Map only: the - plan timeline is single-day, so there is nothing to widen there. - Stays mounted while a day is active rather than appearing on - selection, which would shove the rail sideways under the thumb. */} - {view === 'map' && ( + plan timeline and the road trip chain are both single-day, so there is + nothing to widen there. Stays mounted while a day is active rather than + appearing on selection, which would shove the rail sideways under the + thumb. On the road trip map it means the whole drive in its day colours. */} + {mapFront && ( + )} + {trTab === 'dateien' && (
} label={t('common.upload')} onClick={() => setUploadFilesSignal(s => s + 1)} /> @@ -581,13 +696,16 @@ export default function MTripShell({ ) })()} - {trTab === 'plan' ? ( + {/* Same slot, same markup, same icons in both map tabs, so the switch does + not move or change shape when the tab does. The two views stay separate + states: coupling them would drag one tab into the other's half. */} + {MAP_TABS.has(trTab) ? ( - {view === 'plan' ? : } + {mapFront ? : } ) : ( diff --git a/client/src/mobile/screens/trip/dockTabs.test.ts b/client/src/mobile/screens/trip/dockTabs.test.ts new file mode 100644 index 000000000..27ce77f51 --- /dev/null +++ b/client/src/mobile/screens/trip/dockTabs.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from 'vitest' +import { DOCK_CAP, DOCK_PRIORITY, dockTabIds, pickDockTabs } from './dockTabs' + +// FE-MOB-DOCK-001 to FE-MOB-DOCK-008 + +/** Alles, was ein voll ausgestatteter Trip anbieten kann, in der Reihenfolge des Docks. */ +const ALL = ['plan', 'roadtrip', 'transports', 'buchungen', 'finanzplan', 'listen'] + +const ids = (enabled: string[]) => pickDockTabs(new Set(enabled)).map((tab) => tab.id) + +describe('pickDockTabs', () => { + it('FE-MOB-DOCK-001: five seats beside More, so the packing list gives way to the drive', () => { + // Ein sechster Kreis laesst 3px Abstand, auf die kein Daumen zielt. + expect(DOCK_CAP).toBe(5) + expect(ids(ALL)).toEqual(['plan', 'roadtrip', 'transports', 'buchungen', 'finanzplan']) + expect(ids(ALL)).not.toContain('listen') + }) + + it('FE-MOB-DOCK-002: without the road trip the packing list has its seat back', () => { + expect(ids(ALL.filter((id) => id !== 'roadtrip'))).toEqual([ + 'plan', + 'transports', + 'buchungen', + 'finanzplan', + 'listen', + ]) + }) + + it('FE-MOB-DOCK-003: priority decides who is cut, not the order the tabs were enabled', () => { + const scrambled = ['listen', 'finanzplan', 'roadtrip', 'plan'] + expect(ids(scrambled)).toEqual(['plan', 'roadtrip', 'finanzplan', 'listen']) + }) + + it('FE-MOB-DOCK-004: a trip with few sections gets few seats, never padded', () => { + expect(ids(['plan', 'listen'])).toEqual(['plan', 'listen']) + expect(ids([])).toEqual([]) + }) + + it('FE-MOB-DOCK-005: a plugin tab never takes a seat, it belongs in the More sheet', () => { + expect(ids(['plugin:trip-todos', 'plan'])).toEqual(['plan']) + expect(ids(['plugin:trip-todos', 'plugin:weather'])).toEqual([]) + }) + + it('FE-MOB-DOCK-006: a seat is the priority entry itself, icon and all', () => { + // Das Dock zeichnet den Kreis aus tab.icon; eine umgebaute Kopie ohne Icon bliebe leer. + expect(pickDockTabs(new Set(ALL))).toEqual(DOCK_PRIORITY.slice(0, DOCK_CAP)) + expect(pickDockTabs(new Set(ALL))[1]).toBe(DOCK_PRIORITY[1]) + }) +}) + +describe('dockTabIds', () => { + it('FE-MOB-DOCK-007: names exactly the ids that got a seat, so the More sheet leaves them out', () => { + const enabled = new Set(ALL) + expect([...dockTabIds(enabled)]).toEqual(pickDockTabs(enabled).map((tab) => tab.id)) + expect(dockTabIds(enabled).has('listen')).toBe(false) + expect(dockTabIds(enabled).has('roadtrip')).toBe(true) + }) + + it('FE-MOB-DOCK-008: never names more than the dock can hold', () => { + expect(dockTabIds(new Set([...ALL, 'plugin:trip-todos'])).size).toBe(DOCK_CAP) + }) +}) diff --git a/client/src/mobile/screens/trip/dockTabs.ts b/client/src/mobile/screens/trip/dockTabs.ts new file mode 100644 index 000000000..8b30b0add --- /dev/null +++ b/client/src/mobile/screens/trip/dockTabs.ts @@ -0,0 +1,45 @@ +import { Map as MapIcon, TrainFront, Ticket, Wallet, PackageCheck, Route } from 'lucide-react' +import type { LucideIcon } from 'lucide-react' + +/** + * Which trip sections get a seat in the phone dock, and in which order. + * + * The dock is a fixed 62px pill with `justify-around` and no overflow, so seats are + * a real budget, not a preference: at 375px it measures 343px, 315px of it usable, + * and every circle is 42px. Five sections plus More leave 9px between them. A sixth + * takes that down to 3px, which is not a gap any thumb can aim at. + * + * Hence DOCK_CAP. Everything past it surfaces as a tile in the More sheet, which is + * where files, collaboration and plugin tabs have always lived. + * + * This list is the ONE source for both sides. It used to be two hand-kept copies + * (one here, one in MMehrSheet), and extending only one of them showed the same tab + * in the dock AND as a tile. + */ +export const DOCK_PRIORITY: { id: string; icon: LucideIcon }[] = [ + { id: 'plan', icon: MapIcon }, + { id: 'roadtrip', icon: Route }, + { id: 'transports', icon: TrainFront }, + { id: 'buchungen', icon: Ticket }, + { id: 'finanzplan', icon: Wallet }, + { id: 'listen', icon: PackageCheck }, +] + +/** Seats beside the More button. */ +export const DOCK_CAP = 5 + +/** + * The dock's seats for a trip, given the tabs that are actually enabled. + * + * Priority order decides who is cut, not enabled order: with the road trip addon on, + * the packing list moves into the More sheet rather than the drive never getting a + * seat. Turning the addon off puts it straight back. + */ +export function pickDockTabs(enabledTabIds: ReadonlySet): { id: string; icon: LucideIcon }[] { + return DOCK_PRIORITY.filter(tab => enabledTabIds.has(tab.id)).slice(0, DOCK_CAP) +} + +/** The ids that got a seat, for the More sheet to leave out. */ +export function dockTabIds(enabledTabIds: ReadonlySet): Set { + return new Set(pickDockTabs(enabledTabIds).map(tab => tab.id)) +} diff --git a/client/src/mobile/screens/trip/map/MMapArea.tsx b/client/src/mobile/screens/trip/map/MMapArea.tsx index a8c695249..b3d5abea1 100644 --- a/client/src/mobile/screens/trip/map/MMapArea.tsx +++ b/client/src/mobile/screens/trip/map/MMapArea.tsx @@ -1,12 +1,142 @@ -import { useState } from 'react' +import { useCallback, useLayoutEffect, useMemo, useRef, useState, type RefObject } from 'react' import { MapViewAuto } from '../../../../components/Map/MapViewAuto' import { MapCompassPill, type CompassMap } from '../../../../components/Map/MapCompassPill' +import { MAP_LAYER_SWITCHER_INSET, MAP_ROUND_CONTROL_SIZE } from '../../../../components/Map/MapLayerSwitcher' import { TripRouteOverviewPill, TripRouteOverviewPanel } from '../../../../components/Map/TripRouteOverview' import { DawarichTrailPill } from '../../../../components/Map/DawarichTrailPill' import PoiCategoryPill from '../../../../components/Map/PoiCategoryPill' import { usePoiExplore } from '../../../../components/Map/usePoiExplore' +import { useMergedMapPois } from '../../../../components/Map/useMergedMapPois' +import { firstStopOfPlace, stageOf } from '../../../../components/Roadtrip/roadtripRowModel' +import { stageMapData } from '../../../../components/Roadtrip/stageMap' +import { useRoadtripSettings } from '../../../../hooks/useRoadtripSettings' import { useSettingsStore } from '../../../../store/settingsStore' +import { useTripStore } from '../../../../store/tripStore' +import { RT_ALT_BAR_LIFT } from '../roadtrip/useMRtAlternatives' import type { MMapAreaProps } from '../MTripShell' +import type { Poi } from '../../../../components/Map/poiCategories' +import type { ViewportPadding } from '../../../../utils/mapViewport' + +/** One array, so an explore set switched off does not move every pin on the stage. */ +const NO_POIS: Poi[] = [] + +/** + * The compass stands one gap to the right of the base-layer switcher both engines draw + * in the bottom left corner. Worked out from the switcher's own numbers rather than + * written down as 70, so moving or resizing the switcher carries the compass along. + */ +const COMPASS_LEFT = MAP_LAYER_SWITCHER_INSET + MAP_ROUND_CONTROL_SIZE + 8 + +/** The safe-area insets at the top and the bottom of the screen, in pixels. */ +interface SafeInsets { + top: number + bottom: number +} + +const NO_INSETS: SafeInsets = { top: 0, bottom: 0 } + +/** + * The safe-area insets as numbers, read off a probe that is padded by them. + * + * The frame handed to the map engine is pixels, and `env()` only resolves inside CSS. On a + * phone with a notch the chrome sits a status bar lower (and a home indicator higher) than + * its classes spell out, so a frame worked out without the insets would put the far end of + * a leg under the day chips. A computed padding is where the browser hands the resolved + * inset back. Read on mount and again on a resize, which is what turning the phone does. + */ +function useSafeInsets(probe: RefObject): SafeInsets { + const [insets, setInsets] = useState(NO_INSETS) + useLayoutEffect(() => { + const read = () => { + const el = probe.current + if (!el) return + const style = window.getComputedStyle(el) + const top = Number.parseFloat(style.paddingTop) || 0 + const bottom = Number.parseFloat(style.paddingBottom) || 0 + setInsets(prev => (prev.top === top && prev.bottom === bottom ? prev : { top, bottom })) + } + read() + window.addEventListener('resize', read) + return () => window.removeEventListener('resize', read) + }, [probe]) + return insets +} + +/** + * Where the roads offered for a leg are framed: in the strip of map between the day chips + * and the alternatives bar, rather than behind either of them. + * + * Both engines fit a phone with a flat margin that knows nothing of this shell's bars, and + * with the picker open those cover most of the screen: that margin would leave the leg's + * ends and their time pills under the chips and under a 174px bar. The numbers are the + * ones the classes on this screen are built from, so a change there has to be carried here. + * + * Top: the safe area, then `--m-safe-top`'s own 12px, the chip rail's 50px offset under it + * and its 42px height, then a 12px gap so a time pill at the far end is not flush against + * the rail. The search bar that sits below the rail on the stage steps away while the + * picker is open, so the rail is the lowest chrome up there. + * + * Bottom: the safe area, the dock's 74px (62px tall, 12px off the bottom) and the bar's + * lift (its height and the 15px gap between the dock and its foot). That is the very line + * `--bottom-nav-h` puts the round controls' band on, so the frame ends where they begin, + * and they only take the two corners of it. + * + * The sides keep the 20px both engines already give a phone: nothing floats there. + */ +function alternativesFitPadding(insets: SafeInsets): ViewportPadding { + return { + top: insets.top + 12 + 50 + 42 + 12, + right: 20, + bottom: insets.bottom + 74 + RT_ALT_BAR_LIFT, + left: 20, + } +} + +type FocusPoints = readonly [number, number][] + +/** A camera focus the planner is holding, and the day that was on screen when it arrived. */ +interface HeldFocus { + points: FocusPoints + dayId: number | null + live: boolean + /** + * Every array held before this one. Weak, so the offers of a long session are not kept + * alive by it. Only ever added to, and adding twice changes nothing, so a render React + * runs twice or throws away leaves it saying the same thing. + */ + shown: WeakSet +} + +/** + * Lets go of a pending focus once the day moves off the one it arrived with, and never + * takes one back that the planner hands over a second time. + * + * The planner keeps a point it was asked to show until its next routing round, whatever + * day is picked in the meantime, and a pending focus wins over the stage's own frame. So + * after "show on map" every stage swiped to afterwards stayed on that one point instead of + * framing its drive. Coming back to the day does not bring the point back either: the + * traveller has moved on since, and the camera belongs to the stage they came back to. + * + * The same kept point is also what the planner falls back to once the fuel offers or the + * other roads for a leg close, as the very array it handed over before. Read as a new + * focus, closing either one flew the camera back to that old stop, on another day's stage + * too. So only an array never held before is a new focus. The one exception is the open + * picker's roads (`openRoads`): fuel offers asked for over an open picker take the camera + * from it, and once they close the picker is still asking about its leg. + */ +function holdFocus( + prev: HeldFocus, + points: FocusPoints, + dayId: number | null, + openRoads: FocusPoints, +): HeldFocus { + if (prev.points !== points) { + prev.shown.add(prev.points) + return { points, dayId, live: points === openRoads || !prev.shown.has(points), shown: prev.shown } + } + if (prev.live && prev.dayId !== dayId) return { ...prev, dayId, live: false } + return prev +} /** * Fullscreen map layer of the mobile trip screen (plan tab). Stays mounted for @@ -18,14 +148,17 @@ import type { MMapAreaProps } from '../MTripShell' * setting) with the full desktop feature set: clusters, photo/icon markers, * day-order badges, dashed day route, transport overlays per booking, POI * explore markers and long-press → add place. Only the floating chrome is - * mobile: the POI bar spans the full width below the day-chip rail, and the two - * round controls share the band just above the dock — the compass on the left, - * the map's built-in three-state locate button on the right, both riding the - * --bottom-nav-h contract the map already reads so they cannot drift apart. + * mobile: the POI bar spans the full width below the day-chip rail, and the round + * controls share one band above the dock: the map's own base-layer switcher + * with the compass beside it on the left, the map's built-in three-state locate + * button on the right, all riding the --bottom-nav-h contract the map already reads + * so they cannot drift apart. The map credit sits under that band, alone in the + * bottom right corner. * - * Marker data honours the shared places category filter (#1541) because - * planner.mapPlaces is derived from tripStore's placesCategoryFilter — the - * same set the places browser renders, so the two can't desync. + * On the plan tab, marker data honours the shared places category filter (#1541) + * because planner.mapPlaces is derived from tripStore's placesCategoryFilter, the + * same set the places browser renders, so the two can't desync. The road trip + * stage draws the stops of its chain instead, see `stagePlaces`. */ export default function MMapArea({ planner, shell }: MMapAreaProps) { const poi = usePoiExplore() @@ -33,33 +166,209 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) { const poiPillEnabled = useSettingsStore(s => s.settings.map_poi_pill_enabled) !== false const distanceUnit = useSettingsStore(s => s.settings.distance_unit) - const mapActive = shell.view === 'map' + const dayColorsOn = useRoadtripSettings(s => s.roadtrip_day_colors, planner.tripId) + const tripPlaces = useTripStore(s => s.places) + + // One instance, two tabs. `mapFront` is true whenever the map is the front layer + // in either of them, so the floating chrome below keys off that rather than off + // `view`, which only ever meant the plan tab. + const mapActive = shell.mapFront + const onStage = shell.trTab === 'roadtrip' + + // The stage the road trip tab is looking at, and what the map draws for it. Passed + // through unconditionally while that tab is open, list half included: `focusPoints` + // going array → undefined → array is two dependency changes to React, and the + // second one would throw away whatever the traveller had panned to. + // + // Memoised on what the stage is made of rather than rebuilt per render: the shell + // re-renders on every store write, a settings toggle included, and a fresh + // `focusPoints` array reframes the camera while fresh lines and places set their + // GeoJSON sources again. On the stage that also kept the GL style busy, which is how + // the satellite switch came to miss every tap there. + const stage = useMemo( + () => onStage ? stageOf(planner.roadtripRoutes.days, planner.selectedDayId) : null, + [onStage, planner.roadtripRoutes.days, planner.selectedDayId], + ) + const stageMap = useMemo( + () => onStage ? stageMapData(planner.roadtripRoutes, stage, !!dayColorsOn) : null, + [onStage, planner.roadtripRoutes, stage, dayColorsOn], + ) + + // Only what the stage carries, so a trip's other 200 pins stay off a screen that + // is answering one question. Without a stage (the all-days view) every place a stored + // visit stops at comes back, which is what the drive looks like end to end. + // + // Out of the trip store rather than `planner.mapPlaces`, which is the plan tab's map. + // That list drops the pins of every day its declutter has put away, and this tab moves + // the day without touching the declutter (a swipe, or a chip tap while the plan tab sits + // on its list): after the all days switch and back, the next stage picked came up with + // most of its pins missing. It also runs the places browser's filters, where 'unplanned' + // hides every stop a drive has, and it lacks the service stops hidden from the day lists + // that the chain still draws. The category filter stays off the stage too, on purpose: + // the stage is one day's chain on a map, and a stop the chain lists with no pin under its + // line, hidden by a control on another tab, reads as a broken map rather than a filter. + // + // The all-days view reads the stored visits for the same reasons, not the planner's + // planned list: that one is built from the day lists, which on a phone always leave out + // a booked night and, with the setting off, the service stops, while the drive the routing + // round draws still ends at that hotel and stops at that pump. Its pin is what opens the + // stop, so a missing one left the stop out of reach from this view. + const drivePlaceIds = useMemo( + () => new Set(Object.values(planner.storedAssignments).flat().map(visit => visit.place_id)), + [planner.storedAssignments], + ) + const stagePlaces = useMemo(() => { + const pinned = stageMap && stage ? stageMap.placeIds : drivePlaceIds + return tripPlaces.filter(p => p.lat != null && p.lng != null && pinned.has(p.id)) + }, [stageMap, stage, tripPlaces, drivePlaceIds]) + + // Computed during render rather than in an effect, so the frame handed over below is + // already the right one in the render a day change happens in. See holdFocus. + const [heldFocus, setHeldFocus] = useState( + () => ({ points: planner.mapFocusPoints, dayId: planner.selectedDayId, live: true, shown: new WeakSet() }), + ) + const focus = holdFocus(heldFocus, planner.mapFocusPoints, planner.selectedDayId, planner.alternativeFocusPoints) + if (focus !== heldFocus) setHeldFocus(focus) + const focusPending = focus.live && planner.mapFocusPoints.length > 0 + + // Handed over only once there are roads to frame, not as soon as the picker opens: the + // engines refit whatever they hold when this padding changes, and while the router is + // still thinking that is the stage, which would be flown out to a smaller frame just + // before the answer flies it to the leg. So the padding and the roads arrive in one + // render and the camera moves once, and on close both go in one render as well. + // Memoised for the reason the stage data is, the shell re-rendering on every store write. + const insetProbe = useRef(null) + const insets = useSafeInsets(insetProbe) + const framingOffers = onStage && planner.alternativeOverlays.length > 0 + const fitPadding = useMemo( + () => (framingOffers ? alternativesFitPadding(insets) : undefined), + [framingOffers, insets], + ) + + /** + * A pin on the road trip tab opens its stop: the sheet the chain row opens, not the + * place inspector. + * + * The plan tab's marker click moves the planner's place selection, and the inspector + * opens off that selection, so a tap on a stop of the drive came up with the plan tab's + * card over the map and no word about the stop. Over a stage the stop is found on that + * card, over the whole drive on the first routed day that stops there (firstStopOfPlace). + * A pin no routed day stops at still gets the inspector: the road trip has nothing to + * say about it, and the place does. + * + * One handler for the life of the map, reading the latest values through a ref. Leaflet + * rebuilds every marker whenever this identity moves, and the shell re-renders on every + * store write and on every sheet it opens, this handler's own included. + */ + const latest = useRef({ planner, shell, stage }) + latest.current = { planner, shell, stage } + const openStagePin = useCallback((placeId?: number) => { + const { planner: now, shell: chrome, stage: card } = latest.current + const stop = placeId == null ? null : firstStopOfPlace(card ? [card] : now.roadtripRoutes.days, placeId) + if (stop) chrome.openSheet('rtstop', { dayId: stop.ownerDayId, assignmentId: stop.assignmentId }) + else now.handleMarkerClick(placeId) + }, []) + + /** + * The pins, and they are not the same question on the two tabs. + * + * On the stage: what the corridor search found and what the fuel search is offering, + * both measured along the drive. The explore categories stay off it, and so does their + * bar. "What is around this piece of map" has no relationship to a route, and two + * search bars stacked over a 375px map is the clutter this tab exists to avoid. The + * plan tab is one tap away and shows the same map. + * + * Merged through the planner's own hook rather than concatenated here, because the + * sets overlap: the same petrol station found twice would be two pins on one roof. + */ + /** + * The vias the phone map draws: on a stage, only the night that belongs to it. + * + * A night pause is a pill with a moon and a day number, drawn where one travel day + * ends. The markers are built from the WHOLE drive (`automaticPoints`), which is right + * for the desktop rail and for the all-days view here, but a stage shows one day: with + * the unfiltered list, day 1 carried day 2's pill as well, in the middle of a map that + * is otherwise entirely day 1. Two ends on a map that draws one is a question, not a + * label. + * + * So on a stage the pill is kept only where its day is the day on screen, and off a + * stage the list is left alone, because in the all-days view every night does belong to + * a line that is drawn. `nightPause.day` is the day number the marker was built from + * (see `useAutomaticDayPoints`), which is the same number the stage carries. + */ + const mapVias = useMemo(() => { + const vias = onStage ? planner.roadtripMapVias : planner.routeVias + if (!vias || !stage) return vias + return vias.filter(v => !v.nightPause || v.nightPause.day === stage.dayNumber) + }, [onStage, planner.roadtripMapVias, planner.routeVias, stage]) + + const pois = useMergedMapPois( + onStage ? planner.roadtripCorridor.visible : null, + onStage ? NO_POIS : poi.pois, + planner.refuel.offered, + ) return ( // `isolate` keeps the map's internal z-indexes (Leaflet panes, the z-1000 // locate button) inside this layer so they can never paint over the plan // timeline (z-10) or the browse/tab overlays (z-30) above it. - // The dock is 62px tall at safe-bottom + 12, so a 74px --bottom-nav-h puts - // the round controls (which add their own 12px) a dock's gap above it — - // close enough to the thumb to reach one-handed, clear of the dock itself. -
+ // + // --m-map-floor is the top edge of whatever the map ends at: the dock, 62px tall at + // safe-bottom + 12, or the alternatives bar when the picker puts one over it, which is + // what --m-stage-lift adds. The round controls sit straight on that floor and add + // their own 12px, close enough to the thumb to reach one-handed. Everything that reads + // --bottom-nav-h (the compass, both engines' locate button and base-layer switcher, + // the overview stack) follows on its own. The band used to float a further 38px up to + // leave the corner under it to the map credit; the phone map carries no visible credit + // any more (see mobile.css), so that row would now only be a gap over the dock. + // + // The metrics are classes rather than an inline --bottom-nav-h, and the lift is its + // OWN variable folded into them: the compass band below is identified by being the + // one element that sets that name inline, and a second one would make that ambiguous. +
+ {/* Measures the safe area for the alternatives frame, see useSafeInsets. Out of the + flow and invisible, so it takes no room and catches no tap. */} +