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 (
+
+ )
+}
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) */}
-
{/* 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({
{/* 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 ? (
-
+ onAccept(poi)}
- aria-label={t(electric ? 'roadtrip.refuel.addElectric' : 'roadtrip.refuel.add', { name: poi.name })}
+ aria-label={t(words.add, { name: poi.name })}
className="grid h-[22px] w-[22px] shrink-0 place-items-center rounded-lg bg-surface-secondary text-content-secondary transition-colors hover:bg-accent hover:text-accent-text focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
@@ -648,18 +645,15 @@ function RefuelBand({ dry, refuel, dayId, onAsk, 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 && {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 (
{
+ // Vitest runs with the client package as its root, so cwd is stable here.
+ const css = readFileSync(resolve(process.cwd(), 'src/mobile/mobile.css'), 'utf8')
+
+ /**
+ * Every rule in the sheet as its selector list and its declarations, comments dropped.
+ * Parsed rather than found by substring, because a vendor class name also appears in the
+ * prose above the rules.
+ */
+ const rules = css
+ .replace(/\/\*[\s\S]*?\*\//g, '')
+ .split('}')
+ .filter(chunk => chunk.includes('{'))
+ .map(chunk => {
+ const open = chunk.lastIndexOf('{')
+ const head = chunk.slice(0, open)
+ return {
+ selectors: head.slice(head.lastIndexOf('{') + 1).split(',').map(s => s.trim()),
+ body: chunk.slice(open + 1),
+ }
+ })
+ /** The rules whose selector list names this selector. */
+ const rulesFor = (selector: string) => rules.filter(rule => rule.selectors.includes(selector))
+
+ it('FE-MOB-CREDITCSS-001: both engines and both corners are hidden by one rule', () => {
+ const hidden = rulesFor('.m-root .leaflet-control-attribution')
+
+ expect(hidden).toHaveLength(1)
+ expect(hidden[0].body).toMatch(/display:\s*none;/)
+ // One rule for all of them, so Leaflet, MapLibre and Mapbox cannot drift apart, and so
+ // the credit cannot come back on the one engine nobody happened to open.
+ for (const selector of [
+ '.m-root .maplibregl-ctrl-bottom-left',
+ '.m-root .mapboxgl-ctrl-bottom-left',
+ '.m-root .maplibregl-ctrl-bottom-right',
+ '.m-root .mapboxgl-ctrl-bottom-right',
+ ]) {
+ expect(hidden[0].selectors).toContain(selector)
+ }
+ })
+
+ it('FE-MOB-CREDITCSS-002: nothing else in the sheet places a credit', () => {
+ // The hiding rule is the last word only while no later rule moves one of these
+ // containers back into view. Both corners, because the GL wordmark sits in the left one.
+ const placed = rules.filter(rule => rule.selectors.some(s => /ctrl-bottom-(left|right)|leaflet-control-attribution/.test(s)))
+
+ expect(placed).toHaveLength(1)
+ expect(placed[0].body).toMatch(/display:\s*none;/)
+ })
+
+ it('FE-MOB-CREDITCSS-003: the credit corner and its variables are gone with it', () => {
+ // `m-credit-corner` was the trip map's own credit slot, `m-attrib-open` the class the
+ // Leaflet (i) toggled. Both are dead now; a leftover rule would place an element that
+ // no longer exists and read as if the credit were still somewhere on screen.
+ expect(css).not.toContain('m-credit-corner')
+ expect(css).not.toContain('m-attrib-open')
+ expect(css).not.toContain('--m-credit')
+ })
+
+ it('FE-MOB-CREDITCSS-004: the phone map is the only thing this touches', () => {
+ // Every selector is under `.m-root`, the phone shell. The desktop map keeps its full
+ // credit with its links, which is where it belongs.
+ const hidden = rulesFor('.m-root .leaflet-control-attribution')
+
+ for (const selector of hidden[0].selectors) expect(selector.startsWith('.m-root ')).toBe(true)
+ })
+})
diff --git a/client/src/mobile/screens/journey/MJourneyDetail.tsx b/client/src/mobile/screens/journey/MJourneyDetail.tsx
index 3ca4485a8..e0a707cc7 100644
--- a/client/src/mobile/screens/journey/MJourneyDetail.tsx
+++ b/client/src/mobile/screens/journey/MJourneyDetail.tsx
@@ -204,8 +204,31 @@ export default function MJourneyDetail() {
const [pickerProvider, setPickerProvider] = useState(null)
const dawarichEnabled = useAddonStore(state => state.isEnabled)('dawarich')
const [dawarichOpen, setDawarichOpen] = useState(false)
+ /**
+ * How tall the card rail over the dock currently is.
+ *
+ * Measured rather than written down: the rail is a day scrubber over a row of covers,
+ * and a cover grows from 152 to 180px when it becomes the active one. The Dawarich
+ * button above it used to clear a hard-coded 128px, which was short of the rail on any
+ * screen and left the button sitting over the cards. Zero while there is no rail, which
+ * is also the empty-journal case, and the button then sits straight above the dock.
+ */
+ const [railHeight, setRailHeight] = useState(0)
+ const railRef = useRef(null)
const [uploading, setUploading] = useState(false)
+ useEffect(() => {
+ const node = railRef.current
+ if (!node) { setRailHeight(0); return }
+ // Observed rather than read once: the rail changes height when the active card grows,
+ // and a height read at mount would be the wrong one from the first swipe onwards.
+ if (typeof ResizeObserver === 'undefined') { setRailHeight(node.offsetHeight); return }
+ const observer = new ResizeObserver(() => setRailHeight(node.offsetHeight))
+ observer.observe(node)
+ setRailHeight(node.offsetHeight)
+ return () => observer.disconnect()
+ }, [view, entries.length])
+
const openUpload = useCallback(() => {
if (availableProviders.length > 0) setShowUploadMenu(true)
else galleryFileRef.current?.click()
@@ -450,7 +473,10 @@ export default function MJourneyDetail() {
type="button"
onClick={() => setDawarichOpen(true)}
aria-label={t('dawarich.suggestions.title')}
- className="absolute right-4 z-[9] flex h-[46px] w-[46px] items-center justify-center overflow-hidden rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-sheet)] shadow-[0_6px_18px_-8px_rgba(0,0,0,.35)] bottom-[calc(var(--bottom-nav-h,84px)+16px+128px)]"
+ className="absolute right-4 z-[9] flex h-[46px] w-[46px] items-center justify-center overflow-hidden rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-sheet)] shadow-[0_6px_18px_-8px_rgba(0,0,0,.35)]"
+ // The rail's own offset over the dock, its measured height, then a gap. The 128px
+ // this used to guess at was short of the rail, so the button lay on the cards.
+ style={{ bottom: `calc(var(--bottom-nav-h, 84px) + 2px + ${railHeight}px + 12px)` }}
>
@@ -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) && (
)}
+ {/*
+ 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' && (
+
@@ -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 && (
)}
+ {/* The stage's own header: the day it shows, and a way into the figures
+ behind it. A button rather than the plugin tabs' inert pill, because it
+ is the only entry to the driving settings, and the right slot belongs to
+ the list ⇄ map switch, same as in the plan tab.
+
+ The day and the distance are badges rather than one line joined with a
+ dot, so each reads as a figure of its own. Both stay neutral: the active
+ day chip right below is already the filled pill with the same label, and
+ a second one here would compete with it. The button names itself, because
+ a screen reader runs the texts of pills side by side together. */}
+ {trTab === 'roadtrip' && (
+ openSheet('rtinfo')}
+ aria-label={rtHeaderLabel || undefined}
+ className="absolute left-[52px] right-[52px] top-1/2 mx-auto flex h-[34px] w-fit max-w-full -translate-y-1/2 items-center gap-[5px] rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] px-[10px] backdrop-blur-[24px] backdrop-saturate-[1.7]"
+ >
+
+ {rtHeaderLabel ? (
+ <>
+ {rtHeaderDay && {rtHeaderDay}}
+ {/* Unit symbols keep their case: m and M are different units. */}
+ {rtHeaderDistance && {rtHeaderDistance}}
+ >
+ ) : (
+ {t('roadtrip.title')}
+ )}
+
+
+ )}
+
{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. */}
+
shell.openSheet('transport', { reservationId: rid })}
- pois={poi.pois}
- onPoiClick={marker => planner.openAddPlaceFromPoi(marker, planner.selectedDayId)}
+ pois={pois}
+ // On the stage, through the road trip's own door: it recognises a corridor hit by
+ // the distance it carries and sends it to the draft sheet with the stop kind, the
+ // stay and the position in the chain already worked out. The plan tab has no
+ // chain to place anything in, so there it stays the plain place form.
+ onPoiClick={onStage
+ ? planner.handlePoiClick
+ : marker => planner.openAddPlaceFromPoi(marker, planner.selectedDayId)}
onViewportChange={poi.onViewportChange}
onMapReady={setGlMap}
+ // Other ways of driving the leg the stage asked about, and the one lit up.
+ alternativeRoutes={onStage ? planner.alternativeOverlays : undefined}
+ activeAlternative={onStage ? planner.highlightedAlternative : undefined}
+ // A tap on a road or its time pill only lights it; the bar's confirm takes it. The
+ // desk hands `chooseRouteAlternative` in here and previews on hover, but glass has
+ // no hover, so the same wiring would save a via on the very first touch of a line.
+ // No highlight handler either: a touch fires emulated mouse enter and leave events,
+ // and the leave would put out the road the tap has just lit.
+ onChooseAlternative={onStage ? planner.setHighlightedAlternative : undefined}
+ fitPadding={fitPadding}
/>
{/* Floating map chrome — only while the map view is front-most. The POI bar
sits below the day-chip rail (safe-top + 50px + ~42px chip height) and
takes the full width between the screen margins, so its segments are
the same size as everything else the thumb aims at on this screen. */}
- {mapActive && poiPillEnabled && (
+ {mapActive && !onStage && poiPillEnabled && (
)}
- {/* Compass — GL maps only (Leaflet can't rotate). Bottom-left, mirroring
- the locate button's own `right: 12` off the same --bottom-nav-h, so the
- two round controls always sit on one line. Leaflet has no compass but
- puts its base-layer switcher in the same corner, so the band reads the
- same either way. */}
+ {/* Compass, GL maps only (Leaflet cannot rotate). Both engines draw the base-layer
+ switcher in the bottom left corner, so the compass sits beside it rather than in
+ the corner: at `left-3` it started 8px left of the switcher and ran on under it,
+ reading as a second button showing through the frosted shell. Same
+ --bottom-nav-h band as the locate button's `right: 12`, so the round controls
+ still share one line. The left offset is inline because it is computed from the
+ switcher's own numbers. */}
{mapActive && glMap && (
-
+
)}
{/* Whole-trip overview (#1736): the stages stack above their toggle on the right,
- clear of the round-controls band below it and of the compass and Leaflet's
- base-layer switcher, which both sit in the bottom-LEFT corner. The offset is
- Tailwind rather than inline because the compass band is identified by being
- the one element with an inline --bottom-nav-h, and a second would make that
- ambiguous. */}
- {mapActive && (!planner.roadtripActive || planner.dawarichEnabled) && (
+ clear of the round-controls band below it and of the base-layer switcher and
+ the compass, which both sit bottom left. The offset is Tailwind rather than
+ inline because the compass band is identified by being the one element with
+ an inline --bottom-nav-h, and a second would make that ambiguous. */}
+ {mapActive && !onStage && (!planner.roadtripActive || planner.dawarichEnabled) && (
{!planner.roadtripActive && planner.overviewActive && (
void }) {
+ const kind = row.stop.stopType ? STOP_KIND_BY_KEY[row.stop.stopType] : undefined
+ const face = row.service && kind
+ ? (
+
+
+
+ )
+ : (
+ // Deliberately not font-geist: `.m-root .font-geist` caps the tier at Medium,
+ // which would quietly undo the bold on a number that has to read at 12px.
+
+ {row.number}
+
+ )
+
+ if (!onPickKind) return face
+ return (
+ { e.stopPropagation(); onPickKind() }}
+ onKeyDown={e => { e.stopPropagation() }}
+ className="grid place-items-center rounded-full"
+ >
+ {face}
+
+ )
+}
+
+function Mark({ icon, children, tone }: { icon: ReactNode; children: ReactNode; tone?: 'warn' }) {
+ return (
+
+ {icon}
+ {children}
+
+ )
+}
+
+/** The short form of a finding: the number only, the sentence waits in the sheet. */
+function warningMark(warning: ScheduleWarning, chrome: RowChrome): ReactNode {
+ const { t, unit } = chrome
+ if (warning.code === 'late') {
+ return }>{`+${warning.minutes ?? 0} min`}
+ }
+ if (warning.code === 'range') {
+ return }>{formatDistance(warning.sinceKm ?? 0, unit)}
+ }
+ if (warning.code === 'leg') {
+ return }>{formatDurationShort((warning.overMinutes ?? 0) * 60)}
+ }
+ return }>{t('roadtrip.warn.overnight')}
+}
+
+/**
+ * A stop of the stage. The whole row is the tap target, at least 46px tall, which is
+ * why it is a div with role rather than a button: the desktop needs controls nested
+ * inside its row, and a button inside a button is not markup.
+ */
+export function RtStopRow({ row, chrome, onOpen, onPickKind }: {
+ row: StopRow
+ chrome: RowChrome
+ onOpen: () => void
+ /** Absent for a traveller who may not edit places: the disc is then not a control. */
+ onPickKind?: () => void
+}) {
+ const { t, unit } = chrome
+ const marks: ReactNode[] = []
+ if (row.dwellMinutes) {
+ marks.push(
+ }>{formatDurationShort(row.dwellMinutes * 60)},
+ )
+ }
+ if (row.warning) marks.push({warningMark(row.warning, chrome)})
+ if (!marks.length && row.offRoadMeters) {
+ marks.push(
+ }>
+ {formatDistance(row.offRoadMeters / 1000, unit)}
+ ,
+ )
+ }
+
+ return (
+
{ if (e.target === e.currentTarget && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); onOpen() } }}
+ className="grid cursor-pointer items-center gap-x-[10px] py-1" style={{ gridTemplateColumns: '34px 1fr auto' }}
+ >
+
+
+
+ {row.stop.name}
+
+ {marks.length > 0 && {marks}}
+
+ {row.time && (
+ // dir=ltr so a clock reads the same way round in an RTL locale.
+
+ {row.pinned && }
+ {row.time}
+
+ )}
+
+ )
+}
+
+const LEG_ICONS: Record = {
+ walking: Footprints,
+ cycling: Bike,
+}
+
+/**
+ * What a leg pill says: how far and how long, or that it is not routed yet.
+ *
+ * A segment carries both a pre-formatted text and the raw metres and seconds, and the two
+ * do not always arrive together: a segment that reaches the chain before its routing round
+ * has landed has the numbers at zero and the texts empty. Reading only the texts printed
+ * the template with nothing in its slots, so a leg showed as a bare " in " (the
+ * separator of `roadtrip.leg.driveText` with both values missing) — the screenshot is a
+ * hotel followed by a pill saying nothing.
+ *
+ * So the text is used when there is one and the numbers are formatted when there is not,
+ * which is what the desktop rail does with the same segment. With neither, the leg says
+ * it is pending, the honest answer and the one the missing-segment case already gave.
+ */
+function legText(seg: RouteSegment | undefined, { t, unit }: RowChrome): string {
+ if (!seg) return t('roadtrip.leg.pending')
+ const metres = Number.isFinite(seg.distance) ? seg.distance : 0
+ const seconds = Number.isFinite(seg.duration) ? seg.duration : 0
+ const distance = seg.distanceText || (metres > 0 ? formatDistance(metres / 1000, unit) : '')
+ const time = seg.durationText || seg.drivingText || (seconds > 0 ? formatDurationShort(seconds) : '')
+ if (!distance || !time) return t('roadtrip.leg.pending')
+ return t('roadtrip.leg.driveText', { distance, time })
+}
+
+/**
+ * The drive between two stops. 12px rather than the desktop's 10: a four-hour leg
+ * deserves the space it takes.
+ *
+ * Other ways of driving it are asked for with one 40px round button at the end of the
+ * row, never with the whole band as on the desktop rail. The chain scrolls under a thumb,
+ * and with a band-wide target the tap that only meant to stop that scroll, landing on a
+ * leg, would cost up to five routing requests and a jump to the map. So the pill stays a
+ * line of text, and the button is the one thing on the row that acts: a small, separate
+ * target that keeps that cost behind a gesture nobody makes by accident.
+ *
+ * Open, the button takes the inner surface and the full ink rather than filling with the
+ * action colour, for the reason the rail gives: a filled chip in a column of quiet rows
+ * reads as a button that was pressed and stuck. Offline it keeps its place but dims,
+ * because a choice is saved as a via and vias are online only. Without `onAlternatives`
+ * (no permission, or a leg that cannot be rerouted) the column stays empty.
+ */
+export function RtLegRow({ seg, mode, chrome, onAlternatives, alternativesOpen = false, alternativesDisabled = false }: {
+ seg: RouteSegment | undefined
+ mode: string | null
+ chrome: RowChrome
+ /** Asks for other ways of driving this leg. Absent means the leg offers none. */
+ onAlternatives?: () => void
+ /** True while the picker is open on this leg. */
+ alternativesOpen?: boolean
+ alternativesDisabled?: boolean
+}) {
+ const { t } = chrome
+ const Icon = mode && LEG_ICONS[mode] ? LEG_ICONS[mode] : mode?.startsWith('plugin:') ? Zap : CarFront
+ const text = legText(seg, chrome)
+ return (
+
+ {/* flex-col, not flex: in a row the dashes would stretch sideways and read as
+ a barcode. --m-conn rather than --m-rowbr, because the row hairline is 4.5%
+ alpha and disappears in sunlight, and this line is what says "you drive here". */}
+
+
+
+
+
+ {text}
+
+ {onAlternatives ? (
+
+
+
+ ) : (
+
+ )}
+
+ )
+}
+
+/**
+ * The ground the dry band stands on, where the mascot is.
+ *
+ * Opaque on purpose: the mascot cuts its eyes and wheel hubs out in `--m-bg`, and
+ * `--m-card` is 55% alpha in both themes, so on the card's own ground the red body would
+ * show through the eyes. `--m-sheetop` is the phone's opaque surface. Mixed against that
+ * rather than against `--m-bg`, because the mascot's span renames `--m-bg` to this value
+ * and a variable defined in terms of itself is invalid, which would drop the cutouts.
+ */
+const DRY_GROUND = 'color-mix(in srgb, var(--m-st-danger) 11%, var(--m-sheetop))'
+
+/**
+ * The lamp's circle: a soft wash of the band's own colour rather than the black action
+ * fill. The lamp is a warning light that happens to be pressable, and the 44px circle is
+ * what tells a thumb so without turning it into the loudest thing on the screen.
+ */
+const DANGER_SOFT: CSSProperties = {
+ background: 'color-mix(in srgb, var(--m-st-danger) 14%, transparent)',
+ color: 'var(--m-st-danger)',
+}
+
+/**
+ * Where the tank runs out on this leg, and the reserve lamp that goes looking.
+ *
+ * The desktop band's design, sized for a thumb: the mascot on its skateboard and not
+ * enjoying it, a small uppercase warning, and the lamp itself as the button. Not a pill
+ * with the words on it, because a labelled pill beside a mascot and a title leaves the
+ * title almost no room: the band's content box is only about
+ * 299px wide at 375px and 284px at 360px, and a label like "Cerca un punt de recàrrega"
+ * is a long way into that. So the lamp is the button, as on the desktop, and its words
+ * live in the label a screen reader announces.
+ *
+ * 44px where the desktop lamp is 22px, because it is aimed with a thumb. The title clamps
+ * to two lines instead of truncating, because a warning that loses its end says nothing
+ * ("Qui il serbatoio si esaurisce" does not fit on one). Offline the lamp stops glowing,
+ * because a lamp that glows invites a press that cannot work. Somebody who may not edit
+ * the day still sees the lamp, as a plain mark: the empty tank is information, not an
+ * action.
+ *
+ * While a search runs or its offers show, the lamp steps aside for a close, and an empty
+ * answer leaves a retry in its place. The close matters because the map draws the offers,
+ * and without it nothing in the band could clear those pins short of accepting one. It
+ * stays while offline too, and the offline sentence stands down with it: closing is local,
+ * so there is no dead control left to explain. Which control shows, which offers and which
+ * empty sentence is decided in `refuelBandState`, the same place the desktop band reads
+ * it from.
+ */
+export function RtDryRow({ intoLegKm, chrome, electric, onSearch, offline, refuel, dayId, legIndex, onAccept }: {
+ intoLegKm: number
+ chrome: RowChrome
+ electric: boolean
+ onSearch?: () => void
+ offline: boolean
+ refuel: RefuelSearch
+ dayId: number
+ legIndex: number
+ /** Takes one of the offers onto the trip. Absent for somebody who may not edit days. */
+ onAccept?: (poi: RefuelCandidate) => void
+}) {
+ const { t, unit } = chrome
+ const band = refuelBandState(refuel, dayId, legIndex)
+ const words = REFUEL_WORDS[electric ? 'electric' : 'fuel']
+ const Lamp = electric ? Zap : Fuel
+ return (
+
+
+ {/* Renamed on this span only, never on the band: the offers below are drawn in
+ --m-ink too, and they have to stay ink. Not a tap target either: the lamp at
+ the end of this line is its one control, and a mascot that reacted too would
+ be a second one that looks like none. */}
+
+ {/* Out of fuel is a thing that happens to the drive, so it is the mascot with
+ the vehicle, and it is not enjoying it. */}
+
+
+
+
+ {t(words.dry)}
+
+
+ {t('roadtrip.refuel.after', { distance: formatDistance(Math.round(intoLegKm), unit) })}
+
+
+ {band.control === 'close' ? (
+
+
+
+ ) : onSearch ? (
+
+ {band.control === 'again'
+ ?
+ : }
+
+ ) : (
+
+
+
+ )}
+
+
+ {/* Blunt rather than silent: the lamp keeps its place and this says why it is out. */}
+ {onSearch && offline && band.control !== 'close' && (
+ {t('mobileTrip.rtSearchOffline')}
+ )}
+
+ {band.loading && (
+ {t('roadtrip.refuel.looking')}
+ )}
+
+ {/* The answer, in the band that asked. The desktop puts it in the rail row for the
+ same reason: a station offered somewhere other than where the tank runs out is
+ an offer somebody has to go and find. */}
+ {band.offers.length > 0 && (
+
+ )}
+
+ {/* Three sentences for three different facts. "Nothing on this stretch" after a
+ request that failed states something that was never checked. */}
+ {band.empty && (
+ {t(REFUEL_EMPTY_KEY[band.empty])}
+ )}
+
+ )
+}
+
+/**
+ * One station on offer: what it is, the two figures that decide it, and a 38px plus.
+ *
+ * The detour is what the list is sorted by, because everything in it is reachable
+ * already and what separates them is what the stop costs. What is left in the tank when
+ * the car draws level comes second, with that detour counted in. Both as plain labelled
+ * figures rather than the desktop's icon badges: a tooltip is the desktop's way of
+ * saying which number is which, and there is no hover here to carry it.
+ */
+function RefuelOffer({ poi, chrome, electric, onAccept }: {
+ poi: RefuelCandidate
+ chrome: RowChrome
+ electric: boolean
+ onAccept?: () => void
+}) {
+ const { t, unit } = chrome
+ const kind = STOP_KIND_BY_KEY[poi.category]
+ const KindIcon = kind?.Icon ?? Fuel
+ return (
+
+ )
+}
+
+/**
+ * A night drive crossing into this card.
+ *
+ * The only place a stage shows stops that belong to another day. Without it the
+ * traveller counts wrong at a night crossing, because the card opens with stops it
+ * does not own.
+ */
+export function RtSpillRow({ fromDayNumber, departs, chrome, children }: {
+ fromDayNumber: number
+ departs: string | null
+ chrome: RowChrome
+ children?: ReactNode
+}) {
+ const { t } = chrome
+ return (
+
+ )
+}
diff --git a/client/src/mobile/screens/trip/roadtrip/MRoadtripTab.tsx b/client/src/mobile/screens/trip/roadtrip/MRoadtripTab.tsx
new file mode 100644
index 000000000..c3314e1e7
--- /dev/null
+++ b/client/src/mobile/screens/trip/roadtrip/MRoadtripTab.tsx
@@ -0,0 +1,390 @@
+import { useRef } from 'react'
+import { AlertTriangle, MapPin, Navigation } from 'lucide-react'
+import { useMPlanDaySwipe } from '../plan/useMPlanDaySwipe'
+import { showStopOnMap, useMRoadtrip } from './useMRoadtrip'
+import { useMRtCorridor } from './useMRtCorridor'
+import { useMRtAlternatives } from './useMRtAlternatives'
+import MRtCorridorBar from './MRtCorridorBar'
+import MRtAlternativesBar from './MRtAlternativesBar'
+import { RtAutoRow, RtDryRow, RtLegRow, RtSpillRow, RtStopRow, type RowChrome } from './MRoadtripRows'
+import MBadge from '../../../components/MBadge'
+import MDancingTrek from '../../../components/MDancingTrek'
+import { formatDurationShort } from '../../../../components/Roadtrip/roadtripModel'
+import { getNavigationTargets } from '../../../../components/Planner/placeNavigation'
+import { useSettingsStore } from '../../../../store/settingsStore'
+import { formatDistance } from '../../../../utils/units'
+import { isRtlLanguage } from '../../../../i18n'
+import type { MTripTabPanelProps } from '../MTripShell'
+import { legReroutable, type StopRow } from '../../../../components/Roadtrip/roadtripRowModel'
+
+/**
+ * The road trip tab: one day of the drive, as a chain or on the map.
+ *
+ * Both halves are this one component because they share a stage, and the switch
+ * between them must not lose it. The map itself is not here: it is the shell's single
+ * instance, shared with the plan tab and lying underneath, so the map half of this
+ * screen is nothing but the stage bar floating over it.
+ *
+ * The stage picker is the shell's day-chip rail. This panel renders at z-20, below the
+ * chips at z-25, which is the whole of that: the chips were always mounted and only
+ * ever hidden because the other tabs cover them at z-30. With them come the auto
+ * scroll, the day tints, the label format and the second tap that opens the day sheet.
+ */
+export default function MRoadtripTab({ planner, shell }: MTripTabPanelProps) {
+ const { t, days } = planner
+ const panelRef = useRef(null)
+ const cardRef = useRef(null)
+ const rt = useMRoadtrip(planner)
+ const corridor = useMRtCorridor(planner, shell)
+ // Called once here and handed down, like `rt`: the chain's leg buttons and the bar over
+ // the map read one controller, so a leg shows pressed for exactly the picker on the map.
+ const alts = useMRtAlternatives(planner, shell)
+ const unit = useSettingsStore(s => s.settings.distance_unit)
+ const chrome: RowChrome = { t, unit }
+
+ // The same gesture the day timeline uses, called rather than rebuilt: 370 lines of
+ // worked-out conflict avoidance, down to the dead 24px gutter that stops iOS from
+ // reading a swipe as its own back gesture.
+ const daySwipe = useMPlanDaySwipe({
+ days,
+ selectedDayId: planner.selectedDayId,
+ // skipFit: the map underneath stays mounted, and the stage's own focus points
+ // frame it as soon as the selection moves.
+ onSelectDay: dayId => planner.handleSelectDay(dayId, true),
+ panelRef,
+ cardRef,
+ editing: false,
+ dragging: false,
+ menuOpen: !!shell.sheet,
+ rtl: isRtlLanguage(planner.language),
+ describeDay: (i, n) => t('mobileTrip.dayAnnounce', { current: i + 1, total: n }),
+ })
+
+ const stage = rt.stage
+
+ // The disc is only a control for somebody who may change a place. Read here rather than
+ // inside the row so the whole chain asks once, the way `rt` and `chrome` are handled.
+ const canEditPlaces = planner.can('place_edit', planner.trip)
+
+ const openStop = (row: StopRow) => {
+ shell.openSheet('rtstop', { dayId: row.stop.ownerDayId, assignmentId: row.stop.assignmentId })
+ }
+
+ // The search bar sits in the same band on both halves, at the same offset, so the
+ // list/map switch never moves it: it is one stage seen two ways, and a control that
+ // jumps between them is a control you have to find twice. The band and the margins
+ // are the plan tab's POI bar, for the same reason.
+ //
+ // Only over a stage. Without one there is no drive to search along: the corridor would
+ // fall back to the trip's first routed day, which is not the one on screen, and every
+ // distance it answered with would be measured against a road nobody is looking at.
+ const searchBar = stage && (
+
+ shell.openSheet('rtsearch')} />
+
+ )
+
+ // ── Map half: the search bar, and the picker's bar while it is open. Everything
+ // between them belongs to the map instance the shell keeps mounted, so this layer must
+ // not swallow taps.
+ //
+ // A stage bar used to stand over the dock whenever the map was up: the day's
+ // destination with its picture, its stop count, its arrival and its distance. It went
+ // because the day and the distance are already in the shell's stage header, and on a
+ // map that fills the screen a permanent card over the bottom edge costs more than the
+ // three facts it added.
+ //
+ // While other ways of driving a leg are on offer, their bar stands in that now empty
+ // slot and the search bar steps away. The picker is modal on the map: its lines are the
+ // question on screen, a corridor search started under it would draw its pins over
+ // them, and the band it frees at the top is room the leg is framed into.
+ if (shell.rtView === 'map') {
+ return (
+
+ {!alts.open && searchBar}
+ {/* Just above the dock, the same gap everything else on this shell keeps from it.
+ Mounted only while the picker is open, so nothing invisible lies over the map's
+ own buttons the rest of the time. */}
+ {alts.open && (
+
+ {rt.empty || !stage ? (
+
+ ) : (
+ <>
+ {/* Head card: a header over the chain rather than a third of it. The day's
+ facts ride on the date line as badges instead of in a band of their own
+ under the clocks, and they move under the date together when a long
+ locale or the sentence for a partial total does not fit beside it.
+
+ The two clocks stay the largest figures on the screen: when the stage
+ starts and when it reaches its last place. Both are ones the chain below
+ repeats, read off the same arrival column (see stageClocks), so a first
+ stop pinned at 10:00 heads the card at 10:00 and not at the end of its
+ stay. They carry dir=ltr for the same reason the rows do: a clock reads
+ the same way round in an RTL locale.
+
+ No day colour here. It keys the day's line on the map, and on this half
+ the map lies under the list, so a dot in the card had nothing on screen
+ to explain it and read as a status light. The stage bar's picture ring
+ carries the colour on the half where the line is visible. */}
+
+
+
+ {stageDateLabel(planner, stage.dayId) ?? t('roadtrip.day', { number: stage.dayNumber })}
+
+ {/* The two badges wrap as a pair. Loose in the line, a long drive would keep
+ the date and the drive on one line and drop the count alone onto the next,
+ at the opposite edge from the badge it belongs with. */}
+
+ {/* The drive badge alone may break inside itself. A badge keeps its text on
+ one line, which is right for a figure, but the partial sentence runs to
+ nearly fifty characters in some locales and would push past the card on
+ a narrow phone, so this one stops at the row's width and lets its height
+ follow the text. The stop count is a figure and keeps to one line. */}
+
+ {stage.distance > 0
+ ? t('roadtrip.leg.driveText', {
+ distance: formatDistance(stage.distance / 1000, unit),
+ time: formatDurationShort(stage.duration),
+ })
+ : t('roadtrip.summary.partial')}
+
+ {t('roadtrip.day.stopCount', { count: rt.stops })}
+
+
+
+
+ {t('roadtrip.limit.dayOver', {
+ time: formatDurationShort((stage.dayWarning.minutes - stage.dayWarning.limitMinutes) * 60),
+ })}
+
+ {/* The sentence the desktop hides in a title attribute. */}
+
+ {t('roadtrip.limit.hint')}
+
+
+ )}
+
+
+ {rt.upNext && }
+
+
+ {rt.rows.map((row, i) => {
+ if (row.kind === 'stop') {
+ return (
+ openStop(row)}
+ onPickKind={canEditPlaces
+ ? () => shell.openSheet('rtkind', {
+ placeId: row.stop.placeId,
+ stopType: row.stop.stopType ?? null,
+ name: row.stop.name,
+ })
+ : undefined}
+ />
+ )
+ }
+ if (row.kind === 'leg') {
+ // Only where the desk rail offers it too (legReroutable), and with the
+ // card's day id, the one the desk passes: the planner finds the day each
+ // stop is stored on by itself.
+ return (
+ alts.ask(stage.dayId, row.index) : undefined}
+ alternativesOpen={alts.isOpenFor(stage.dayId, row.index)}
+ alternativesDisabled={!alts.editable}
+ />
+ )
+ }
+ if (row.kind === 'auto') return
+ if (row.kind === 'spill') {
+ return
+ }
+ return (
+ planner.askRefuel(stage.dayId, dryPointFor(planner, stage.dayId, row.legIndex))
+ : undefined}
+ onAccept={planner.can('day_edit', planner.trip)
+ ? poi => planner.acceptRefuel(stage.dayId, poi, dryPointFor(planner, stage.dayId, row.legIndex))
+ : undefined}
+ />
+ )
+ })}
+
+ >
+ )}
+
+
+ )
+}
+
+/**
+ * What is coming up, measured against the clock rather than the plan.
+ *
+ * Without it the stage is a morning plan in a narrow column: leave at 09:15 instead of
+ * 08:30 and every figure on the screen is quietly wrong for the rest of the day. The
+ * planned time stays put and the delta sits beside it, because the planned time is the
+ * number you want to compare against.
+ */
+function UpNext({ planner, shell, rt, stageDayId, onOpen }: {
+ planner: MTripTabPanelProps['planner']
+ shell: MTripTabPanelProps['shell']
+ rt: ReturnType
+ stageDayId: number
+ onOpen: (row: StopRow) => void
+}) {
+ const { t } = planner
+ const next = rt.upNext
+ if (!next) return null
+ const late = next.minutesUntil < 0
+ const place = planner.places.find(p => p.id === next.row.stop.placeId)
+ const targets = place ? getNavigationTargets(place) : []
+
+ return (
+
+ onOpen(next.row)} className="w-full text-left">
+
+
+ {t('mobileTrip.upNext')}
+
+ {/* One pill, two readings: a countdown while the stop is still ahead, the
+ delay once its planned time has passed. There is no position source, so
+ "behind plan" is the strongest honest claim available. */}
+
+ {late
+ ? t('mobileTrip.rtBehind', { time: formatDurationShort(-next.minutesUntil * 60) })
+ : t('mobileTrip.inCountdown', { time: formatDurationShort(next.minutesUntil * 60) })}
+
+
+ {next.row.stop.name}
+ {next.row.time && (
+ {next.row.time}
+ )}
+
+
+
+ )
+}
+
+/**
+ * An empty stage is not a failure.
+ *
+ * A day with one place has no drive, because a route needs two. So no summary card
+ * full of zeroes, no skeleton and no button, just the line and the one sentence that
+ * says out loud where the planning happens.
+ */
+function EmptyStage({ planner, loading }: { planner: MTripTabPanelProps['planner']; loading: boolean }) {
+ const { t } = planner
+ return (
+
+ )
+}
+
+/* ── small helpers ────────────────────────────────────────────────────────── */
+
+function stageDateLabel(planner: MTripTabPanelProps['planner'], dayId: number): string | null {
+ const day = planner.days.find(d => d.id === dayId)
+ if (!day?.date) return null
+ const date = new Date(`${day.date.slice(0, 10)}T00:00:00`)
+ if (Number.isNaN(date.getTime())) return null
+ return new Intl.DateTimeFormat(planner.language, { weekday: 'short', day: 'numeric', month: 'short' }).format(date)
+}
+
+/** The dry point the refuel search measures from, looked up by its leg. */
+function dryPointFor(planner: MTripTabPanelProps['planner'], dayId: number, legIndex: number) {
+ const day = planner.roadtripRoutes.days.find(d => d.dayId === dayId)
+ const point = day?.dryPoints?.find(p => p.legIndex === legIndex)
+ return point!
+}
diff --git a/client/src/mobile/screens/trip/roadtrip/MRtAlternativesBar.tsx b/client/src/mobile/screens/trip/roadtrip/MRtAlternativesBar.tsx
new file mode 100644
index 000000000..c1137b9b7
--- /dev/null
+++ b/client/src/mobile/screens/trip/roadtrip/MRtAlternativesBar.tsx
@@ -0,0 +1,178 @@
+import { AlertTriangle, Check, Loader2, Shuffle, X } from 'lucide-react'
+import MBadge from '../../../components/MBadge'
+import MIconBtn from '../../../components/MIconBtn'
+import { alternativeSubline, type AlternativeOverlay } from '../../../../components/Roadtrip/alternativeOverlays'
+import { useSettingsStore } from '../../../../store/settingsStore'
+import { formatDistance } from '../../../../utils/units'
+import { badgeLabel } from './stageBadges'
+import { RT_ALT_BAR_HEIGHT, type MRtAlternativesController } from './useMRtAlternatives'
+import type { TripPlanner } from '../MTripShell'
+
+export interface MRtAlternativesBarProps {
+ planner: TripPlanner
+ alts: MRtAlternativesController
+}
+
+/**
+ * The ways of driving one leg, over the map that draws them.
+ *
+ * It takes the stage bar's slot rather than a sheet: the answer is the lines on the map,
+ * and a sheet big enough for three offers would cover the very roads it asks about.
+ *
+ * Three rows at fixed heights, because the map lifts its credit and its round controls by
+ * this bar's height (RT_ALT_BAR_LIFT), and a bar that grew with its text would slide under
+ * them. So every line truncates or clamps instead of wrapping into another row.
+ *
+ * A chip previews and the button takes. The chip lights its road on the map, and so does
+ * a tap on the line itself; nothing is written until the confirm, which stays off until a
+ * road other than the one already driven is picked. The chips go quiet while the choice
+ * is being saved, so a second tap cannot pick another road under a write in flight.
+ */
+export default function MRtAlternativesBar({ planner, alts }: MRtAlternativesBarProps) {
+ const { t } = planner
+ const title = t('roadtrip.alt.title')
+
+ return (
+
+
+
+
+ {title}
+
+
+
+
+
+
+
+
+
+
+
+ {/* The desk hides this sentence in a tooltip on the chip. There is no hover here,
+ so it stands beside the button whose choice it qualifies. */}
+ {alts.picked?.otherEngine && (
+
+ {t('roadtrip.alt.otherEngine')}
+
+ )}
+
+ {alts.saving
+ ?
+ : }
+ {t('common.confirm')}
+
+
+
+ )
+}
+
+/** The middle row: what the router said, or the roads to pick from. */
+function AlternativesBody({ planner, alts }: MRtAlternativesBarProps) {
+ const { t } = planner
+ const unit = useSettingsStore(s => s.settings.distance_unit)
+
+ if (alts.phase === 'loading') {
+ return (
+
+ )
+ }
+ if (alts.phase === 'onlyOne') {
+ // One road back is genuinely one sensible way to drive the leg, not a failure.
+ return (
+
+ {t('roadtrip.alt.onlyOne')}
+
+ )
+ }
+ // No phase means no open picker. The tab mounts the bar only while one is open, so this
+ // is at most the render it closes in, and "only one way" there would describe no leg.
+ if (alts.phase !== 'choose') return null
+
+ // Scrolls sideways rather than wrapping, because the row has a fixed height. The negative
+ // margin lets a chip slide under the bar's own edge instead of stopping short of it.
+ return (
+
+ )
+}
+
+/**
+ * One offered road: its colour, its drive time, its length and what sets it apart.
+ *
+ * The drive time comes first because it is the exact text of the pill on the map, and it
+ * is that text rather than the swatch that ties a chip to its line: every offer is drawn
+ * in the same pale blue. The distance is a badge, a figure on its own the way the stage
+ * bar sets its figures, and the chip spells its parts out in its name for the reason the
+ * stage bar does.
+ */
+function AlternativeChip({ alt, picked, disabled, distance, subline, onPick }: {
+ alt: AlternativeOverlay
+ picked: boolean
+ disabled: boolean
+ distance: string
+ subline: string
+ onPick: () => void
+}) {
+ return (
+
+
+
+
+ {alt.label}
+ {distance}
+
+ {subline}
+
+
+ )
+}
diff --git a/client/src/mobile/screens/trip/roadtrip/MRtCorridorBar.tsx b/client/src/mobile/screens/trip/roadtrip/MRtCorridorBar.tsx
new file mode 100644
index 000000000..30dd8a307
--- /dev/null
+++ b/client/src/mobile/screens/trip/roadtrip/MRtCorridorBar.tsx
@@ -0,0 +1,88 @@
+import { AlertTriangle, Loader2, Search, WifiOff, X } from 'lucide-react'
+import MIconBtn from '../../../components/MIconBtn'
+import { formatDistance } from '../../../../utils/units'
+import { useSettingsStore } from '../../../../store/settingsStore'
+import type { MRtCorridorController } from './useMRtCorridor'
+import type { TripPlanner } from '../MTripShell'
+
+export interface MRtCorridorBarProps {
+ planner: TripPlanner
+ corridor: MRtCorridorController
+ /** Opens the sheet where the question is asked and the answer is read. */
+ onOpen: () => void
+}
+
+/**
+ * The one control that puts "what is on the way" on a phone screen.
+ *
+ * It sits in the same band as the plan tab's POI bar, on both halves of the road trip
+ * tab, and it never moves: the list and the map are two views of one stage, and a
+ * control that jumps when you switch between them is a control you have to find twice.
+ *
+ * It is a status line as much as a button. A corridor search is several requests over a
+ * mobile connection and can take the better part of half a minute, so the state it is in
+ * has to be readable without opening anything: running, answered, or nothing asked yet.
+ * The answer's own pins are on the map underneath either way.
+ */
+export default function MRtCorridorBar({ planner, corridor, onOpen }: MRtCorridorBarProps) {
+ const { t } = planner
+ const unit = useSettingsStore(s => s.settings.distance_unit)
+
+ const reachLabel = corridor.reach === 'stage'
+ ? t('roadtrip.poi.wholeDay')
+ : t('mobileTrip.rtReachAhead', { distance: formatDistance(corridor.reachKm, unit) })
+
+ let icon =
+ let title = t('roadtrip.poi.title')
+ let meta: string | null = reachLabel
+
+ if (corridor.offline) {
+ icon =
+ title = t('mobileTrip.rtSearchOffline')
+ meta = null
+ } else if (corridor.error) {
+ // Never "0 on the way" after a search that failed: nothing was checked, and a count
+ // of nothing reads as a stretch of road with no petrol station on it.
+ icon =
+ title = t('roadtrip.poi.failed')
+ meta = null
+ } else if (corridor.loading) {
+ icon =
+ title = t('roadtrip.poi.searching', { done: corridor.progress.done, total: corridor.progress.total })
+ meta = null
+ } else if (corridor.answered) {
+ title = t('roadtrip.poi.found', { count: corridor.hits.length })
+ }
+
+ // The trailing round button is a sibling rather than nested: a button inside a button
+ // is markup no browser and no screen reader agrees on. While a search runs it aborts
+ // it; once one has answered it throws the answer away, pins and all.
+ const trailing = corridor.loading || corridor.answered
+
+ return (
+
+ )
+}
diff --git a/client/src/mobile/screens/trip/roadtrip/MRtCorridorSheet.tsx b/client/src/mobile/screens/trip/roadtrip/MRtCorridorSheet.tsx
new file mode 100644
index 000000000..154b21e54
--- /dev/null
+++ b/client/src/mobile/screens/trip/roadtrip/MRtCorridorSheet.tsx
@@ -0,0 +1,268 @@
+import type { ReactNode } from 'react'
+import { AlertTriangle, Loader2, MapPin, Plus, Search, WifiOff, X } from 'lucide-react'
+import MSheet from '../../../components/MSheet'
+import MChip from '../../../components/MChip'
+import MIconBtn from '../../../components/MIconBtn'
+import { Eyebrow } from '../sheets/MTripSheetUi'
+import { useMRtCorridor, type MRtCorridorController } from './useMRtCorridor'
+import { corridorHitLabel } from '../../../../components/Roadtrip/corridorSearchModel'
+import { CORRIDOR_CATEGORIES, CORRIDOR_CATEGORY_BY_KEY } from '../../../../components/Roadtrip/stopKinds'
+import { serviceColor } from '../../../../components/Roadtrip/roadtripModel'
+import { formatDistance } from '../../../../utils/units'
+import { useSettingsStore } from '../../../../store/settingsStore'
+import type { CorridorPoi } from '../../../../components/Roadtrip/useCorridorPois'
+import type { MTripSheetsProps } from '../MTripShell'
+import type { DistanceUnit, TranslationFn } from '../../../../types'
+
+/**
+ * Asking "what is on the way" from the passenger seat.
+ *
+ * The desktop asks this in a 420px column with six controls: the day, the categories,
+ * the corridor width, a section of the drive, a plug type and a minimum power. Two of
+ * those are the question and four are ways of narrowing an answer already on screen,
+ * which is a desk activity. Here the question is two chips and a button, and the
+ * narrowing is gone: a phone shows ten rows, not a hundred, and the way to see fewer of
+ * them is to ask about less road.
+ *
+ * That is the second chip. A search covers one day either way, but a day can be three
+ * hundred kilometres and fifteen requests over a mobile connection, while the fifty
+ * ahead of the driver are three. "Ahead" is where the money is; "the whole stage" is
+ * there because somebody planning tomorrow evening's dinner is not driving right now.
+ */
+/**
+ * Rows a sheet prints before it starts being a scroll rather than an answer.
+ *
+ * A whole-stage search with four categories comes back with a couple of hundred, which
+ * is a list nobody reads on a 375px screen and a couple of hundred inline icons to draw.
+ * The rest are not lost: every one of them is a pin on the map behind this sheet, and
+ * asking about less road is the way to see fewer.
+ */
+const MAX_ROWS = 60
+
+export default function MRtCorridorSheet({ planner, shell }: MTripSheetsProps) {
+ const { t } = planner
+ const corridor = useMRtCorridor(planner, shell)
+ const unit = useSettingsStore(s => s.settings.distance_unit)
+ const open = shell.sheet?.id === 'rtsearch'
+
+ const reachLabel = t('mobileTrip.rtReachAhead', { distance: formatDistance(corridor.reachKm, unit) })
+
+ /**
+ * Taking a hit onto the trip.
+ *
+ * Through the planner's own POI handler, which is the same door the map's pins use:
+ * it works out where in the day's chain the place belongs from how far along the drive
+ * it sits, and hands the stop kind and the stay to the draft sheet. The sheet closes
+ * first so the draft is not opened underneath it.
+ */
+ const add = (poi: CorridorPoi) => {
+ shell.closeSheet()
+ planner.handlePoiClick(poi)
+ }
+
+ /** Brings a hit into view, which on a phone means the map half of this tab. */
+ const show = (poi: CorridorPoi) => {
+ shell.closeSheet()
+ planner.focusRoadtripPoint(poi.lat, poi.lng)
+ if (shell.rtView === 'list') shell.toggleRtView()
+ }
+
+ const canAdd = planner.can('place_edit', planner.trip)
+
+ return (
+
+
+ {corridor.hits.length > MAX_ROWS && (
+ // Said out loud rather than silently cut: a list that stops at sixty
+ // without saying so reads as the whole answer. All of them are on the
+ // map underneath, which is the other half of this screen.
+
+
+ )
+}
+
+/**
+ * What the search has to say about itself.
+ *
+ * Every one of these lines exists because the alternative is a list that looks complete
+ * and is not: a stretch nobody asked about, a box that did not answer, an answer the
+ * server cut short. On a desk those are footnotes under a hundred rows; on a phone they
+ * are the difference between "there is no petrol station" and "we did not look".
+ */
+function StatusBand({ corridor, t }: { corridor: MRtCorridorController; t: TranslationFn }) {
+ const notes: string[] = []
+ if (corridor.capped) notes.push(t('roadtrip.poi.capped'))
+ if (corridor.failedAreas > 0) notes.push(t('roadtrip.poi.partial', { count: corridor.failedAreas }))
+ // The phone's own wording, because the desk's ends in "narrow the corridor" and the
+ // corridor width is a control this screen deliberately does not have. What it does
+ // have is the category chips, and fewer of them really is what makes a box fit.
+ if (corridor.truncatedAreas > 0) notes.push(t('mobileTrip.rtTruncated', { count: corridor.truncatedAreas }))
+
+ if (corridor.offline) return }>{t('mobileTrip.rtSearchOffline')}
+ if (corridor.error) return }>{t('roadtrip.poi.failed')}
+ if (corridor.categories.length === 0) return {t('roadtrip.poi.empty')}
+
+ const empty = corridor.answered && corridor.hits.length === 0
+ return (
+ <>
+ {empty && (
+
+ {corridor.reach === 'ahead' ? t('mobileTrip.rtNoneAhead') : t('mobileTrip.rtNoneOnStage')}
+
+ )}
+ {notes.map(note => (
+ }>{note}
+ ))}
+ >
+ )
+}
+
+function Note({ tone, icon, children }: { tone: 'warn' | 'calm'; icon?: ReactNode; children: ReactNode }) {
+ return (
+
+ {icon && {icon}}
+ {children}
+
+ )
+}
+
+/**
+ * One hit: what it is, where on the drive it sits, and the one action worth a button.
+ *
+ * Two targets and not three. The row shows it on the map, the plus takes it onto the
+ * trip, and everything the desktop puts beside those (the plug list, the price, the
+ * opening hours) belongs to the stop once it exists, where the stop sheet already
+ * prints it. Adding it twice would be the same duplication the corridor line avoids.
+ */
+function HitRow({ poi, unit, t, first, onShow, onAdd }: {
+ poi: CorridorPoi
+ unit: DistanceUnit
+ t: TranslationFn
+ first: boolean
+ onShow: () => void
+ onAdd?: () => void
+}) {
+ const Icon = CORRIDOR_CATEGORY_BY_KEY[poi.category]?.Icon ?? MapPin
+ const color = serviceColor(poi.category)
+ return (
+
+ )
+}
diff --git a/client/src/mobile/screens/trip/roadtrip/MRtDraftSheet.tsx b/client/src/mobile/screens/trip/roadtrip/MRtDraftSheet.tsx
new file mode 100644
index 000000000..2aad66a9b
--- /dev/null
+++ b/client/src/mobile/screens/trip/roadtrip/MRtDraftSheet.tsx
@@ -0,0 +1,181 @@
+import { useEffect, useRef, useState } from 'react'
+import { AlertTriangle, BedDouble, Hourglass, ParkingSquare } from 'lucide-react'
+import MSheet from '../../../components/MSheet'
+import MChip from '../../../components/MChip'
+import { Eyebrow, FormSheetHeader } from '../sheets/PlSheetChrome'
+import { STOP_KINDS, STOP_KIND_BY_KEY, isOvernightCategory } from '../../../../components/Roadtrip/stopKinds'
+import { formatDurationShort } from '../../../../components/Roadtrip/roadtripModel'
+import type { RoadtripStopDraft } from '../../../../components/Roadtrip/RoadtripStopPopup'
+import type { TripPlanner } from '../MTripShell'
+import type { RoadtripStopType } from '@trek/shared'
+
+export interface MRtDraftSheetProps {
+ planner: TripPlanner
+}
+
+/**
+ * How long to stand still, offered as the few answers anybody actually gives.
+ * The same six the desktop popup offers, so a stop added on the phone and one
+ * added at the desk are the same stop.
+ */
+const DWELL_CHOICES = [5, 10, 20, 30, 45, 60]
+
+/**
+ * Taking a hit found along the drive onto the trip, on the phone.
+ *
+ * Driven by `planner.stopDraft` rather than by `shell.sheet`, because the draft
+ * is what every entry point produces: the fuel search accepting a station
+ * (`acceptRefuel`), a corridor hit dropped on the map, and the chain opening a
+ * service stop it already owns all set that one piece of state and nothing
+ * else. Without a consumer here the fuel button on the phone visibly did
+ * nothing, because the draft was set and no surface read it.
+ *
+ * The write goes through `planner.saveStopDraft`, the same call the desktop
+ * popup makes. It owns the whole sequence a stop needs (the place, the
+ * assignment at the worked-out position, the via re-anchoring, the re-route)
+ * and reports its own failure with a toast, so there is no second path here for
+ * any of it to go wrong in.
+ */
+export default function MRtDraftSheet({ planner }: MRtDraftSheetProps) {
+ const { t, stopDraft, setStopDraft, saveStopDraft, stopDraftDuplicate } = planner
+
+ const [stopType, setStopType] = useState(null)
+ const [dwell, setDwell] = useState(30)
+ const [saving, setSaving] = useState(false)
+
+ // Hold the last draft so the panel keeps its content through the 280ms exit
+ // animation: saving clears the draft immediately, and rendering off the live
+ // value alone would blank the sheet mid-slide.
+ const heldRef = useRef(null)
+ if (stopDraft) heldRef.current = stopDraft
+ const draft = stopDraft ?? heldRef.current
+
+ // Seeded from what the hit brings with it: a charge is not a fuel stop, and
+ // each kind carries how long it usually takes. An edit answers with what the
+ // stop already says instead.
+ useEffect(() => {
+ if (!stopDraft) return
+ const suggested = STOP_KINDS.find(k => k.key === stopDraft.poi.category)
+ setStopType(stopDraft.editing ? stopDraft.editing.stopType : suggested?.key ?? null)
+ setDwell(stopDraft.editing?.dwellMinutes ?? suggested?.defaultMinutes ?? 30)
+ setSaving(false)
+ }, [stopDraft])
+
+ if (!draft) return null
+
+ const kind = STOP_KINDS.find(k => k.key === stopType)
+
+ /**
+ * A place somebody could sleep at is not offered here at all.
+ *
+ * Booking a night is a second write path (the room, the two days it spans,
+ * the check-in) and the phone has no surface for any of it yet. Saving such a
+ * hit as an ordinary pause would look like it worked while quietly losing the
+ * night, which is worse than saying where it can be done.
+ */
+ const overnightOnly = draft.overnight != null || isOvernightCategory(draft.poi.category)
+
+ const discard = () => setStopDraft(null)
+
+ const pickKind = (key: RoadtripStopType) => {
+ if (stopType === key) return
+ setStopType(key)
+ // Picking a kind picks its usual length too, until the user says otherwise.
+ // Tapping the kind already chosen changes nothing, so a time set by hand
+ // survives it.
+ setDwell(STOP_KIND_BY_KEY[key]?.defaultMinutes ?? dwell)
+ }
+
+ const submit = async (): Promise => {
+ if (saving) return
+ setSaving(true)
+ try {
+ await saveStopDraft({ stopType, dwellMinutes: dwell })
+ } finally {
+ setSaving(false)
+ }
+ }
+
+ return (
+
+
+
+
+
+ {stopDraftDuplicate && (
+ // The full place form warns about duplicates; without the same warning
+ // here this would be the quickest way to add one petrol station twice.
+
+
+ )
+}
diff --git a/client/src/mobile/screens/trip/roadtrip/MRtInfoSheet.tsx b/client/src/mobile/screens/trip/roadtrip/MRtInfoSheet.tsx
new file mode 100644
index 000000000..00a343e98
--- /dev/null
+++ b/client/src/mobile/screens/trip/roadtrip/MRtInfoSheet.tsx
@@ -0,0 +1,237 @@
+import type { ReactNode } from 'react'
+import { Car, Fuel, Zap } from 'lucide-react'
+import MSheet from '../../../components/MSheet'
+import type { MTripSheetsProps } from '../MTripShell'
+import { useTranslation } from '../../../../i18n'
+import { useSettingsStore } from '../../../../store/settingsStore'
+import { useRoadtripSettings } from '../../../../hooks/useRoadtripSettings'
+import { useVehicleRange } from '../../../../components/Roadtrip/useVehicleRange'
+import { blockMask } from '../../../../components/Roadtrip/RangeStrip'
+import { dayWindow } from '../../../../components/Roadtrip/dayWindow'
+import { formatDurationShort, parseAvoid } from '../../../../components/Roadtrip/roadtripModel'
+import { valhallaAvailable } from '../../../../components/Map/valhallaRoute'
+import { convertDistance, formatDistance, getDistanceUnitLabel } from '../../../../utils/units'
+import { Eyebrow, TileHeader } from '../sheets/MTripSheetUi'
+import type { DistanceUnit } from '../../../../types'
+
+/**
+ * The figures the stage plans with, read out loud.
+ *
+ * The chain says a stretch is too long, or that there is nothing to fill up at before the
+ * tank runs dry, and on a phone there was nothing behind those sentences: the numbers they
+ * are measured against live in a desktop dialog with seven panels and two columns. Without
+ * them a warning is an opinion. So two of those panels come along, the two that decide what
+ * the stage is allowed to say, and nothing else does.
+ *
+ * Nothing here can be changed. That is the point rather than a gap: driving limits are set
+ * once, at a table, before anybody is in the car, and a form in the passenger seat is a way
+ * to break a trip while it is happening. So there is no field, no slider and no greyed-out
+ * button that looks like one, and the last line says plainly where the settings are and what
+ * else that screen can do that this one cannot.
+ */
+
+/**
+ * How many kilometres one block of the bar stands for.
+ *
+ * The same fifty as `RangeStrip`, whose `blockMask` cuts the bar here too. The mask comes
+ * from that module so the two pictures cannot drift apart; the figure the note quotes is
+ * the one thing it does not hand out, so it is stated once here.
+ */
+const BLOCK_KM = 50
+
+/** One value of the driving limits, with the row rule above every row but the first. */
+function LimitLine({ label, value, fallback, first }: {
+ label: string
+ value: string | null
+ fallback: string
+ first: boolean
+}) {
+ return (
+
+ {label}
+
+ {value ?? fallback}
+
+
+ )
+}
+
+/** One card of the sheet: eyebrow plus whatever the section is made of. */
+function InfoCard({ label, children }: { label: string; children: ReactNode }) {
+ return (
+
+ {label}
+ {children}
+
+ )
+}
+
+/**
+ * Driving figures sheet ('rtinfo'): the vehicle's range as the tank it leaves the factory
+ * with, and the limits every warning on the stage is measured against. Read-only.
+ */
+export default function MRtInfoSheet({ planner, shell }: MTripSheetsProps) {
+ const { t } = useTranslation()
+ const open = shell.sheet?.id === 'rtinfo'
+ const tripId = planner.tripId
+
+ const unitSetting = useSettingsStore(s => s.settings.distance_unit)
+ const unit: DistanceUnit = unitSetting === 'imperial' ? 'imperial' : 'metric'
+
+ // The same range the stage plans with: the vehicle's own figures when they add up,
+ // the typed one otherwise. Reading it through the shared hook is what keeps the sheet
+ // from becoming a second opinion about the tank.
+ const { vehicleKind, rangeKm } = useVehicleRange(tripId)
+ const legMinutes = useRoadtripSettings(s => s.roadtrip_leg_minutes, tripId)
+ const dayMinutes = useRoadtripSettings(s => s.roadtrip_day_minutes, tripId)
+ const dayStart = useRoadtripSettings(s => s.roadtrip_day_start, tripId)
+ const dayEnd = useRoadtripSettings(s => s.roadtrip_day_end, tripId)
+ const fillPercent = useRoadtripSettings(s => s.roadtrip_fill_percent, tripId)
+ const degradation = useRoadtripSettings(s => s.roadtrip_battery_degradation, tripId)
+ const avoidRaw = useRoadtripSettings(s => s.roadtrip_avoid, tripId)
+
+ const electric = vehicleKind === 'electric'
+ const VehicleIcon = electric ? Zap : vehicleKind === 'combustion' ? Fuel : Car
+
+ // Capped where the arithmetic caps it, so no picture can claim a battery is gone. The
+ // range above the bar already has this taken off it, which is exactly why it gets said.
+ const wear = electric ? Math.min(90, Math.max(0, degradation ?? 0)) : 0
+ const fill = fillPercent && fillPercent > 0 && fillPercent < 100 ? fillPercent : 100
+
+ // Split rather than formatted whole, so the unit can sit smaller beside the figure. The
+ // rounding is formatDistance's own, because the stage header uses that and the two must
+ // not disagree by a tenth.
+ const shown = rangeKm ? Math.round(convertDistance(rangeKm, unit) * 10) / 10 : null
+ const mask = blockMask(rangeKm)
+
+ const notes = [
+ shown === null ? t('roadtrip.limit.rangeEmptyHint') : null,
+ shown !== null && fill < 100
+ ? t('roadtrip.limit.afterFill', { percent: fill, distance: formatDistance((rangeKm ?? 0) * fill / 100, unit) })
+ : null,
+ mask ? t('roadtrip.limit.blockNote', { distance: formatDistance(BLOCK_KM, unit) }) : null,
+ wear > 0 ? t('roadtrip.limit.wearNote', { percent: wear }) : null,
+ ].filter((note): note is string => note !== null)
+
+ const unitLabel = getDistanceUnitLabel(unit)
+ const perLabel = t(electric ? 'roadtrip.limit.perCharge' : 'roadtrip.limit.perFill')
+ const barLabel = shown === null
+ ? t('roadtrip.limit.rangeEmpty')
+ : `${shown} ${unitLabel} ${perLabel}`
+
+ // Both times on one line, in the separator the desktop badge already uses. A dash
+ // between two clock readings is the one place a phone line breaks in the wrong spot.
+ const windowText = dayWindow(dayStart, dayEnd) ? `${dayStart} · ${dayEnd}` : null
+
+ // No second routing engine, no avoidance: the stored classes would be a promise the
+ // router cannot keep, so the row says the same "off" it would say with none set.
+ const avoiding = parseAvoid(avoidRaw)
+ const avoidText = valhallaAvailable() && avoiding.length > 0
+ ? t('roadtrip.avoid.badge', { count: avoiding.length })
+ : null
+
+ const off = t('roadtrip.limit.off')
+ const lines: { key: string; label: string; value: string | null; fallback: string }[] = [
+ {
+ key: 'leg',
+ label: t('roadtrip.limit.legLabel'),
+ value: legMinutes ? formatDurationShort(legMinutes * 60) : null,
+ fallback: off,
+ },
+ {
+ key: 'day',
+ label: t('roadtrip.limit.dayLabel'),
+ value: dayMinutes ? formatDurationShort(dayMinutes * 60) : null,
+ fallback: off,
+ },
+ { key: 'window', label: t('roadtrip.window.title'), value: windowText, fallback: off },
+ {
+ key: 'fill',
+ label: t('roadtrip.limit.fillLabel'),
+ value: fill < 100 ? `${fill} %` : null,
+ // "off" is the wrong word for a tank: not saying how far you fill it means you fill
+ // it right up, which is what the arithmetic then does.
+ fallback: t('roadtrip.limit.fillFull'),
+ },
+ { key: 'avoid', label: t('roadtrip.avoid.section'), value: avoidText, fallback: off },
+ ]
+
+ return (
+
+
+ {/* Cut as a mask rather than painted over, so the gaps are real holes and
+ the glass behind the sheet shows through them. */}
+
+
+
+
+
+ {notes.length > 0 && (
+
+ {notes.join(' · ')}
+
+ )}
+
+
+
+ {/* ── Limits: what every warning on the stage is measured against ── */}
+
+
+
+ {lines.map((line, i) => (
+
+ ))}
+
+
+
+
+
+ {t('mobileTrip.rtDesktopNote')}
+
+
+
+ )
+}
diff --git a/client/src/mobile/screens/trip/roadtrip/MRtKindSheet.tsx b/client/src/mobile/screens/trip/roadtrip/MRtKindSheet.tsx
new file mode 100644
index 000000000..44b0d389f
--- /dev/null
+++ b/client/src/mobile/screens/trip/roadtrip/MRtKindSheet.tsx
@@ -0,0 +1,149 @@
+import { useRef, useState } from 'react'
+import { MapPin } from 'lucide-react'
+import MSheet from '../../../components/MSheet'
+import type { MTripSheetsProps } from '../MTripShell'
+import { useTranslation } from '../../../../i18n'
+import { STOP_KINDS } from '../../../../components/Roadtrip/stopKinds'
+import { FormSheetHeader } from '../sheets/PlSheetChrome'
+import type { RoadtripStopType } from '@trek/shared'
+
+/** What the chain hands over when a stop's disc is tapped. */
+interface RtKindSheetPayload {
+ placeId?: number
+ /** What the stop is now: a service kind, or null for a destination. */
+ stopType?: string | null
+ name?: string
+}
+
+/**
+ * Turning a place on the drive into a pause, and back, on the phone ('rtkind', payload
+ * { placeId, stopType, name }).
+ *
+ * Opened from the stop's own disc in the chain, which is where the desktop opens it from
+ * and for the same reason: the disc is exactly what changes. A destination wears its
+ * running number, a service stop wears its kind's icon in that kind's colour, so the
+ * control is its own preview. Tap the 3, pick the pump, and the 3 becomes an orange disc
+ * while everything below it renumbers.
+ *
+ * A sheet rather than the desktop's popover under the disc: a popover is aimed at an
+ * anchor with a mouse, and the same palette on a phone would land under the thumb that
+ * opened it. The kinds stay a palette of discs rather than a list of words, as they are
+ * on the desktop. At this size the colour and the shape are the label, and seven rows of
+ * text for seven icons would be a menu where a palette does. Each disc still carries its
+ * name for a screen reader.
+ *
+ * It writes through `planner.setRoadtripStopKind`, the very call the desktop rail makes:
+ * one field on one place, with the chain redrawing off the store as soon as it lands.
+ */
+export default function MRtKindSheet({ planner, shell }: MTripSheetsProps) {
+ const { t } = useTranslation()
+ const open = shell.sheet?.id === 'rtkind'
+ const payload = (shell.sheet?.payload ?? {}) as RtKindSheetPayload
+ const canEdit = planner.can('place_edit', planner.trip)
+
+ // Hold the last payload so the name and the current kind survive the exit animation
+ // instead of blinking out while the sheet slides away.
+ const heldRef = useRef(null)
+ if (open && typeof payload.placeId === 'number') heldRef.current = payload
+ const stop = open && typeof payload.placeId === 'number' ? payload : heldRef.current
+
+ const [saving, setSaving] = useState(false)
+ const current = stop?.stopType ?? null
+
+ /**
+ * Writes the kind and closes.
+ *
+ * Closing rather than reopening the stop sheet: the answer to "what kind is this" is
+ * the disc in the chain, which is already on screen behind this sheet and redraws the
+ * moment the store lands. `setRoadtripStopKind` reports its own failures and resolves
+ * either way, so what the guard buys is a sheet that does not sit open pretending to
+ * save.
+ */
+ const pick = async (kind: RoadtripStopType | null) => {
+ const placeId = stop?.placeId
+ if (!canEdit || saving || placeId == null) return
+ setSaving(true)
+ try {
+ await planner.setRoadtripStopKind(placeId, kind)
+ shell.closeSheet()
+ } catch {
+ // Swallowed rather than toasted again: `setRoadtripStopKind` catches its own
+ // failures and shows the message itself, so a second one here would be the same
+ // news twice. What this catch is for is the sheet, which stays open on a write that
+ // never landed instead of closing as if it had.
+ } finally {
+ setSaving(false)
+ }
+ }
+
+ return (
+
+ {stop && (
+ <>
+
+
+
+ {stop.name && (
+
{stop.name}
+ )}
+
+ {/* Wrapped rather than scrolled sideways: seven discs do not fit one phone row,
+ and a row that scrolls hides the kinds past its edge behind a gesture. */}
+
+
+ {/* Only once there is something to undo. On a destination it would be a button
+ saying "leave everything as it is". */}
+ {current && (
+ { void pick(null) }}
+ className="mt-[18px] flex w-full items-center justify-center gap-2 rounded-[14px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 py-3 text-[0.8125rem] font-semibold text-m-ink disabled:opacity-35"
+ >
+
+ {t('roadtrip.stop.backToDestination')}
+
+ )}
+
+ >
+ )}
+
+ )
+}
diff --git a/client/src/mobile/screens/trip/roadtrip/MRtStaySheet.tsx b/client/src/mobile/screens/trip/roadtrip/MRtStaySheet.tsx
new file mode 100644
index 000000000..8485ce6f5
--- /dev/null
+++ b/client/src/mobile/screens/trip/roadtrip/MRtStaySheet.tsx
@@ -0,0 +1,285 @@
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { ArrowRight, Minus, Plus } from 'lucide-react'
+import MSheet from '../../../components/MSheet'
+import MChip from '../../../components/MChip'
+import type { MTripSheetsProps } from '../MTripShell'
+import { useTranslation } from '../../../../i18n'
+import { useSettingsStore } from '../../../../store/settingsStore'
+import { formatClock, formatDurationShort, parseClock } from '../../../../components/Roadtrip/roadtripModel'
+import { stageOf } from '../../../../components/Roadtrip/roadtripRowModel'
+import { formatClockTime } from '../../../../utils/formatters'
+import { FormSheetHeader } from '../sheets/PlSheetChrome'
+import { INNER_CLS } from '../sheets/MTripSheetUi'
+
+/** What the chain hands over when a stop's stay is tapped. */
+interface RtStaySheetPayload {
+ placeId?: number
+ /** The stay the place carries right now; absent and zero mean the same thing. */
+ minutes?: number | null
+ name?: string
+}
+
+/** The step the two buttons move in. Same five minutes as the desktop dialog. */
+const STEP = 5
+
+const DAY_MINUTES = 24 * 60
+
+/**
+ * As far as a stay goes, in minutes: a full day, like the desktop slider.
+ *
+ * Kept even though there is no slider here: the plus button has to stop somewhere, and
+ * a stay longer than a day is a second day rather than a longer stop.
+ */
+const MAX = DAY_MINUTES
+
+/**
+ * The lengths a stop usually takes, so the common answer is one tap.
+ *
+ * The same eight the desktop offers. They are the whole of the coarse control here: the
+ * desktop's slider runs 0 to 1440, which on a 343px phone row is four minutes a pixel,
+ * and a control that cannot hit the value it is dragged to is worse than no control.
+ */
+const PRESETS = [15, 30, 45, 60, 90, 120, 480, 720]
+
+const clampMinutes = (value: number): number => Math.min(MAX, Math.max(0, Math.round(value)))
+
+/**
+ * How long the traveller stays at one stop, on the phone ('rtstay', payload
+ * { placeId, minutes, name }).
+ *
+ * Writes `places.duration_minutes` through `planner.setRoadtripStay`, which is the same
+ * single write the desktop dialog makes. Zero rather than null clears it: the update
+ * statement folds a null into "leave it alone", so a null could give a stop a stay but
+ * never take one away.
+ *
+ * Two things this sheet deliberately does not do:
+ *
+ * 1. The two buttons do not auto-repeat on hold. Five-minute steps under a repeat land
+ * forty minutes past the intended value about as often as they land on it, and the
+ * eight presets already cover every length anybody holds a button for.
+ * 2. The preview moves this stop's own departure and nothing else. Every later arrival
+ * shifts too, but that is the routing round's answer after the write, and computing
+ * second time here would be two sources for one number, and they would disagree the
+ * first time a rule changed.
+ */
+export default function MRtStaySheet({ planner, shell }: MTripSheetsProps) {
+ const { t } = useTranslation()
+ const open = shell.sheet?.id === 'rtstay'
+ const payload = (shell.sheet?.payload ?? {}) as RtStaySheetPayload
+ const is12h = useSettingsStore(s => s.settings.time_format) === '12h'
+ const canEdit = planner.can('place_edit', planner.trip)
+
+ // Hold the last payload so the name and the number survive the exit animation
+ // instead of blinking out while the sheet slides away.
+ const heldRef = useRef(null)
+ if (open && typeof payload.placeId === 'number') heldRef.current = payload
+ const stop = open && typeof payload.placeId === 'number' ? payload : heldRef.current
+
+ /** What the place carries now: the value the draft starts from and falls back to. */
+ const stored = clampMinutes(stop?.minutes ?? 0)
+
+ const [minutes, setMinutes] = useState(stored)
+ const [saving, setSaving] = useState(false)
+
+ // Reopened on a different stop, so it starts from that stop's own value rather than
+ // from whatever the last one was left on.
+ useEffect(() => {
+ if (!open) return
+ setMinutes(clampMinutes(payload.minutes ?? 0))
+ setSaving(false)
+ }, [open, payload.placeId, payload.minutes])
+
+ /**
+ * When the drive gets here.
+ *
+ * Read off the stage (the one day both halves of the road trip tab show) rather than
+ * passed in, so the arrival on screen is the arrival the chain drew, from the same
+ * routing round, for the same day. A place planned on several days has an arrival per
+ * day, and the stage is the day the tap came from.
+ */
+ const stage = stageOf(planner.roadtripRoutes.days, planner.selectedDayId)
+ const stopPlaceId = stop?.placeId
+ const arrival = useMemo(() => {
+ if (!stage || stopPlaceId == null) return null
+ const index = stage.stops.findIndex(s => s.placeId === stopPlaceId)
+ if (index === -1) return null
+ return stage.schedule.entries[index]?.arrival ?? null
+ }, [stage, stopPlaceId])
+
+ // What the stay does to this stop: the arrival is fixed by the drive, the departure is
+ // the one end this sheet moves.
+ const preview = useMemo(() => {
+ const at = parseClock(arrival)
+ if (at === null) return null
+ return {
+ arrive: formatClockTime(formatClock(at), is12h),
+ leave: formatClockTime(formatClock(at + minutes), is12h),
+ // `formatClock` wraps modulo 24 h, so a stay running past midnight reads as a small
+ // number again. Without the carry the sheet would quietly promise "leave 01:00" for
+ // a departure the chain places on the next day.
+ carry: Math.floor((at + minutes) / DAY_MINUTES) - Math.floor(at / DAY_MINUTES),
+ }
+ }, [arrival, minutes, is12h])
+
+ const nudge = (delta: number) => setMinutes(m => clampMinutes(m + delta))
+
+ /**
+ * Writes the draft, then hands the traveller back to the stop they came from.
+ *
+ * Reopening 'rtstop' is the point of the save: the times that just moved are shown
+ * there, in the chain's own reading, so the change lands where it was asked for.
+ * Closing without saving deliberately does not reopen it: nothing moved.
+ *
+ * `setRoadtripStay` reports its own failures and resolves either way, so the catch is
+ * the second line rather than the first: what it guards is the sheet being left showing
+ * a number the place does not have.
+ */
+ const save = async () => {
+ const placeId = stop?.placeId
+ if (!canEdit || saving || placeId == null) return
+ const value = minutes
+ setSaving(true)
+ try {
+ await planner.setRoadtripStay(placeId, value)
+ shell.openSheet('rtstop', { ...stop, placeId, minutes: value })
+ } catch {
+ setMinutes(stored)
+ planner.toast.error(t('common.unknownError'))
+ } finally {
+ setSaving(false)
+ }
+ }
+
+ const stepCls =
+ 'flex h-11 w-11 flex-none items-center justify-center rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] text-m-ink disabled:opacity-35'
+ const captionCls = 'font-geist text-[0.5625rem] font-bold uppercase tracking-[.09em] text-m-faint'
+
+ return (
+
+ {stop && (
+ <>
+
+
+
+ {/* Which stop, and what the number actually attaches to. The stay is a column
+ on the place, not on the day's assignment, so a place planned twice keeps
+ one stay for both, and saying so here is cheaper than the surprise. */}
+ {stop.name && (
+
{stop.name}
+ )}
+
+ {t('mobileTrip.rtStayScope')}
+
+
+ {/* The number, the way a timer shows one, with minus and plus either side so a
+ value can be nudged without a control to aim at. */}
+
+
+ {/* The eight usual answers. Read as durations rather than as raw minutes: a
+ tile saying 480 is a number to work out, one saying 8 h is an answer. */}
+ {canEdit && (
+
+ {/* Clearing is the same write as setting one, so it only fills the number in;
+ the save below is still the one way anything is written. */}
+ setMinutes(0)}
+ disabled={!canEdit || saving || minutes === 0}
+ className="inline-flex h-11 items-center rounded-full px-3 text-[0.8125rem] font-semibold text-[color:var(--m-st-danger)] disabled:opacity-40"
+ >
+ {t('roadtrip.stay.none')}
+
+ { void save() }}
+ disabled={!canEdit || saving}
+ className="ml-auto inline-flex h-11 items-center rounded-full bg-m-act px-[18px] text-[0.8125rem] font-semibold text-m-actfg disabled:opacity-40"
+ >
+ {t('common.save')}
+
+
+ >
+ )}
+
+ )
+}
diff --git a/client/src/mobile/screens/trip/roadtrip/MRtStopSheet.tsx b/client/src/mobile/screens/trip/roadtrip/MRtStopSheet.tsx
new file mode 100644
index 000000000..d77f346bd
--- /dev/null
+++ b/client/src/mobile/screens/trip/roadtrip/MRtStopSheet.tsx
@@ -0,0 +1,431 @@
+import { useEffect, useMemo, useRef, useState, type ReactNode, type Ref } from 'react'
+import {
+ AlertTriangle, Clock, Footprints, Fuel, Hourglass, MapPin, Moon, Navigation, Pencil, X,
+} from 'lucide-react'
+import MSheet from '../../../components/MSheet'
+import MIconBtn from '../../../components/MIconBtn'
+import MListRow from '../../../components/MListRow'
+import MToggle from '../../../components/MToggle'
+import type { MTripSheetsProps } from '../MTripShell'
+import { useTranslation } from '../../../../i18n'
+import { useSettingsStore } from '../../../../store/settingsStore'
+import { useTripStore } from '../../../../store/tripStore'
+import ChargingInfo from '../../../../components/Roadtrip/ChargingInfo'
+import { formatDurationShort } from '../../../../components/Roadtrip/roadtripModel'
+import { roadtripRows, stageOf, type StopRow } from '../../../../components/Roadtrip/roadtripRowModel'
+import { STOP_KIND_BY_KEY } from '../../../../components/Roadtrip/stopKinds'
+import { getNavigationTargets, openNavigationTarget } from '../../../../components/Planner/placeNavigation'
+import { NavigationMenu } from '../../../../components/shared/NavigationMenu'
+import { formatDistance } from '../../../../utils/units'
+import { Eyebrow, displayTime } from '../sheets/MTripSheetUi'
+import { showStopOnMap } from './useMRoadtrip'
+import type { DistanceUnit } from '../../../../types'
+import type { RoadtripDay, ScheduleWarning } from '@trek/shared/roadtrip'
+
+/**
+ * One stop of the stage, written out.
+ *
+ * The chain gives a stop a disc, a name, a clock and at most two marks, because that is
+ * what a 375px line carries while somebody is driving. Everything the marks stand for is
+ * here instead, as sentences: why the clock reads what it reads, how long the stay is,
+ * how far the road stops short, and which limit the drive to here went past.
+ *
+ * Read-mostly on purpose. Deleting a stop, reordering the day, changing what kind of stop
+ * it is and how full the tank leaves it are desktop work, done at a table before anybody
+ * is in the car, and they are not here at all: not greyed out, not hidden behind a
+ * confirmation, simply absent, because a dead control on a phone is a promise the screen
+ * cannot keep. What is left are the three things a passenger does decide on the road:
+ * navigate there, stay longer, stop for the night here.
+ *
+ * Editing the place is the one way out of that rule, and it is a hand-over rather than a
+ * control of this sheet: the pencil opens the place editor the plan tab opens, with this
+ * very visit in context, and this sheet closes behind it. The time somebody fixed for a
+ * stop is that editor's start time (the chain anchors on the visit's own start time), so
+ * a time control here would be a second writer for one number. A booked night can also
+ * be held by its check-in, which belongs to the booking and not to the place.
+ */
+
+interface RtStopSheetPayload {
+ dayId?: number
+ assignmentId?: number
+}
+
+/** The stop the sheet is about, and the card it is drawn on. */
+interface Located {
+ day: RoadtripDay
+ row: StopRow
+ /** Index into the CARD's stops, which is what every finding is filed under. */
+ index: number
+}
+
+/**
+ * Finds the stop across the routed days.
+ *
+ * The caller names the day a stop is stored on (`ownerDayId`), which after a night drive
+ * is not the card that draws it: a stop set off from on Tuesday and reached on Wednesday
+ * appears in Wednesday's `stops`. So the named day is tried first and the rest after it,
+ * rather than trusting one lookup that is right most of the time.
+ */
+function locate(days: readonly RoadtripDay[], dayId: number | null, assignmentId: number | null): Located | null {
+ if (assignmentId == null) return null
+ const named = stageOf(days, dayId)
+ const search = named ? [named, ...days.filter(d => d !== named)] : days
+ for (const day of search) {
+ const index = day.stops.findIndex(s => s.assignmentId === assignmentId && !s.automaticNight)
+ if (index < 0) continue
+ const row = roadtripRows(day).find(
+ (r): r is StopRow => r.kind === 'stop' && r.stop.assignmentId === assignmentId,
+ )
+ if (row) return { day, row, index }
+ }
+ return null
+}
+
+/** One finding: an icon, a sentence, and the figure it is about when that reads better apart. */
+function Finding({ icon, label, value, warn = false }: {
+ icon: ReactNode
+ label: string
+ value?: string
+ warn?: boolean
+}) {
+ return (
+
+ return {inner}
+}
+
+/**
+ * Stop detail sheet ('rtstop', payload { dayId, assignmentId }) of the road trip tab.
+ */
+export default function MRtStopSheet({ planner, shell }: MTripSheetsProps) {
+ const { t, locale } = useTranslation()
+ const open = shell.sheet?.id === 'rtstop'
+ const payload = (shell.sheet?.payload ?? {}) as RtStopSheetPayload
+
+ const timeFormat = useSettingsStore(s => s.settings.time_format) || '24h'
+ const unitSetting = useSettingsStore(s => s.settings.distance_unit)
+ const unit: DistanceUnit = unitSetting === 'imperial' ? 'imperial' : 'metric'
+ const tripPlaces = useTripStore(s => s.places)
+
+ const days = planner.roadtripRoutes.days
+ const live = useMemo(
+ () => locate(days, payload.dayId ?? null, payload.assignmentId ?? null),
+ [days, payload.dayId, payload.assignmentId],
+ )
+
+ // Hold the last stop so the card keeps its content through the 280ms exit.
+ const heldRef = useRef(null)
+ if (live) heldRef.current = live
+ const located = live ?? heldRef.current
+
+ const [navOpen, setNavOpen] = useState(false)
+ const navBtnRef = useRef(null)
+ const [saving, setSaving] = useState(false)
+ // The end-day switch, as it should read while the write is in the air.
+ const [pending, setPending] = useState<{ from: boolean; to: boolean } | null>(null)
+ useEffect(() => {
+ if (!open) { setNavOpen(false); setPending(null) }
+ }, [open])
+ useEffect(() => { setPending(null) }, [payload.assignmentId])
+
+ const stop = located?.row.stop ?? null
+ // From the whole trip store, not planner.places: with service stops hidden from the day
+ // lists the phone filters them out of that list, while the stage still draws them, and
+ // both the pencil and the directions have to reach the row the chain drew.
+ const place = tripPlaces.find(p => p.id === stop?.placeId) ?? null
+
+ /**
+ * Addressed by stop, not by selection.
+ *
+ * `planner.roadtripEndDay` derives itself from the place selection, which is what the
+ * desktop inspector needs. Here that would mean moving the selection to open a sheet,
+ * and the place inspector hangs off the same value and would come up underneath. So
+ * the stage sheet calls the stop-addressed writer directly.
+ */
+ const canEndDay = stop != null && planner.dailyTimesActive && planner.can('day_edit', planner.trip)
+ const endDayTruth = !!stop?.endDay
+ // The optimistic value is released the moment the planner's own answer moves off what
+ // it was taken from, so a landed write shows the real state rather than a copy of it.
+ const endDayActive = pending && pending.from === endDayTruth ? pending.to : endDayTruth
+
+ if (!located || !stop) {
+ return
+ }
+
+ const { day, row, index } = located
+ const kind = stop.stopType ? STOP_KIND_BY_KEY[stop.stopType] : undefined
+ const KindIcon = kind?.Icon
+
+ const entry = row.entry
+ const arrive = displayTime(entry?.arrival, locale, timeFormat)
+ const leave = displayTime(entry?.departure, locale, timeFormat)
+
+ // Every finding filed at this stop, not just the one the chain had room for: being late
+ // and driving too far are separate answers and the sheet is where both fit.
+ const warnings: ScheduleWarning[] = [
+ ...day.schedule.warnings.filter(w => w.index === index && w.code === 'late'),
+ ...day.driveWarnings.filter(w => w.index === index && (w.code === 'leg' || w.code === 'range')),
+ ]
+ const warningText = (w: ScheduleWarning): string => {
+ if (w.code === 'late') return t('roadtrip.warn.late', { minutes: w.minutes ?? 0 })
+ if (w.code === 'range') return t('roadtrip.limit.range', { distance: formatDistance(w.sinceKm ?? 0, unit) })
+ return t('roadtrip.limit.legOver', { time: formatDurationShort((w.overMinutes ?? 0) * 60) })
+ }
+ const warningIcon = (w: ScheduleWarning): ReactNode => {
+ if (w.code === 'late') return
+ if (w.code === 'range') return
+ return
+ }
+
+ // One app offered means no picker: the tap opens it, exactly as the place sheet does.
+ // The stop's own name and position stand in when the place row is not to hand, so the
+ // one control a driver actually needs is there whatever else the device is missing.
+ const navTargets = getNavigationTargets(place ?? { name: stop.name, lat: stop.lat, lng: stop.lng })
+ const openDirections = () => {
+ if (navTargets.length === 1) openNavigationTarget(navTargets[0])
+ else if (navTargets.length > 1) setNavOpen(true)
+ }
+
+ const stayMinutes = stop.dwellMinutes
+ const canEditPlace = planner.can('place_edit', planner.trip)
+ const editStay = () => {
+ shell.openSheet('rtstay', { placeId: stop.placeId, minutes: stayMinutes })
+ }
+
+ // A negative id is the optimistic row of a stop still being saved. The editor would
+ // write the time against an id the server never issued, and handing it null instead is
+ // no way round that: the planner then falls back to the place's only visit, which can be
+ // that same row. So the pencil waits until the stop carries the id the server gave it.
+ const canOpenEditor = canEditPlace && place != null && stop.assignmentId > 0
+ const editPlace = () => {
+ if (!place) return
+ planner.openPlaceEditor(place, stop.assignmentId)
+ shell.closeSheet()
+ }
+
+ const toggleEndDay = async (next: boolean) => {
+ if (!canEndDay || saving) return
+ setPending({ from: endDayTruth, to: next })
+ setSaving(true)
+ try {
+ await planner.setRoadtripEndDay(stop)
+ } catch (err: unknown) {
+ setPending(null)
+ planner.toast.error(err instanceof Error ? err.message : t('common.unknownError'))
+ } finally {
+ setSaving(false)
+ }
+ }
+
+ // The camera rather than the place selection, for the reason the end-day switch above
+ // stays off it: the place inspector would come up over the map. `day` is the card the
+ // stop is drawn on, so a stop reached after a night drive shows on the stage that has it.
+ const showOnMap = () => {
+ showStopOnMap(planner, shell, stop, day.dayId)
+ shell.closeSheet()
+ }
+
+ const tiles = (navTargets.length > 0 ? 1 : 0) + 1
+
+ return (
+
+ {/* ── Header: the disc the chain draws, the name, the way to the editor and the way out ── */}
+
+ {/* Centred, not top-aligned: one line of the name is shorter than the 34px disc, so
+ hung from the top it sat high beside it. A name that wraps to its two lines grows
+ the row, and the disc and the buttons centre on both, as they do in the chain row. */}
+
+ {row.service ? (
+ kind && KindIcon ? (
+
+
+
+ ) : (
+
+
+
+ )
+ ) : (
+ // Deliberately not font-geist: that tier caps the weight at Medium and would
+ // quietly undo the bold on a number that has to read at 13px.
+
+ {row.number}
+
+ )}
+
+ {stop.name}
+
+
+ {canOpenEditor && (
+
+
+
+ )}
+
+
+
+
+
+
+
+
+ {/* ── The two clock readings, and where they come from ── */}
+ {(arrive || leave) && (
+
+
+ {arrive && (
+
+ {t('roadtrip.stay.arrive')}
+ {/* dir=ltr so a clock reads the same way round in an RTL locale. */}
+
+ {arrive}
+
+
+ )}
+ {leave && (
+
+ {t('roadtrip.stay.leave')}
+
+ {leave}
+
+
+ )}
+
+ {/* The desktop says this in a tooltip, which a phone has nowhere to put. */}
+
+ )}
+
+ {/* ── What this stop costs, and what the drive to it went past ── */}
+ {(!!stayMinutes || !!row.offRoadMeters || warnings.length > 0) && (
+
+ {navOpen && (
+ setNavOpen(false)}
+ title={t('inspector.openWith')}
+ />
+ )}
+
+ {/* ── Stopping here for the night. Offline too: it is a plan, not a lookup. ── */}
+ {canEndDay && (
+
+ )}
+
+ {/* ── Out to the map, with the stop marked on it ── */}
+
+
+
+
+
+ )
+}
diff --git a/client/src/mobile/screens/trip/roadtrip/stageBadges.test.ts b/client/src/mobile/screens/trip/roadtrip/stageBadges.test.ts
new file mode 100644
index 000000000..1a1bd29e9
--- /dev/null
+++ b/client/src/mobile/screens/trip/roadtrip/stageBadges.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest'
+import { badgeLabel, distanceBadge } from './stageBadges'
+
+// FE-MOB-RTBADGE-001 to FE-MOB-RTBADGE-004
+
+describe('distanceBadge', () => {
+ it('FE-MOB-RTBADGE-001: formats metres in the traveller\'s own unit', () => {
+ expect(distanceBadge(412_000, 'metric')).toBe('412 km')
+ expect(distanceBadge(412_000, 'imperial')).toBe('256 mi')
+ // A short hop keeps its metres reading, the one the route connectors print.
+ expect(distanceBadge(300, 'metric')).toBe('300 m')
+ })
+
+ it('FE-MOB-RTBADGE-002: nothing measured is no badge, never a 0 m one', () => {
+ expect(distanceBadge(0, 'metric')).toBeNull()
+ expect(distanceBadge(-5, 'metric')).toBeNull()
+ expect(distanceBadge(Number.NaN, 'metric')).toBeNull()
+ expect(distanceBadge(Number.POSITIVE_INFINITY, 'imperial')).toBeNull()
+ })
+})
+
+describe('badgeLabel', () => {
+ it('FE-MOB-RTBADGE-003: joins the parts with a comma and leaves the empty ones out', () => {
+ expect(badgeLabel(['Sat 2', null, '', undefined, '123 km'])).toBe('Sat 2, 123 km')
+ })
+
+ it('FE-MOB-RTBADGE-004: a single part is itself, and no parts is an empty name', () => {
+ expect(badgeLabel(['Sat 2'])).toBe('Sat 2')
+ expect(badgeLabel([])).toBe('')
+ expect(badgeLabel([null, undefined])).toBe('')
+ })
+})
diff --git a/client/src/mobile/screens/trip/roadtrip/stageBadges.ts b/client/src/mobile/screens/trip/roadtrip/stageBadges.ts
new file mode 100644
index 000000000..9f3e36243
--- /dev/null
+++ b/client/src/mobile/screens/trip/roadtrip/stageBadges.ts
@@ -0,0 +1,32 @@
+import { formatDistance } from '../../../../utils/units'
+import type { DistanceUnit } from '../../../../types'
+
+/**
+ * What the two bars of the road trip tab put in their badges, kept out of their markup.
+ *
+ * Phone only: the shell's stage header and the stage bar over the map are the two places
+ * that draw these figures as badges, and the desktop has neither of them.
+ */
+
+/**
+ * A distance as a badge reads it, or null when there is nothing to read.
+ *
+ * Nothing measured is no badge rather than a "0 m" one. A stage sits at zero while its
+ * legs are still routing, and a zero in a badge reads as a drive that goes nowhere, which
+ * is a claim, where a missing badge only says that the figure is not there yet.
+ */
+export function distanceBadge(meters: number, unit: DistanceUnit): string | null {
+ return Number.isFinite(meters) && meters > 0 ? formatDistance(meters / 1000, unit) : null
+}
+
+/**
+ * The accessible name of a button made of badges.
+ *
+ * The eye separates two pills by their edges, but the name a screen reader builds from
+ * them runs the texts together ("Sat 2123 km"), so the button spells the separators out.
+ * A comma rather than Intl.ListFormat: the parts are facts in a row, not a list with an
+ * "and" before its last item, and the client's ES2020 lib does not type that API anyway.
+ */
+export function badgeLabel(parts: readonly (string | null | undefined)[]): string {
+ return parts.filter((part): part is string => !!part).join(', ')
+}
diff --git a/client/src/mobile/screens/trip/roadtrip/useMRoadtrip.ts b/client/src/mobile/screens/trip/roadtrip/useMRoadtrip.ts
new file mode 100644
index 000000000..2485dd8c3
--- /dev/null
+++ b/client/src/mobile/screens/trip/roadtrip/useMRoadtrip.ts
@@ -0,0 +1,145 @@
+import { useEffect, useMemo, useState } from 'react'
+import { destinationCount, roadtripRows, stageClocks, stageEnd, stageOf, upNextStop } from '../../../../components/Roadtrip/roadtripRowModel'
+import { useRoadtripSettings } from '../../../../hooks/useRoadtripSettings'
+import { useSettingsStore } from '../../../../store/settingsStore'
+import { useTripStore } from '../../../../store/tripStore'
+import { isEffectivelyOffline, onNetworkModeChange } from '../../../../sync/networkMode'
+import type { RoadtripDay } from '@trek/shared/roadtrip'
+import type { MTripShellApi, TripPlanner } from '../MTripShell'
+import type { RoadtripRow, StopRow } from '../../../../components/Roadtrip/roadtripRowModel'
+import type { Category, Place } from '../../../../types'
+
+/** Minutes since midnight, local time. */
+const nowMinutes = (): number => {
+ const d = new Date()
+ return d.getHours() * 60 + d.getMinutes()
+}
+
+/** The same 30 s tick the day timeline runs on, so the two never disagree by a minute. */
+const TICK_MS = 30_000
+
+export interface MRoadtripController {
+ stage: RoadtripDay | null
+ rows: RoadtripRow[]
+ /** The head card's two figures, both taken from the arrival column the rows print. See stageClocks. */
+ clocks: ReturnType
+ /** The stop the bar over the map names, pictures and opens, with the clock it shows. See stageEnd. */
+ end: StopRow | null
+ /** The place row behind `end`, for the picture the bar leads with. Null without one. */
+ endPlace: Place | null
+ /** Its category, whose icon and colour stand in for a place that has no photo. */
+ endCategory: Category | null
+ stops: number
+ /** True while the routing round is still working through the trip's days. */
+ loading: boolean
+ /** The trip has the addon on but nothing routable: one place on a day is not a drive. */
+ empty: boolean
+ offline: boolean
+ electric: boolean
+ /** Next destination the plan still owes, today only. Negative minutesUntil is late. */
+ upNext: ReturnType
+ isToday: boolean
+}
+
+/**
+ * Everything the stage screen needs, kept out of its markup.
+ *
+ * The clock is the only moving part: a screen that shows a morning's plan all day
+ * quietly lies once you leave twenty minutes late, and the fix is arithmetic on the
+ * schedule rather than a request. Nothing here asks the network for anything.
+ */
+export function useMRoadtrip(planner: TripPlanner): MRoadtripController {
+ const { roadtripRoutes, selectedDayId, days } = planner
+ const vehicle = useRoadtripSettings(s => s.roadtrip_vehicle, planner.tripId)
+ const [minutes, setMinutes] = useState(nowMinutes)
+ const [offline, setOffline] = useState(isEffectivelyOffline)
+
+ useEffect(() => {
+ const id = window.setInterval(() => setMinutes(nowMinutes()), TICK_MS)
+ return () => window.clearInterval(id)
+ }, [])
+
+ useEffect(() => onNetworkModeChange(() => setOffline(isEffectivelyOffline())), [])
+
+ const stage = useMemo(
+ () => stageOf(roadtripRoutes.days, selectedDayId),
+ [roadtripRoutes.days, selectedDayId],
+ )
+
+ const rows = useMemo(() => (stage ? roadtripRows(stage) : []), [stage])
+ const clocks = useMemo(() => stageClocks(rows), [rows])
+ const end = useMemo(() => stageEnd(rows), [rows])
+
+ // The place behind the end comes from the whole trip store, not planner.places: with
+ // service stops hidden from the day lists the phone filters them out of that list, while
+ // the stage still draws them, and a day that ends at a hidden campsite still ends there.
+ // The stop sheet and the stage pins read the same list for the same reason.
+ const tripPlaces = useTripStore(s => s.places)
+ const endPlace = useMemo(
+ () => (end ? tripPlaces.find(p => p.id === end.stop.placeId) ?? null : null),
+ [end, tripPlaces],
+ )
+ const categories = planner.categories
+ const endCategory = useMemo(
+ () => (endPlace?.category_id == null ? null : categories.find(c => c.id === endPlace.category_id) ?? null),
+ [endPlace, categories],
+ )
+
+ // "Today" is the stage's own date, not the selected day's index: a trip can be
+ // planned for next year, and a countdown on a day in March is noise.
+ const isToday = useMemo(() => {
+ const date = days.find(d => d.id === selectedDayId)?.date
+ if (!date) return false
+ return date.slice(0, 10) === new Date().toISOString().slice(0, 10)
+ }, [days, selectedDayId])
+
+ return {
+ stage,
+ rows,
+ clocks,
+ end,
+ endPlace,
+ endCategory,
+ stops: stage ? destinationCount(stage) : 0,
+ loading: roadtripRoutes.loading,
+ empty: !roadtripRoutes.loading && roadtripRoutes.days.length === 0,
+ offline,
+ electric: vehicle === 'electric',
+ upNext: upNextStop(stage, minutes, isToday),
+ isToday,
+ }
+}
+
+/**
+ * Brings one stop of the drive into view on the map half, from wherever it was asked for.
+ *
+ * Through the camera and never through the planner's place selection: the place inspector
+ * opens off that selection, so selecting the place came up with the plan tab's card over
+ * the very map this was meant to show. The corridor search shows its hits the same way.
+ *
+ * `cardDayId` is the card the stop is DRAWN on, which after a night drive is not the day it
+ * is stored on. When that card is not the stage on screen it becomes the stage first, so the
+ * line around the stop the camera lands on is the stage the bar is about. With skipFit, as
+ * the day swipe does it: on the stage the camera follows focus points, and here the focus
+ * is the stop. The map area lets a focus go once the day moves off the one it arrived with,
+ * so the day is picked first, in the same tap, and the focus arrives together with it
+ * instead of being let go by it (see MMapArea).
+ */
+export function showStopOnMap(
+ planner: TripPlanner,
+ shell: MTripShellApi,
+ stop: { lat: number; lng: number },
+ cardDayId: number,
+): void {
+ if (planner.selectedDayId !== cardDayId) planner.handleSelectDay(cardDayId, true)
+ planner.focusRoadtripPoint(stop.lat, stop.lng)
+ if (shell.rtView === 'list') shell.toggleRtView()
+}
+
+/** The trip's own distance unit, for every figure the stage prints. */
+export function useDistanceUnit() {
+ return useSettingsStore(s => s.settings.distance_unit)
+}
+
+/** Kept for the tick's identity in tests. */
+export const ROADTRIP_TICK_MS = TICK_MS
diff --git a/client/src/mobile/screens/trip/roadtrip/useMRtAlternatives.ts b/client/src/mobile/screens/trip/roadtrip/useMRtAlternatives.ts
new file mode 100644
index 000000000..5a990b187
--- /dev/null
+++ b/client/src/mobile/screens/trip/roadtrip/useMRtAlternatives.ts
@@ -0,0 +1,136 @@
+import { useEffect, useTransition } from 'react'
+import { alternativesPhase, type AlternativeOverlay, type AlternativesPhase } from '../../../../components/Roadtrip/alternativeOverlays'
+import type { LegAlternatives } from '../../../../components/Roadtrip/useRouteAlternatives'
+import type { MTripShellApi, TripPlanner } from '../MTripShell'
+
+/**
+ * The alternatives bar's fixed height, in pixels. MRtAlternativesBar is drawn at exactly
+ * this, and the map floor below is worked out from it, so the two cannot drift apart.
+ */
+export const RT_ALT_BAR_HEIGHT = 174
+
+/**
+ * How far the map floor rises while the alternatives bar stands over the dock, in pixels.
+ *
+ * The bar's height plus the 15px gap between the top of the dock and the foot of a bar
+ * standing over it. So the floor lands on this bar's top edge and the round controls
+ * clear it rather than sitting in it. It is the only bar left in that slot: the stage bar
+ * that used to hold it whenever the map was up is gone.
+ *
+ * A number rather than a CSS length because the map's fit padding is added up from it.
+ * Kept in this module rather than in the bar's, so the map area reads it without pulling
+ * a component in.
+ */
+export const RT_ALT_BAR_LIFT = RT_ALT_BAR_HEIGHT + 15
+
+export interface MRtAlternativesController {
+ /** The leg being reconsidered and what came back for it. Null while no picker is open. */
+ open: LegAlternatives | null
+ /** The very overlays the map draws, so a chip and its line can never disagree. */
+ overlays: AlternativeOverlay[]
+ /** Which of its four states the open picker is in. Null while none is open. */
+ phase: AlternativesPhase | null
+ /** The road a tap is previewing, lit on the map and waiting for confirm. */
+ picked: AlternativeOverlay | null
+ /** May this person reshape the drive at all. Without it no leg offers the question. */
+ canAsk: boolean
+ /** False offline: a choice is written as a via, and vias are online only. */
+ editable: boolean
+ canConfirm: boolean
+ /** True while the chosen road is being written. */
+ saving: boolean
+ isOpenFor: (dayId: number, legIndex: number) => boolean
+ ask: (dayId: number, legIndex: number) => void
+ pick: (index: number) => void
+ confirm: () => void
+ cancel: () => void
+}
+
+/**
+ * Other ways of driving a leg, as a phone asks for them and takes one.
+ *
+ * Holds no picker state of its own. The road trip tab is mounted in two places, one per
+ * half of the list and map switch, so it remounts on every toggle, and a picker living
+ * here would be gone the moment somebody looked back at the chain. Everything stays in
+ * the planner, where the desk keeps it too: the open leg, the offers, the overlays and
+ * the road lit on the map. What this adds is what a desk does not need.
+ *
+ * A tap previews and a confirm takes. On the desk a pointer hovers to preview and a
+ * click writes; glass has no hover, so the first touch on a chip or a line would already
+ * be the write. Here that touch only lights the road (`pick`), and the bar's button
+ * commits it (`confirm`).
+ *
+ * The question is always about the leg on screen. Asking goes to the map, where the
+ * answer is drawn, and a stage change closes the picker, because offers drawn for a leg
+ * of another day are lines nobody on this stage asked about.
+ */
+export function useMRtAlternatives(planner: TripPlanner, shell: MTripShellApi): MRtAlternativesController {
+ const { open, close } = planner.routeAlternatives
+ const overlays = planner.alternativeOverlays
+ const editable = planner.roadtripVias.editable
+ const [saving, startSaving] = useTransition()
+
+ const phase = open ? alternativesPhase(open, overlays) : null
+ const highlighted = planner.highlightedAlternative
+ const picked = highlighted == null ? null : overlays.find(o => o.index === highlighted) ?? null
+ // The road already driven is no choice: taking it writes nothing and only closes the
+ // picker, which the close button already does without pretending to save.
+ const canConfirm = !!picked && phase === 'choose' && !open?.routes[picked.index]?.current && editable && !saving
+
+ const isOpenFor = (dayId: number, legIndex: number) => open?.dayId === dayId && open.index === legIndex
+
+ // The day chips, a swipe and the all days switch all move the stage under an open
+ // picker. `close` is the planner's stable callback, so this runs when the leg or the
+ // stage changes and not on every render.
+ const selectedDayId = planner.selectedDayId
+ useEffect(() => {
+ if (open && open.dayId !== selectedDayId) close()
+ }, [open, selectedDayId, close])
+
+ const ask = (dayId: number, legIndex: number) => {
+ // The planner's own ask toggles a leg that is already open, which is the desk
+ // button's second click. Here the pressed button on the chain is the way back to the
+ // answer on the map, so it must not close what it is pointing at.
+ if (!isOpenFor(dayId, legIndex)) {
+ // A pick belongs to the leg it was made on. Carried over, it would light a road
+ // on the next leg by its position in a list that leg never offered.
+ planner.setHighlightedAlternative(null)
+ // An open fuel search keeps the camera on its stations (see mapFocusPoints), so the
+ // leg would be asked about and never framed. The picker is modal on the map anyway.
+ planner.refuel.close()
+ // The card's day, as the desk passes it: the planner looks the stops up on that
+ // card and works out the day each one is stored on by itself.
+ planner.askRouteAlternatives(dayId, legIndex)
+ }
+ if (shell.rtView === 'list') shell.toggleRtView()
+ }
+
+ const pick = (index: number) => planner.setHighlightedAlternative(index)
+
+ const confirm = () => {
+ if (!canConfirm || !picked) return
+ const index = picked.index
+ // A transition rather than a flag of our own, so the pending state ends when the
+ // write does. The planner reports a failure itself and leaves the picker open for
+ // another go, and closes it once the via is saved.
+ startSaving(async () => {
+ await planner.chooseRouteAlternative(index)
+ })
+ }
+
+ return {
+ open,
+ overlays,
+ phase,
+ picked,
+ canAsk: planner.can('day_edit', planner.trip),
+ editable,
+ canConfirm,
+ saving,
+ isOpenFor,
+ ask,
+ pick,
+ confirm,
+ cancel: close,
+ }
+}
diff --git a/client/src/mobile/screens/trip/roadtrip/useMRtCorridor.ts b/client/src/mobile/screens/trip/roadtrip/useMRtCorridor.ts
new file mode 100644
index 000000000..da731eccb
--- /dev/null
+++ b/client/src/mobile/screens/trip/roadtrip/useMRtCorridor.ts
@@ -0,0 +1,146 @@
+import { useCallback, useEffect, useMemo } from 'react'
+import { anchorKmFor, corridorWindow, PHONE_REACH_KM, type CorridorReach } from '../../../../components/Roadtrip/corridorSearchModel'
+import { stageOf, upNextStop } from '../../../../components/Roadtrip/roadtripRowModel'
+import { useNetworkMode } from '../../../../hooks/useNetworkMode'
+import type { CorridorPoi } from '../../../../components/Roadtrip/useCorridorPois'
+import type { MTripShellApi, TripPlanner } from '../MTripShell'
+
+/** Minutes since midnight, local time: the same reading the stage screen takes. */
+const nowMinutes = (): number => {
+ const d = new Date()
+ return d.getHours() * 60 + d.getMinutes()
+}
+
+export interface MRtCorridorController {
+ /** What is being looked for. Several at once: they ride one query per box. */
+ categories: string[]
+ toggleCategory: (key: string) => void
+ /** How much of the stage the next search covers. */
+ reach: CorridorReach
+ setReach: (value: CorridorReach) => void
+ /** How far "ahead" reaches, in kilometres of driving. */
+ reachKm: number
+ /**
+ * True when "ahead" would start at the stop the clock says is next, false when it
+ * starts at the beginning of the stage. The sheet says which, because that difference
+ * is the whole meaning of the answer.
+ */
+ anchored: boolean
+ /** Asks. Does nothing without a route, a category and a connection. */
+ run: () => void
+ /** Throws the answer away, pins included. */
+ clear: () => void
+ canSearch: boolean
+ loading: boolean
+ progress: { done: number; total: number }
+ /** What was found, in driving order, and the same array the map draws. */
+ hits: CorridorPoi[]
+ /** True once a search has run and left something to read. */
+ answered: boolean
+ offline: boolean
+ error: boolean
+ capped: boolean
+ failedAreas: number
+ truncatedAreas: number
+}
+
+/**
+ * The corridor search, as a phone asks it.
+ *
+ * The state itself is the planner's: the map draws `corridor.visible`, so a search
+ * living inside a sheet would lose its pins the moment the sheet closed. What is added
+ * here is the two things a desk does not need: which stretch of the day to ask about,
+ * and where that stretch starts.
+ *
+ * Called from two places (the bar over the stage, and the sheet), so it holds no state
+ * of its own: the reach lives on the shell and everything else on the planner. The one
+ * thing that would need a clock (where "ahead" begins) is read at the moment the
+ * button is pressed rather than ticked, so this hook costs a screen nothing while
+ * nobody is searching.
+ *
+ * The stage on screen decides the day. Switching stages therefore drops the results,
+ * and that is not a special case handled here: `useCorridorPois` clears whenever the
+ * routed line changes, so an answer can never outlive the question it belongs to.
+ */
+export function useMRtCorridor(planner: TripPlanner, shell: MTripShellApi): MRtCorridorController {
+ const corridor = planner.roadtripCorridor
+ const { setDayId, clear: clearCorridor, search, categories, toggleCategory, stopsAlongKm } = corridor
+ const { offline } = useNetworkMode()
+ const reach = shell.rtReach
+
+ const stage = useMemo(
+ () => stageOf(planner.roadtripRoutes.days, planner.selectedDayId),
+ [planner.roadtripRoutes.days, planner.selectedDayId],
+ )
+
+ // The chip rail names the stage, so the stage names the drive being searched. Written
+ // as an effect rather than as a prop because `dayId` is also the desktop day picker's
+ // state, and only one of the two shells is ever mounted.
+ const stageDayId = stage ? String(stage.dayId) : ''
+ useEffect(() => {
+ if (stageDayId) setDayId(stageDayId)
+ }, [stageDayId, setDayId])
+
+ /**
+ * Whether the clock can say where the drive has got to.
+ *
+ * Only on the day itself, and only once one stop is behind: on the first stop of the
+ * morning "ahead" and "the whole stage" are the same stretch, and claiming a position
+ * nobody gave us would be worse than starting at the beginning.
+ */
+ const upNextIndexNow = useCallback((): number => {
+ if (!stage) return -1
+ const date = planner.days.find(d => d.id === planner.selectedDayId)?.date
+ const isToday = !!date && date.slice(0, 10) === new Date().toISOString().slice(0, 10)
+ const next = upNextStop(stage, nowMinutes(), isToday)
+ if (!next) return -1
+ return stage.stops.findIndex(s => s.assignmentId === next.row.stop.assignmentId)
+ }, [stage, planner.days, planner.selectedDayId])
+
+ const anchored = upNextIndexNow() > 0
+
+ const canSearch = !offline && categories.length > 0 && search.spine.length > 1
+
+ const runSearch = search.search
+ const run = useCallback(() => {
+ if (!canSearch) return
+ const index = upNextIndexNow()
+ runSearch(corridorWindow(anchorKmFor(stopsAlongKm, index > 0 ? index : null), reach))
+ }, [canSearch, runSearch, upNextIndexNow, stopsAlongKm, reach])
+
+ /**
+ * Changing the reach throws the answer away on purpose.
+ *
+ * Hits found in the fifty kilometres ahead are not an answer to "the whole stage", and
+ * a list that stays put while the chip above it says something else is the kind of
+ * quiet wrongness that gets a stop planned in the wrong place. The categories behave
+ * the same way one level down, in `useCorridorPois`.
+ */
+ const { setRtReach } = shell
+ const setReach = useCallback((value: CorridorReach) => {
+ if (value === reach) return
+ setRtReach(value)
+ clearCorridor()
+ }, [reach, setRtReach, clearCorridor])
+
+ return {
+ categories,
+ toggleCategory,
+ reach,
+ setReach,
+ reachKm: PHONE_REACH_KM,
+ anchored,
+ run,
+ clear: clearCorridor,
+ canSearch,
+ loading: search.loading,
+ progress: search.progress,
+ hits: corridor.visible,
+ answered: !search.loading && search.progress.total > 0,
+ offline,
+ error: search.error,
+ capped: search.capped,
+ failedAreas: search.failedAreas,
+ truncatedAreas: search.truncatedAreas,
+ }
+}
diff --git a/client/src/mobile/screens/trip/sheets/MMehrSheet.tsx b/client/src/mobile/screens/trip/sheets/MMehrSheet.tsx
index df164c23c..d4149eb5a 100644
--- a/client/src/mobile/screens/trip/sheets/MMehrSheet.tsx
+++ b/client/src/mobile/screens/trip/sheets/MMehrSheet.tsx
@@ -2,13 +2,12 @@ import { ChevronRight, FileDown, Settings, Share2 } from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import MSheet from '../../../components/MSheet'
import type { MTripSheetsProps } from '../MTripShell'
+import { dockTabIds } from '../dockTabs'
import { useTranslation } from '../../../../i18n'
-/** The sections living in the dock — everything else surfaces in this sheet. */
-const DOCK_IDS = new Set(['plan', 'transports', 'buchungen', 'finanzplan', 'listen'])
-
/** Demo tile tints per legacy tab id; plugins share the files neutral. */
const TILE_COLORS: Record = {
+ roadtrip: '#0a84ff',
transports: '#4A7DDB',
buchungen: '#9B5DE5',
listen: '#2FA9A0',
@@ -27,7 +26,10 @@ export default function MMehrSheet({ planner, shell }: MTripSheetsProps) {
const open = shell.sheet?.id === 'mehr'
const canEditTrip = planner.can('trip_edit', planner.trip)
- const gridTabs = planner.TRIP_TABS.filter(tab => !DOCK_IDS.has(tab.id))
+ // Derived from the same priority list the dock seats itself from, so a section
+ // can never show up in both places at once.
+ const seated = dockTabIds(new Set(planner.TRIP_TABS.map(tab => tab.id)))
+ const gridTabs = planner.TRIP_TABS.filter(tab => !seated.has(tab.id))
const tileStat = (id: string): string | null => {
if (id === 'dateien') {
diff --git a/client/src/mobile/screens/trip/sheets/MPlaceEditSheet.tsx b/client/src/mobile/screens/trip/sheets/MPlaceEditSheet.tsx
index a9027dbb8..e0c671950 100644
--- a/client/src/mobile/screens/trip/sheets/MPlaceEditSheet.tsx
+++ b/client/src/mobile/screens/trip/sheets/MPlaceEditSheet.tsx
@@ -14,7 +14,7 @@ import PlPlaceSearch, { type PlSearchPick } from './PlPlaceSearch'
import PlCategoryPicker from './PlCategoryPicker'
import PlTimeFields from './PlTimeFields'
import PlFileAttach from './PlFileAttach'
-import type { Place } from '../../../../types'
+import type { Assignment, AssignmentsMap, Place } from '../../../../types'
import type { TripPlanner } from '../MTripShell'
import { useLocationBias } from '../../../../hooks/useLocationBias'
@@ -48,6 +48,21 @@ function findDuplicateName(
return null
}
+/**
+ * The visit the editor was opened on, looked up in the planner's STORED list.
+ *
+ * Not planner.assignments: the phone filters booked nights (always) and service stops
+ * (while the day lists hide them) out of that one, and the road trip stop sheet opens
+ * this editor on exactly those visits. Looked up there the visit was not found, Start
+ * prefilled from the pool place, and a plain save wrote that over the time the stop was
+ * pinned to; the day note was dropped the same way. Every visit the plan tab shows is in
+ * the stored list as well, so its entry points resolve exactly as they did.
+ */
+function findVisit(stored: AssignmentsMap, assignmentId: number | null): Assignment | null {
+ if (!assignmentId) return null
+ return Object.values(stored).flat().find(a => a.id === assignmentId) ?? null
+}
+
/**
* Add/edit place sheet — the mobile counterpart of PlaceFormModal, driven by
* the planner's own editor flags (showPlaceForm / editingPlace / prefillCoords /
@@ -58,7 +73,7 @@ function findDuplicateName(
*/
export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSheetProps) {
const {
- t, toast, places, assignments, canUploadFiles,
+ t, toast, places, assignments, storedAssignments, canUploadFiles,
showPlaceForm, setShowPlaceForm,
editingPlace, setEditingPlace,
prefillCoords, setPrefillCoords,
@@ -84,11 +99,23 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
const [sheetPlace, setSheetPlace] = useState(null)
const [sheetAssignmentId, setSheetAssignmentId] = useState(null)
- const dayAssignments = useMemo(
- () => (sheetPlace ? Object.values(assignments).flat() : []),
- [sheetPlace, assignments],
+ // Live rather than the open-time snapshot, so the note's dirty check compares against
+ // the note as it stands when Save is tapped.
+ const ctxAssignment = useMemo(
+ () => (sheetPlace ? findVisit(storedAssignments, sheetAssignmentId) : null),
+ [sheetPlace, storedAssignments, sheetAssignmentId],
)
+ // The overlap warning keeps to what the day lists show: on the plan tab a clash with a
+ // pump or a booked night the list does not draw would name a stop nobody can see there.
+ // The visit under edit joins when the lists hide it, because the warning reads the day
+ // to compare against off that very row.
+ const dayAssignments = useMemo(() => {
+ if (!sheetPlace) return []
+ const listed = Object.values(assignments).flat()
+ return ctxAssignment && !listed.some(a => a.id === ctxAssignment.id) ? [...listed, ctxAssignment] : listed
+ }, [sheetPlace, assignments, ctxAssignment])
+
// Prefill on open — same source order as the desktop form: editing place
// (times off the in-context assignment), map/POI prefill coords, blank.
useEffect(() => {
@@ -96,9 +123,7 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
setSheetPlace(editingPlace)
setSheetAssignmentId(editingAssignmentId)
if (editingPlace) {
- const assignment = editingAssignmentId
- ? Object.values(assignments).flat().find(a => a.id === editingAssignmentId)
- : null
+ const assignment = findVisit(storedAssignments, editingAssignmentId)
const timeSource = assignment?.place ?? editingPlace
setForm({
name: editingPlace.name || '',
@@ -143,7 +168,7 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
setPendingFiles([])
setDuplicateWarning(null)
setDeleteArmed(false)
- // assignments is a fresh map each load — read at open time only.
+ // storedAssignments is a fresh map each load, so it is read at open time only.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [showPlaceForm, editingPlace, prefillCoords, editingAssignmentId])
@@ -236,7 +261,6 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
// #2163: the per-assignment note only travels when an assignment is in
// context AND the value actually changed — same dirty-check as the
// desktop form, so an untouched note never produces a PUT.
- const ctxAssignment = sheetAssignmentId ? dayAssignments.find(a => a.id === sheetAssignmentId) : null
if (!ctxAssignment || (form.assignment_notes ?? '') === (ctxAssignment.notes ?? '')) {
delete payload.assignment_notes
}
diff --git a/client/src/mobile/screens/trip/sheets/MTripSheets.tsx b/client/src/mobile/screens/trip/sheets/MTripSheets.tsx
index 65832416c..6c304c84c 100644
--- a/client/src/mobile/screens/trip/sheets/MTripSheets.tsx
+++ b/client/src/mobile/screens/trip/sheets/MTripSheets.tsx
@@ -23,6 +23,12 @@ import MNoteSheet, { type MNoteSheetPayload } from './MNoteSheet'
import MImportSheet from './MImportSheet'
import MExportSheet from './MExportSheet'
import MMehrSheet from './MMehrSheet'
+import MRtStopSheet from '../roadtrip/MRtStopSheet'
+import MRtStaySheet from '../roadtrip/MRtStaySheet'
+import MRtKindSheet from '../roadtrip/MRtKindSheet'
+import MRtInfoSheet from '../roadtrip/MRtInfoSheet'
+import MRtCorridorSheet from '../roadtrip/MRtCorridorSheet'
+import MRtDraftSheet from '../roadtrip/MRtDraftSheet'
import type { BookingExpenseRequest } from '../../../../components/Planner/BookingCostsSection.types'
import type { BudgetItem } from '../../../../types'
import type { MTripSheetsProps } from '../MTripShell'
@@ -63,6 +69,17 @@ export default function MTripSheets({ planner, shell }: MTripSheetsProps) {
+ {/* The stage's own sheets. Each one checks shell.sheet?.id itself, the draft
+ sheet hangs off planner.stopDraft the way the place editor hangs off its flag. */}
+
+
+
+
+ {/* Before the draft sheet, not after: both sit at the same z, so the one mounted
+ later paints on top, and taking a hit onto the trip opens the draft OVER the
+ search it came from. */}
+
+
case 'listen':
return
+ // The only tab with two halves of its own: the chain, or the same map showing
+ // the stage. Both are this one component, because they share a stage and the
+ // switch between them must not lose it.
+ case 'roadtrip':
+ return
default:
return {null}
}
diff --git a/client/src/pages/JourneyDetailPage.tsx b/client/src/pages/JourneyDetailPage.tsx
index 8d618df2f..b869a7fa0 100644
--- a/client/src/pages/JourneyDetailPage.tsx
+++ b/client/src/pages/JourneyDetailPage.tsx
@@ -14,7 +14,7 @@ import {
Plus, ChevronUp, ChevronDown, Eye, EyeOff, BookOpen, Image, Search, X,
} from 'lucide-react'
import MobileMapTimeline from '../components/Journey/MobileMapTimeline'
-import DawarichSuggestionsPanel from '../components/Dawarich/DawarichSuggestionsPanel'
+import JourneyDayDawarich from '../components/Journey/JourneyDayDawarich'
import MobileEntryView from '../components/Journey/MobileEntryView'
import { useJourneyStore } from '../store/journeyStore'
import { computeJourneyLifecycle } from '../utils/journeyLifecycle'
@@ -47,6 +47,7 @@ function JourneyDetailPageDesktop() {
unlinkTrip, setUnlinkTrip, showSettings, setShowSettings,
hideSkeletons, setHideSkeletons,
query, setQuery, dismissSuggestion, restoreSuggestions, openAtEntryId,
+ dawarichByDate, dawarichBusyId, acceptDawarich, dismissDawarich,
mapRef, fullMapRef, galleryUploadRef, galleryProviders, setGalleryProviders, galleryBrowseRef,
activeLocationId, handleMarkerClick, handleLocationClick,
mapEntries, sidebarMapItems, tripDates, isMobile, tracks,
@@ -70,7 +71,14 @@ function JourneyDetailPageDesktop() {
query,
)
const dayGroups = groupByDate(timelineEntries)
- const sortedDates = [...dayGroups.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
+ // A stay falls on the day it happened, and that is often a day the journal has no entry
+ // on yet — which is the whole point of offering it. Those days join the timeline so the
+ // stay can be reached; without them the only way to a quiet day's stays would be to
+ // write an entry on it first. Not while a search is running: a day whose entries the
+ // query filtered out is not a day the reader is looking at.
+ const suggestionDates = canEditEntries && !query ? [...dawarichByDate.keys()] : []
+ const sortedDates = [...new Set([...dayGroups.keys(), ...suggestionDates])]
+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
const tripDateMin = current.trips.length
? current.trips.reduce((min: string, t: any) => t.start_date && (!min || t.start_date < min) ? t.start_date : min, '')
@@ -323,7 +331,10 @@ function JourneyDetailPageDesktop() {
{[
- { value: sortedDates.length, label: t('journey.stats.days') },
+ // The journal's own days, not the ones a pending stay added to the
+ // timeline: "11 days" for a trip of 7 counts somebody else's data as
+ // the journey.
+ { value: dayGroups.size, label: t('journey.stats.days') },
{ value: current.stats.places, label: t('journey.stats.places') },
{ value: current.stats.entries, label: t('journey.stats.entries') },
{ value: current.stats.photos, label: t('journey.stats.photos') },
@@ -413,20 +424,7 @@ function JourneyDetailPageDesktop() {
{/* Timeline (desktop only — mobile uses fullscreen combined view above) */}
{!isMobile && (
- {/* Stays Dawarich recorded over this journal's dates, waiting to
- be turned into entries (#2279). Above the timeline because
- that is what they become; renders nothing when there is
- nothing pending. */}
- {canEditEntries && (
- { void loadJourney(current.id) }}
- />
- )}
-
- {sortedDates.length === 0 && (
+ {dayGroups.size === 0 && sortedDates.length === 0 && (
{
- const entries = dayGroups.get(date)!
+ // Empty on a day that only has stays waiting on it.
+ const entries = dayGroups.get(date) ?? []
+ const stays = canEditEntries ? dawarichByDate.get(date) ?? [] : []
const fd = formatDate(date, locale)
const locations = [...new Set(entries.map(e => e.location_name).filter(Boolean))]
@@ -550,6 +550,16 @@ function JourneyDetailPageDesktop() {
)
})}
+
+ {/* What Dawarich recorded on this day, folded into it. One line
+ with a count, the mark for where it came from, and the rows on
+ a tap. Nothing at all on a day with nothing pending. */}
+
)
})}
diff --git a/client/src/pages/JourneyDetailPage.wiring.test.tsx b/client/src/pages/JourneyDetailPage.wiring.test.tsx
index 593385ed8..52abdb574 100644
--- a/client/src/pages/JourneyDetailPage.wiring.test.tsx
+++ b/client/src/pages/JourneyDetailPage.wiring.test.tsx
@@ -100,6 +100,10 @@ function buildHook(over: Record = {}): Record
hideSkeletons: false, setHideSkeletons: vi.fn(),
query: '', setQuery: vi.fn(), dismissSuggestion: vi.fn(async () => {}),
restoreSuggestions: vi.fn(async () => {}), openAtEntryId: null,
+ // The stays Dawarich recorded, by the day they fall on. Empty here: the fold each day
+ // carries has its own suite (FE-JRN-DAYDAW), and what this file pins is the wiring.
+ dawarichByDate: new Map(), dawarichBusyId: null,
+ acceptDawarich: vi.fn(async () => {}), dismissDawarich: vi.fn(),
mapRef: { current: null }, fullMapRef: { current: null }, galleryUploadRef: { current: null },
galleryProviders: [], setGalleryProviders: vi.fn(), galleryBrowseRef: { current: null },
activeLocationId: null, handleMarkerClick: vi.fn(), handleLocationClick: vi.fn(),
diff --git a/client/src/pages/journeyDetail/useJourneyDetail.ts b/client/src/pages/journeyDetail/useJourneyDetail.ts
index 7d267bcd9..69627f81c 100644
--- a/client/src/pages/journeyDetail/useJourneyDetail.ts
+++ b/client/src/pages/journeyDetail/useJourneyDetail.ts
@@ -12,6 +12,9 @@ import { useIsMobile } from '../../hooks/useIsMobile'
import { lockBodyScroll } from '../../utils/bodyScrollLock'
import type { JourneyEntry } from '../../store/journeyStore'
import { createDraftJourneyEntry } from './JourneyDetailPage.helpers'
+import { useDawarichSuggestions } from '../../hooks/useDawarichSuggestions'
+import { openStaysByDate } from '../../components/Dawarich/dawarichSuggestionModel'
+import type { DawarichSuggestion, DawarichSuggestionTarget } from '@trek/shared'
import { useDawarichJournalTrail } from '../../hooks/useDawarichJournalTrail'
@@ -298,6 +301,34 @@ export function useJourneyDetail() {
}
}, [current, loadJourney, toast, t])
+ /**
+ * The stays Dawarich recorded over this journal's dates, by the day they happened on.
+ *
+ * Read here rather than inside a panel so the timeline can fold each day's stays into
+ * that day (discussion with Roel, 16.09.): stacked above the entries, a fortnight of
+ * driving put forty rows between the reader and their own first entry.
+ *
+ * Only what is still open — an accepted stay is an entry on the timeline already, and a
+ * dismissed one was waved away on purpose. Within a day the order is the order they were
+ * lived in, which is what makes a run of them read as an afternoon.
+ */
+ const dawarich = useDawarichSuggestions()
+ const dawarichByDate = useMemo(() => openStaysByDate(dawarich.suggestions), [dawarich.suggestions])
+
+ /**
+ * Accepting writes the stay into THIS journal and reloads it, which is how the new entry
+ * reaches the timeline the stay was standing in.
+ */
+ const acceptDawarich = useCallback(async (suggestion: DawarichSuggestion, target: DawarichSuggestionTarget) => {
+ if (!current) return
+ const ok = await dawarich.accept(suggestion.id, { target, journalId: current.id })
+ if (ok) await loadJourney(current.id)
+ }, [dawarich, current, loadJourney])
+
+ const dismissDawarich = useCallback((suggestion: DawarichSuggestion) => {
+ void dawarich.dismiss(suggestion.id)
+ }, [dawarich])
+
const handleMarkerClick = useCallback((entryId: string) => {
const el = document.querySelector(`[data-entry-id="${entryId}"]`)
if (!el) return
@@ -503,6 +534,7 @@ export function useJourneyDetail() {
unlinkTrip, setUnlinkTrip, showSettings, setShowSettings,
hideSkeletons, setHideSkeletons,
query, setQuery, dismissSuggestion, restoreSuggestions,
+ dawarichByDate, dawarichBusyId: dawarich.busyId, acceptDawarich, dismissDawarich,
openAtEntryId,
mapRef, fullMapRef, galleryUploadRef, galleryProviders, setGalleryProviders, galleryBrowseRef,
activeLocationId, handleMarkerClick, handleLocationClick,
diff --git a/client/src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx b/client/src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx
index 71e6f4eef..9644cec18 100644
--- a/client/src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx
+++ b/client/src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx
@@ -1,5 +1,5 @@
import { roadtripPreferencesRepo } from '../../repo/roadtripPreferencesRepo'
-// FE-TP-ROAD-001 to FE-TP-ROAD-074
+// FE-TP-ROAD-001 to FE-TP-ROAD-099
import React from 'react'
import { renderHook, act, waitFor } from '@testing-library/react'
import { TranslationProvider } from '../../i18n/TranslationContext'
@@ -87,6 +87,10 @@ const rt = vi.hoisted(() => {
remove: vi.fn(async () => {}),
reanchor: vi.fn(async () => {}),
}
+ // What the routing round was last called with. The round itself is a fixture, so
+ // the arguments are the only place the planner's own decisions are visible: which
+ // days it is willing to route, and which assignment list it builds them from.
+ const routesArgs = { current: [] as unknown[] }
const routes = {
days: [] as Array>,
quietDays: [] as unknown[],
@@ -141,13 +145,21 @@ const rt = vi.hoisted(() => {
ask: vi.fn(),
close: vi.fn(),
}
- return { vias, routes, corridor, alt }
+ // Hands out a fresh copy of `alt` on every render when set, the identity the real hook
+ // had before it was memoised. A stable fixture runs an effect keyed on it once and never
+ // again, which is exactly how a close gate that fired on every render went unseen.
+ const altFresh = { current: false }
+ return { vias, routes, corridor, alt, altFresh, routesArgs }
})
vi.mock('../../components/Roadtrip/useRoadtripVias', () => ({ useRoadtripVias: () => rt.vias }))
-vi.mock('../../components/Roadtrip/useRoadtripRoutes', () => ({ useRoadtripRoutes: () => rt.routes }))
+vi.mock('../../components/Roadtrip/useRoadtripRoutes', () => ({
+ useRoadtripRoutes: (...args: unknown[]) => { rt.routesArgs.current = args; return rt.routes },
+}))
vi.mock('../../components/Roadtrip/useRoadtripCorridor', () => ({ useRoadtripCorridor: () => rt.corridor }))
-vi.mock('../../components/Roadtrip/useRouteAlternatives', () => ({ useRouteAlternatives: () => rt.alt }))
+vi.mock('../../components/Roadtrip/useRouteAlternatives', () => ({
+ useRouteAlternatives: () => (rt.altFresh.current ? { ...rt.alt } : rt.alt),
+}))
vi.mock('../../components/Roadtrip/useFollowTrack', () => ({
useFollowTrack: () => ({ busy: false, dayId: null, run: vi.fn(), attach: vi.fn(), detach: vi.fn() }),
}))
@@ -295,6 +307,7 @@ beforeEach(() => {
rt.vias.stale = false
rt.vias.editable = true
rt.routes.days = []
+ rt.routesArgs.current = []
rt.routes.lines = []
rt.routes.lineDays = []
rt.corridor.day = undefined
@@ -304,6 +317,7 @@ beforeEach(() => {
rt.corridor.search.spine = []
rt.corridor.insertIndexFor.mockReturnValue(1)
rt.alt.open = null
+ rt.altFresh.current = false
usePluginStore.setState({ plugins: [], loaded: true })
useBackgroundTasksStore.setState({ tasks: [] })
@@ -1926,3 +1940,231 @@ it('preserves exclusive service stops when reordering the visible Days stops', a
await act(async () => result.current.handleReorder(5, [13, 11]))
expect(actions.reorderAssignments).toHaveBeenCalledWith(42, 5, [13, 12, 11])
})
+
+/**
+ * The phone's own way into the drive.
+ *
+ * Road trip MODE is a data switch, not a view switch: `assignments` and `places` are
+ * derived from it for the whole hook, and every permanently mounted sheet of the phone
+ * shell reads those same two lists. The phone has no control that turns the mode back
+ * off, so it never turns it on. `roadtripMode = storedRoadtripMode && !isMobile` stays
+ * exactly as it is, and the tab feeds the routing round instead.
+ */
+describe('useTripPlanner road trip: the phone feed', () => {
+ let desktopWidth: number
+
+ beforeEach(() => {
+ desktopWidth = window.innerWidth
+ Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: 390 })
+ })
+
+ afterEach(() => {
+ Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: desktopWidth })
+ })
+
+ /** The days the routing round was handed. Empty means it is standing down. */
+ const fedDays = () => rt.routesArgs.current[1] as Array<{ id: number }>
+ /** The assignment list the drive is built from. */
+ const fedAssignments = () => rt.routesArgs.current[2] as Record>
+
+ /** The routed shape of one day, which `renderRoadtrip` builds for the desk suites. */
+ const routeDay = (dayId: number) => {
+ rt.routes.days = [{
+ dayId,
+ dayNumber: 1,
+ schedule: { entries: [] },
+ legs: [],
+ stops: [0, 1, 2].map((i) => ({
+ assignmentId: i + 1, placeId: i + 1, lat: 53 - i, lng: 10 + i,
+ ownerDayId: dayId, ownerIndex: i,
+ })),
+ }]
+ }
+
+ /** Mount on a phone and wait until the addon feed has answered. */
+ async function renderPhone() {
+ const rendered = renderHook(() => useTripPlanner(), { wrapper })
+ await act(async () => { await Promise.resolve() })
+ // The drive tab exists on the phone and nowhere else, so its arrival doubles as
+ // the proof that the addon feed landed.
+ await waitFor(() => expect(rendered.result.current.TRIP_TABS.some(tab => tab.id === 'roadtrip')).toBe(true))
+ return rendered
+ }
+
+ it('FE-TP-ROAD-090: the phone opens the feed and leaves the mode alone', async () => {
+ seedTrip({ days: [buildDay({ id: 5, day_number: 1 })] })
+ sessionStorage.setItem('trip-tab-42', 'roadtrip')
+
+ const { result } = await renderPhone()
+
+ // The session still carries the switch from an earlier, wider window, which is
+ // the whole point: narrowing past the breakpoint must not bring the mode along.
+ expect(sessionStorage.getItem('trip-roadtrip-42')).toBe('1')
+ expect(result.current.roadtripMode).toBe(false)
+ expect(result.current.roadtripActive).toBe(false)
+ expect(result.current.roadtripFeedActive).toBe(true)
+ })
+
+ it('FE-TP-ROAD-091: a phone that never opened the drive routes nothing', async () => {
+ seedTrip({ days: [buildDay({ id: 5, day_number: 1 })] })
+
+ const { result } = await renderPhone()
+
+ expect(result.current.activeTab).toBe('plan')
+ expect(result.current.roadtripFeedActive).toBe(false)
+ // A day costs a rate-limited routing request, so the tab has to be asked for first.
+ expect(fedDays()).toHaveLength(0)
+ })
+
+ it('FE-TP-ROAD-092: with the drive tab open the round is handed the trip days', async () => {
+ seedTrip({ days: [buildDay({ id: 5, day_number: 1 }), buildDay({ id: 6, day_number: 2 })] })
+ sessionStorage.setItem('trip-tab-42', 'roadtrip')
+
+ const { result } = await renderPhone()
+
+ expect(result.current.roadtripFeedActive).toBe(true)
+ expect(fedDays().map(d => d.id)).toEqual([5, 6])
+ })
+
+ it('FE-TP-ROAD-093: the round is fed the STORED list, the day sheet keeps the filtered one', async () => {
+ const town = buildPlace({ id: 101, name: 'Bergen' })
+ const fuelStop = buildPlace({ id: 102, name: 'Tankstelle', stop_type: 'fuel' })
+ const hotel = buildPlace({ id: 103, name: 'Fjordhotell' })
+ seedTrip({
+ places: [town, fuelStop, hotel],
+ days: [buildDay({ id: 5, day_number: 1 })],
+ assignments: {
+ '5': [
+ buildAssignment({ id: 11, day_id: 5, order_index: 0, place: town }),
+ buildAssignment({ id: 12, day_id: 5, order_index: 1, place: fuelStop }),
+ buildAssignment({ id: 13, day_id: 5, order_index: 2, place: hotel, accommodation_id: 9 }),
+ ],
+ },
+ })
+ useSettingsStore.setState(s => ({ settings: { ...s.settings, roadtrip_service_stops_in_days: false } }))
+ sessionStorage.setItem('trip-tab-42', 'roadtrip')
+
+ const { result } = await renderPhone()
+
+ // What the day sheet, the day list and the PDF export read: the pump is switched
+ // out of the plan, and the booked night is already its own overnight block.
+ expect(result.current.assignments['5'].map(v => v.id)).toEqual([11])
+ // What the drive is built from: the pump it stops at and the night it ends on.
+ expect(fedAssignments()['5'].map(v => v.id)).toEqual([11, 12, 13])
+ })
+
+ it('FE-TP-ROAD-094: leaving the drive tab does not throw the routed legs away', async () => {
+ seedTrip({ days: [buildDay({ id: 5, day_number: 1 })] })
+ sessionStorage.setItem('trip-tab-42', 'roadtrip')
+
+ const { result } = await renderPhone()
+ act(() => { result.current.handleTabChange('plan') })
+
+ expect(result.current.activeTab).toBe('plan')
+ expect(result.current.roadtripFeedActive).toBe(true)
+ expect(fedDays().map(d => d.id)).toEqual([5])
+ })
+ it('FE-TP-ROAD-095: a hit found on the phone lands in the chain, not in the full place form', async () => {
+ // The sharp one. `roadtripActive` is false on a phone by design, so gating the
+ // corridor branch on it sent every hit the stage map found into the ordinary place
+ // form, losing the stop kind, the stay, and the position worked out just above it.
+ seedTrip({ days: [buildDay({ id: 5, day_number: 1 })] })
+ sessionStorage.setItem('trip-tab-42', 'roadtrip')
+ rt.corridor.day = { dayId: 5, dayNumber: 1 }
+ rt.corridor.insertIndexFor.mockReturnValue(2)
+ routeDay(5)
+
+ const { result } = await renderPhone()
+ act(() => { result.current.handlePoiClick(poi() as never) })
+
+ expect(result.current.roadtripActive).toBe(false)
+ expect(result.current.stopDraft).toMatchObject({ dayId: 5, position: 2, dayNumber: 1 })
+ expect(result.current.showPlaceForm).toBe(false)
+ })
+
+ it('FE-TP-ROAD-096: an ordinary POI on the phone still carries the stage it was tapped on', async () => {
+ seedTrip({ days: [buildDay({ id: 5, day_number: 1 })] })
+ sessionStorage.setItem('trip-tab-42', 'roadtrip')
+ rt.corridor.day = { dayId: 5, dayNumber: 1 }
+
+ const { result } = await renderPhone()
+ const { alongKm: _drop, offRouteKm: _drop2, ...plain } = poi()
+ act(() => { result.current.handlePoiClick(plain as never) })
+
+ // Without the day it lands in the unplanned pool, which the stage does not show.
+ expect(result.current.showPlaceForm).toBe(true)
+ expect(result.current.placeFormDayId).toBe(5)
+ })
+
+ it('FE-TP-ROAD-097: a service stop opened for editing on the phone gets the place form with its own visit', async () => {
+ // The stop sheet's pencil relies on this. The desk popup it would otherwise open has
+ // no start time, and for a service stop the start time is the only way to pin or
+ // unpin its arrival (a booked night can also be held by the booking's check-in).
+ const fuelStop = buildPlace({ id: 102, name: 'Tankstelle', stop_type: 'fuel', lat: 60.39, lng: 5.32 })
+ seedTrip({
+ places: [fuelStop],
+ days: [buildDay({ id: 5, day_number: 1 })],
+ assignments: { '5': [buildAssignment({ id: 12, day_id: 5, order_index: 0, place: fuelStop })] },
+ })
+ // The STORED mode is on, set here rather than trusted to the suite's beforeEach: with
+ // it off the form branch would be taken anyway and this test would prove nothing.
+ sessionStorage.setItem('trip-roadtrip-42', '1')
+ sessionStorage.setItem('trip-tab-42', 'roadtrip')
+
+ const phone = await renderPhone()
+ act(() => { phone.result.current.openPlaceEditor(fuelStop, 12) })
+
+ expect(phone.result.current.roadtripMode).toBe(false)
+ expect(phone.result.current.stopDraft).toBeNull()
+ expect(phone.result.current.showPlaceForm).toBe(true)
+ expect(phone.result.current.editingPlace?.id).toBe(102)
+ expect(phone.result.current.editingAssignmentId).toBe(12)
+ phone.unmount()
+
+ // The very same trip at desk width opens the stop popup, so what kept the phone on
+ // the form is the width alone.
+ Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: desktopWidth })
+ const desk = await renderRoadtrip()
+ act(() => { desk.result.current.openPlaceEditor(fuelStop, 12) })
+
+ expect(desk.result.current.stopDraft).toMatchObject({ dayId: 5, editing: { placeId: 102, stopType: 'fuel' } })
+ expect(desk.result.current.showPlaceForm).toBe(false)
+ })
+
+ it('FE-TP-ROAD-098: a picker open on the drive tab survives the next render, with the mode still off', async () => {
+ // The blocker the phone picker hit. The close gate read `roadtripActive`, which is false
+ // on a phone by design, and ran on every render because the hook handed out a new
+ // object each time: asking set the picker loading, the render after it closed it again.
+ // The fixture hands out a fresh object per render so the gate is proven on its own,
+ // whatever identity the hook keeps.
+ seedTrip({ days: [buildDay({ id: 5, day_number: 1 })] })
+ sessionStorage.setItem('trip-tab-42', 'roadtrip')
+ rt.alt.open = { dayId: 5, index: 0, routes: [], loading: true, error: false }
+ rt.altFresh.current = true
+
+ const { result, rerender } = await renderPhone()
+ rt.alt.close.mockClear()
+ rerender()
+ rerender()
+
+ expect(rt.alt.close).not.toHaveBeenCalled()
+ expect(result.current.roadtripActive).toBe(false)
+ expect(result.current.roadtripMode).toBe(false)
+ })
+
+ it('FE-TP-ROAD-099: leaving the drive tab on a phone closes the picker, though the feed stays on', async () => {
+ // The phone's counterpart of FE-TP-ROAD-044: the overlay depends only on the picker, so
+ // a tab that no longer shows the bar must not leave the other roads drawn on its map.
+ seedTrip({ days: [buildDay({ id: 5, day_number: 1 })] })
+ sessionStorage.setItem('trip-tab-42', 'roadtrip')
+ rt.alt.open = { dayId: 5, index: 0, routes: [], loading: false, error: false }
+
+ const { result } = await renderPhone()
+ rt.alt.close.mockClear()
+ act(() => { result.current.handleTabChange('plan') })
+
+ await waitFor(() => expect(rt.alt.close).toHaveBeenCalled())
+ // The routed legs are kept (FE-TP-ROAD-094), so it is the tab that closed it, not the feed.
+ expect(result.current.roadtripFeedActive).toBe(true)
+ })
+})
diff --git a/client/src/pages/tripPlanner/useTripPlanner.ts b/client/src/pages/tripPlanner/useTripPlanner.ts
index 11069bc95..60e72b71f 100644
--- a/client/src/pages/tripPlanner/useTripPlanner.ts
+++ b/client/src/pages/tripPlanner/useTripPlanner.ts
@@ -9,7 +9,7 @@ import { useSettingsStore } from '../../store/settingsStore'
import { dayColor } from '../../components/Roadtrip/dayColors'
import { getCached, fetchPhoto } from '../../services/photoService'
import { useToast } from '../../components/shared/Toast'
-import { Map, Ticket, PackageCheck, Wallet, FolderOpen, Users, Train } from 'lucide-react'
+import { Map, Ticket, PackageCheck, Wallet, FolderOpen, Users, Train, Route } from 'lucide-react'
import { resolvePluginIcon } from '../../components/shared/PluginIcon'
import { useTranslation, translateApiError } from '../../i18n'
import { addonsApi, accommodationsApi, authApi, tripsApi, assignmentsApi, healthApi, airtrailApi, mapsApi, placesApi } from '../../api/client'
@@ -34,6 +34,7 @@ import { useTripRouteOverview } from '../../components/Map/useTripRouteOverview'
import { useDawarichTrail } from '../../components/Map/useDawarichTrail'
import { collapsedDayDates } from '../../components/Map/dawarichTrail'
import { useRoadtripCorridor } from '../../components/Roadtrip/useRoadtripCorridor'
+import { PHONE_CORRIDOR_OPTIONS } from '../../components/Roadtrip/corridorSearchModel'
import { useRoadtripVias } from '../../components/Roadtrip/useRoadtripVias'
import { useRefuelSearch } from '../../components/Roadtrip/useRefuelSearch'
import type { RefuelCandidate } from '../../components/Roadtrip/refuelSuggestion'
@@ -222,6 +223,9 @@ export function useTripPlanner() {
{ id: 'plan', label: t(TRIP_TAB_LABEL_KEYS.plan), icon: Map },
{ id: 'transports', label: t(TRIP_TAB_LABEL_KEYS.transports), icon: Train },
{ id: 'buchungen', label: t(TRIP_TAB_LABEL_KEYS.buchungen), shortLabel: t('trip.tabs.reservationsShort'), icon: Ticket },
+ // Phone only: the desktop reaches the drive through the mode switch beside the
+ // day plan, and a second entry point there would be a tab nobody needs.
+ ...(enabledAddons.roadtrip && isMobile ? [{ id: 'roadtrip', label: t(TRIP_TAB_LABEL_KEYS.roadtrip), icon: Route }] : []),
...(enabledAddons.packing ? [{ id: 'listen', label: t(TRIP_TAB_LABEL_KEYS.listen), shortLabel: t('trip.tabs.listsShort'), icon: PackageCheck }] : []),
...(enabledAddons.budget ? [{ id: 'finanzplan', label: t(TRIP_TAB_LABEL_KEYS.finanzplan), icon: Wallet }] : []),
...(enabledAddons.documents ? [{ id: 'dateien', label: t(TRIP_TAB_LABEL_KEYS.dateien), icon: FolderOpen }] : []),
@@ -625,12 +629,30 @@ export function useTripPlanner() {
// Road trip mode reads the whole trip, not the selected day, so it owns its own legs.
// Passing no days while the mode is off keeps it inert — no routing requests, no state.
const roadtripActive = !!enabledAddons.roadtrip && roadtripMode
+ // The phone's own way into the drive, and the reason line 148 above stays as it is.
+ //
+ // `roadtripMode` is not a view switch, it is a data switch: `assignments` and
+ // `places` are derived from it for the whole hook, and every permanently mounted
+ // sheet of the phone shell reads those same lists. Letting the phone flip it would
+ // bring back exactly the regressions the comment up there describes, on paths that
+ // never touch a tab. The second tap on a day chip opens the day sheet, the More
+ // button opens the PDF export.
+ //
+ // So the phone feeds the routing round instead, and nothing else. Once the tab has
+ // been opened the feed stays on for as long as the trip is: a tab switch must not
+ // throw away legs that cost a rate-limited request each.
+ const roadtripTabSeen = useRef(false)
+ if (activeTab === 'roadtrip') roadtripTabSeen.current = true
+ const roadtripFeedActive = !!enabledAddons.roadtrip
+ && (roadtripMode || (isMobile && (activeTab === 'roadtrip' || roadtripTabSeen.current)))
const roadtripPreferencesState = useLoadRoadtripSettings(tripId, !!enabledAddons.roadtrip)
useEffect(() => {
if (roadtripPreferencesState.failed) toast.error(t('common.error'))
}, [roadtripPreferencesState.failed, toast, t])
const dailyTimesActive = !!dayWindow(roadtripSettings.roadtrip_day_start, roadtripSettings.roadtrip_day_end)
- const dayBoundaries = useDayBoundaries(tripId, roadtripActive && dailyTimesActive, assignments)
+ // Fed from the same flag as the routing round: without the boundaries the phone
+ // would draw a drive that never ends for the night.
+ const dayBoundaries = useDayBoundaries(tripId, roadtripFeedActive && dailyTimesActive, assignments)
useEffect(() => { if (dayBoundaries.stale) toast.error(t('trip.toast.loadError')) }, [dayBoundaries.stale, toast, t])
const resetDayBoundaries = dayBoundaries.editable && dayBoundaries.boundaries.length && can('day_edit', trip) ? async () => {
try {
@@ -648,8 +670,11 @@ export function useTripPlanner() {
const refuel = useRefuelSearch()
const roadtripRoutes = useRoadtripRoutes(
tripId,
- roadtripActive && roadtripPreferencesState.ready ? days : EMPTY_DAYS,
- assignments,
+ roadtripFeedActive && roadtripPreferencesState.ready ? days : EMPTY_DAYS,
+ // Deliberately the stored list, not the filtered one: the drive wants the
+ // service stops and the night a lodging booking put on the map, and the filter
+ // above only exists to keep those out of a day list read as a plan.
+ roadtripFeedActive ? storedAssignments : assignments,
routeProfile,
roadtripVias.byDay,
dayBoundaries.boundaries,
@@ -658,7 +683,10 @@ export function useTripPlanner() {
// Lives here rather than in the panel because the map draws what it finds.
// The trip comes with it for the vehicle: an electric car looks for chargers rather
// than for pumps, and that preference is stored per trip.
- const roadtripCorridor = useRoadtripCorridor(roadtripRoutes, tripId)
+ // The phone searches under a smaller ceiling: fewer boxes, a capped retry pass and a
+ // deadline, because a search that keeps the radio warm costs battery somebody is
+ // navigating on. Which stretch of the day it asks about is decided per search.
+ const roadtripCorridor = useRoadtripCorridor(roadtripRoutes, tripId, isMobile ? PHONE_CORRIDOR_OPTIONS : undefined)
// Applying a track is a long job — a routing round trip per refinement — so it lives
// above the dialog: a component that unmounted halfway would leave the day holding
// half a chain of vias.
@@ -815,7 +843,12 @@ export function useTripPlanner() {
if (!can('place_edit', trip)) return
// A corridor hit knows how far along the drive it sits, so it can go straight into
// the chain in driving order instead of being dragged there afterwards.
- const hit = roadtripActive && 'alongKm' in poi ? (poi as unknown as CorridorPoi) : null
+ //
+ // Gated on the FEED, not on road trip mode: the phone never turns that mode on (it
+ // is a data switch the mobile sheets cannot survive, see `roadtripFeedActive`), so
+ // reading it here sent every hit found on the stage map into the full place form
+ // instead, losing the stop kind, the stay, and the position worked out just above.
+ const hit = roadtripFeedActive && 'alongKm' in poi ? (poi as unknown as CorridorPoi) : null
if (hit && roadtripDayId != null) {
const displayed = roadtripRoutes.days.find(d => d.dayId === roadtripDayId)
const insert = displayed && roadtripInsertion(displayed, roadtripInsertIndexFor(hit))
@@ -834,8 +867,8 @@ export function useTripPlanner() {
}
const selected = roadtripRoutes.days.find(d => d.dayId === roadtripDayId)
const target = selected && roadtripInsertion(selected, selected.stops.length)
- openAddPlaceFromPoi(poi, roadtripActive ? target?.dayId ?? roadtripDayId : undefined)
- }, [openAddPlaceFromPoi, roadtripActive, roadtripDayId, roadtripDayNumber, roadtripInsertIndexFor, roadtripRoutes.days, overnightOptions, can, trip])
+ openAddPlaceFromPoi(poi, roadtripFeedActive ? target?.dayId ?? roadtripDayId : undefined)
+ }, [openAddPlaceFromPoi, roadtripFeedActive, roadtripDayId, roadtripDayNumber, roadtripInsertIndexFor, roadtripRoutes.days, overnightOptions, can, trip])
/**
* The stops of a day as the road trip counts them, in the order it drives them.
@@ -1295,9 +1328,16 @@ export function useTripPlanner() {
// on the picker — so flipping the mode off left pale blue alternatives, their
// casings and their drive-time pills drawn on an ordinary planner map, with no
// road trip UI left to dismiss them from.
+ //
+ // The gate is where the picker can be seen, not the mode. `roadtripActive` is false
+ // on a phone by design (see `roadtripMode`), so gating on it alone closed a picker
+ // the phone had just opened, on the very next render. On the phone the picker lives
+ // on the drive tab, so it stays open there and closes once the tab is left. At desk
+ // width `isMobile` is false and this is exactly `roadtripActive`, as it always was.
+ const alternativesShown = roadtripActive || (isMobile && roadtripFeedActive && activeTab === 'roadtrip')
useEffect(() => {
- if (!roadtripActive) routeAlternatives.close()
- }, [roadtripActive, routeAlternatives])
+ if (!alternativesShown) routeAlternatives.close()
+ }, [alternativesShown, routeAlternatives])
/**
* The offered routes as the map draws them: line, colour, and the label that sits on
@@ -2402,7 +2442,7 @@ export function useTripPlanner() {
selectedDayId, isLoading, tripActions, can, canUploadFiles,
pushUndo, undo, canUndo, lastActionLabel, handleUndo,
enabledAddons, collabFeatures, tripAccommodations, setTripAccommodations,
- roadtripMode, toggleRoadtripMode, roadtripActive, roadtripRoutes, roadtripLineColors, roadtripMapLines, roadtripMapPlaces, collapsedRoadtripDays, toggleRoadtripDay, roadtripCorridor,
+ roadtripMode, toggleRoadtripMode, roadtripActive, roadtripFeedActive, roadtripRoutes, roadtripLineColors, roadtripMapLines, roadtripMapPlaces, collapsedRoadtripDays, toggleRoadtripDay, roadtripCorridor,
overviewShown, toggleOverview, overviewActive, tripOverview,
dawarichTrailShown, toggleDawarichTrail, dawarichTrail, dawarichHiddenDates, dawarichEnabled: !!enabledAddons.dawarich,
followTrack, roadtripViaCounts,
@@ -2426,6 +2466,10 @@ export function useTripPlanner() {
refuel, askRefuel, acceptRefuel,
routeAlternatives, askRouteAlternatives, chooseRouteAlternative, alternativeOverlays, alternativeFocusPoints, mapFocusPoints, roadtripMapVias, focusRoadtripPoint,
stayDraft, setStayDraft, editRoadtripStay, setRoadtripStay, roadtripEndDay, roadtripStay,
+ // Addressed by stop rather than by selection: the phone's stage sheet knows which
+ // stop it is showing, and going through the place selection there would open the
+ // permanently mounted place inspector underneath it.
+ setRoadtripEndDay, dailyTimesActive,
highlightedAlternative, setHighlightedAlternative,
moveRoadtripStopToDay,
dropPoiOnRoute,
diff --git a/client/tests/helpers/mobileTrip.ts b/client/tests/helpers/mobileTrip.ts
index d7c8d8955..d3a270654 100644
--- a/client/tests/helpers/mobileTrip.ts
+++ b/client/tests/helpers/mobileTrip.ts
@@ -58,6 +58,9 @@ export function buildPlanner(overrides: Partial = {}): TripPlanner
days: [],
places: [],
assignments: [],
+ // The unfiltered map the store holds. The place editor looks the visit it was
+ // opened on up here, so every sheet test that edits a place needs the shape.
+ storedAssignments: {},
packingItems: [],
todoItems: [],
categories: [],
@@ -201,6 +204,56 @@ export function buildPlanner(overrides: Partial = {}): TripPlanner
toggleDawarichTrail: vi.fn(),
dawarichTrail: { track: null, status: 'idle', reload: vi.fn() },
+ // The road trip addon's routing round. The shell reads days/totalDistance for
+ // its stage header on every render, addon on or off, so the empty-but-valid
+ // shape belongs in the base rather than in the overrides of one suite.
+ roadtripRoutes: {
+ days: [], quietDays: [], lines: [], lineDays: [], accessLines: [], vias: [], segments: [],
+ totalDistance: 0, totalDuration: 0, totalStops: 0, loading: false,
+ },
+
+ // The corridor search, idle. Both the search bar over the stage and the search
+ // sheet read it on every render of the road trip tab, addon on or off, so the
+ // empty-but-valid shape belongs here rather than in one suite's overrides.
+ roadtripCorridor: {
+ dayId: '', setDayId: vi.fn(), day: undefined,
+ categories: ['fuel'], toggleCategory: vi.fn(),
+ widthKm: 5, setWidthKm: vi.fn(),
+ search: {
+ results: [], progress: { done: 0, total: 0 }, loading: false, capped: false,
+ failedSources: [], failedAreas: 0, truncatedAreas: 0, error: false, spine: [],
+ search: vi.fn(), clear: vi.fn(),
+ },
+ nameFilter: '', setNameFilter: vi.fn(), anchors: [],
+ section: null, setSection: vi.fn(), sectionKm: 50, setSectionKm: vi.fn(),
+ socketFilter: '', setSocketFilter: vi.fn(), minKw: 0, setMinKw: vi.fn(),
+ visible: [], insertIndexFor: vi.fn(() => 0), stopsAlongKm: [], clear: vi.fn(),
+ },
+ // The fuel search, idle: the dry band in the chain reads it per leg.
+ refuel: {
+ openFor: null, loading: false, outcome: null, results: [], offered: [],
+ ask: vi.fn(), close: vi.fn(),
+ },
+ askRefuel: vi.fn(),
+ acceptRefuel: vi.fn(),
+ // Other ways of driving a leg, with no picker open. The road trip tab and the map area
+ // read the picker on every render, so the closed shape belongs in the base.
+ routeAlternatives: { open: null, ask: vi.fn(), close: vi.fn() },
+ askRouteAlternatives: vi.fn(),
+ chooseRouteAlternative: vi.fn(async () => undefined),
+ alternativeOverlays: [],
+ alternativeFocusPoints: [],
+ highlightedAlternative: null,
+ setHighlightedAlternative: vi.fn(),
+ // The drive's vias, online and empty. `editable` is what the leg buttons read.
+ roadtripVias: {
+ byDay: {}, trackByDay: {}, stale: false, editable: true,
+ add: vi.fn(), addMany: vi.fn(), move: vi.fn(), remove: vi.fn(), reanchor: vi.fn(),
+ },
+ mapFocusPoints: [],
+ focusRoadtripPoint: vi.fn(),
+ handlePoiClick: vi.fn(),
+
route: null,
routeSegments: [],
routeInfo: null,
@@ -245,6 +298,11 @@ export function buildPlanner(overrides: Partial = {}): TripPlanner
export function buildShell(overrides: Partial = {}): MTripShellApi {
const base: MTripShellApi = {
view: 'plan',
+ rtView: 'list',
+ mapFront: false,
+ toggleRtView: vi.fn(),
+ rtReach: 'ahead',
+ setRtReach: vi.fn(),
mode: 'go',
trTab: 'plan',
setTrTab: vi.fn(),
diff --git a/client/tests/unit/mobile/trip/MMapArea.test.tsx b/client/tests/unit/mobile/trip/MMapArea.test.tsx
index 628944385..4b57af9b8 100644
--- a/client/tests/unit/mobile/trip/MMapArea.test.tsx
+++ b/client/tests/unit/mobile/trip/MMapArea.test.tsx
@@ -1,14 +1,28 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { render, screen } from '../../../helpers/render'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, render, screen } from '../../../helpers/render'
import { buildPlanner, buildShell } from '../../../helpers/mobileTrip'
+import { buildAssignment, buildPlace } from '../../../helpers/factories'
+import type { AccessSpur, RoadtripDay } from '@trek/shared/roadtrip'
import type { MTripShellApi, TripPlanner } from '../../../../src/mobile/screens/trip/MTripShell'
import type { CompassMap } from '../../../../src/components/Map/MapCompassPill'
+import { MAP_LAYER_SWITCHER_INSET, MAP_ROUND_CONTROL_SIZE } from '../../../../src/components/Map/MapLayerSwitcher'
import { useSettingsStore } from '../../../../src/store/settingsStore'
+import { useTripStore } from '../../../../src/store/tripStore'
+import { seedStore } from '../../../helpers/store'
+import type { Place } from '../../../../src/types'
+import type { AlternativeOverlay } from '../../../../src/components/Roadtrip/alternativeOverlays'
+import type { LegAlternatives } from '../../../../src/components/Roadtrip/useRouteAlternatives'
+import { RT_ALT_BAR_LIFT } from '../../../../src/mobile/screens/trip/roadtrip/useMRtAlternatives'
-// FE-MOB-MAPAREA-001 to FE-MOB-MAPAREA-007
+// FE-MOB-MAPAREA-001 to FE-MOB-MAPAREA-035
+//
+// The stage's pins come out of the trip store rather than the planner's map list, so the
+// stage fixtures seed the store and leave `mapPlaces` to stand for what the plan tab shows.
const mocks = vi.hoisted(() => ({
poi: {} as Record,
+ /** The traveller's road trip preferences, read per trip by the area. */
+ prefs: {} as Record,
/** Handed to onMapReady, standing in for a GL map that can rotate. */
glMap: null as CompassMap | null,
/** Last props the area handed the renderer, so its callbacks can be fired. */
@@ -28,6 +42,10 @@ vi.mock('../../../../src/components/Map/usePoiExplore', () => ({
usePoiExplore: () => mocks.poi,
}))
+vi.mock('../../../../src/hooks/useRoadtripSettings', () => ({
+ useRoadtripSettings: (select: (p: Record) => unknown) => select(mocks.prefs),
+}))
+
import MMapArea from '../../../../src/mobile/screens/trip/map/MMapArea'
const COMPASS: CompassMap = {
@@ -39,7 +57,10 @@ const COMPASS: CompassMap = {
function renderArea(shellOver: Partial = {}, plannerOver: Partial = {}) {
const planner = buildPlanner(plannerOver)
- const shell = buildShell({ view: 'map', ...shellOver })
+ // `mapFront` is what the floating chrome keys off since the map became one
+ // instance shared by the plan tab and the road trip tab. `view` alone no longer
+ // says whether the map is the front layer.
+ const shell = buildShell({ view: 'map', mapFront: true, ...shellOver })
return { planner, shell, ...render() }
}
@@ -47,13 +68,118 @@ function renderArea(shellOver: Partial = {}, plannerOver: Partial
const compassBand = (container: HTMLElement) =>
container.querySelector('[style*="--bottom-nav-h"]') as HTMLElement | null
+/** One stage of a drive: two stops on day 1, one of them reached down a short spur. */
+function stageDay(): RoadtripDay {
+ return {
+ dayId: 3, dayNumber: 1, date: '2026-05-01', title: null,
+ stops: [
+ {
+ assignmentId: 31, ownerDayId: 3, ownerIndex: 0, placeId: 11, name: 'Hamburg',
+ lat: 53.55, lng: 9.99, time: null, dwellMinutes: null,
+ legMode: null, incomingLegMode: null, stopType: null,
+ },
+ {
+ assignmentId: 32, ownerDayId: 3, ownerIndex: 1, placeId: 12, name: 'Lübeck',
+ lat: 53.87, lng: 10.69, time: null, dwellMinutes: null,
+ legMode: null, incomingLegMode: null, stopType: null,
+ },
+ ],
+ legs: [], legVias: [[]], geometry: [], distance: 0, duration: 0,
+ schedule: { entries: [], warnings: [] }, driveWarnings: [], dayWarning: null,
+ } as unknown as RoadtripDay
+}
+
+/** The planner carrying that stage, plus a place from another day the stage leaves off. */
+function stagePlanner(selectedDayId: number | null): TripPlanner {
+ const base = buildPlanner()
+ const spur: AccessSpur = { line: [[53.87, 10.69], [53.871, 10.692]], meters: 180, stopKey: '53.87000,10.69000,,' }
+ seedStore(useTripStore, { places: [buildPlace({ id: 11 }), buildPlace({ id: 12 }), buildPlace({ id: 99 })] })
+ return buildPlanner({
+ selectedDayId,
+ mapPlaces: [buildPlace({ id: 11 }), buildPlace({ id: 12 }), buildPlace({ id: 99 })],
+ // The stored visits, which are what the all days view draws: 99 is on no day.
+ storedAssignments: {
+ '3': [
+ buildAssignment({ day_id: 3, place: buildPlace({ id: 11 }) }),
+ buildAssignment({ day_id: 3, place: buildPlace({ id: 12 }) }),
+ ],
+ },
+ roadtripRoutes: {
+ ...base.roadtripRoutes,
+ days: [stageDay()],
+ lines: [[[53.55, 9.99], [53.87, 10.69]]],
+ lineDays: [1],
+ accessLines: [spur],
+ },
+ } as unknown as Partial)
+}
+
+/**
+ * Two routed days. Lübeck is passed on the day before the stage, and the stage itself is a
+ * loop that leaves Hamburg in the morning and comes back to it at night.
+ */
+function drivePlanner(selectedDayId: number | null, over: Partial = {}): TripPlanner {
+ const base = stagePlanner(selectedDayId)
+ const stage = stageDay()
+ const [hamburg, luebeck] = stage.stops
+ const before = { ...stage, dayId: 2, dayNumber: 1, stops: [{ ...luebeck, assignmentId: 21, ownerDayId: 2, ownerIndex: 0 }] }
+ const loop = { ...stage, dayNumber: 2, stops: [hamburg, luebeck, { ...hamburg, assignmentId: 33, ownerIndex: 2 }] }
+ return {
+ ...base,
+ roadtripRoutes: { ...base.roadtripRoutes, days: [before, loop], lineDays: [2] },
+ ...over,
+ } as TripPlanner
+}
+
+/** The shell with the road trip map in front. */
+const stageShell = () => buildShell({ view: 'map', mapFront: true, trTab: 'roadtrip', rtView: 'map' })
+
+/** The pin handler the area last handed the renderer. */
+const tapPin = (placeId?: number) => (mocks.props.onMarkerClick as (id?: number) => void)(placeId)
+
+/** What the area handed the renderer that a fresh copy would make it draw again. */
+const DRAWN = ['places', 'route', 'routeColors', 'accessLines', 'focusPoints'] as const
+
+/** A picker open on leg 0 of day 3, with or without roads back yet. */
+function withPicker(overlays: AlternativeOverlay[], over: Partial = {}): Partial {
+ const base = buildPlanner()
+ const open: LegAlternatives = { dayId: 3, index: 0, routes: [], loading: overlays.length === 0, error: false }
+ return {
+ routeAlternatives: { ...base.routeAlternatives, open },
+ alternativeOverlays: overlays,
+ ...over,
+ } as Partial
+}
+
+/** Two offered roads, as far as the map area reads them. */
+const OFFERS = [
+ { index: 0, coordinates: [[53.55, 9.99], [53.87, 10.69]], color: 'blue', label: '1 h', note: 'Current' },
+ { index: 1, coordinates: [[53.55, 9.99], [53.7, 10.2], [53.87, 10.69]], color: 'pale', label: '1 h 10 min', note: '' },
+] as unknown as AlternativeOverlay[]
+
+/** The probe the area reads the safe area off, answering like a phone with a notch. */
+function notchedPhone(top: string, bottom: string) {
+ const real = window.getComputedStyle.bind(window)
+ return vi.spyOn(window, 'getComputedStyle').mockImplementation((el: Element, pseudo?: string | null) => (
+ el.className.toString().includes('safe-area-inset-top')
+ ? ({ paddingTop: top, paddingBottom: bottom } as CSSStyleDeclaration)
+ : real(el, pseudo)
+ ))
+}
+
+afterEach(() => {
+ vi.restoreAllMocks()
+})
+
beforeEach(() => {
mocks.glMap = COMPASS
+ mocks.prefs = {}
mocks.poi = {
active: new Set(), pois: [], loadingKeys: new Set(), errorKeys: new Set(),
moved: false, toggle: vi.fn(), searchArea: vi.fn(), onViewportChange: vi.fn(),
}
useSettingsStore.setState(s => ({ settings: { ...s.settings, map_poi_pill_enabled: true } }))
+ seedStore(useTripStore, { places: [], placesFilter: 'all', placesCategoryFilter: new Set() })
})
describe('MMapArea', () => {
@@ -70,15 +196,41 @@ describe('MMapArea', () => {
// LocationButton hard-codes `right: 12` off the same variable, so matching
// the offset here is what keeps the two round controls on one line.
expect(compassBand(container)?.style.bottom).toBe('calc(var(--bottom-nav-h, 84px) + 12px)')
- expect(compassBand(container)?.className).toContain('left-3')
+ // Beside the base-layer switcher both engines draw in the corner: its inset, its
+ // size and one gap. In the corner itself it lay under the switcher's frosted shell.
+ expect(compassBand(container)?.style.left).toBe(`${MAP_LAYER_SWITCHER_INSET + MAP_ROUND_CONTROL_SIZE + 8}px`)
+ expect(compassBand(container)?.className).not.toContain('left-3')
})
- it('FE-MOB-MAPAREA-003: the map layer floats those controls a dock gap above the dock', () => {
+ it('FE-MOB-MAPAREA-003: the map layer stands those controls on the dock, with no credit row under them', () => {
const { container } = renderArea()
+ const layer = container.firstElementChild as HTMLElement
- // The dock is 62px tall at safe-bottom + 12; the controls add their own 12.
- expect((container.firstElementChild as HTMLElement).className)
- .toContain('[--bottom-nav-h:calc(env(safe-area-inset-bottom,0px)+74px)]')
+ // The floor is the dock's top edge: 62px tall at safe-bottom + 12, raised by the stage lift.
+ expect(layer.className)
+ .toContain('[--m-map-floor:calc(env(safe-area-inset-bottom,0px)+74px+var(--m-stage-lift,0px))]')
+ // The band sits on that floor and the controls add their own 12 on top. It used to float
+ // a further 38px up to leave the corner under it to the credit; the phone map shows none,
+ // so that row would only be a gap over the dock.
+ expect(layer.className).toContain('[--bottom-nav-h:var(--m-map-floor)]')
+ expect(layer.className).not.toContain('38px')
+ // No lift off the stage: the plan tab has no bar in that band.
+ expect(layer.style.getPropertyValue('--m-stage-lift')).toBe('0px')
+ })
+
+ it('FE-MOB-MAPAREA-013: on the stage nothing stands over the dock, so the floor stays on it', () => {
+ const { container } = renderArea({ trTab: 'roadtrip', mapFront: true })
+
+ // A 61px stage bar used to hold this slot whenever the map was up, and the floor rose
+ // 76px to clear it. It is gone, so the road trip tab lifts nothing by itself; only the
+ // picker's bar still raises the floor (FE-MOB-MAPAREA-030).
+ expect((container.firstElementChild as HTMLElement).style.getPropertyValue('--m-stage-lift')).toBe('0px')
+ })
+
+ it('FE-MOB-MAPAREA-014: behind the chain there is no bar to clear, so nothing lifts', () => {
+ const { container } = renderArea({ trTab: 'roadtrip', mapFront: false })
+
+ expect((container.firstElementChild as HTMLElement).style.getPropertyValue('--m-stage-lift')).toBe('0px')
})
it('FE-MOB-MAPAREA-004: a renderer that cannot rotate gets no compass', () => {
@@ -98,7 +250,7 @@ describe('MMapArea', () => {
})
it('FE-MOB-MAPAREA-006: no floating chrome while the timeline covers the map', () => {
- const { container } = renderArea({ view: 'plan' })
+ const { container } = renderArea({ view: 'plan', mapFront: false })
expect(screen.queryByLabelText('Cafés')).not.toBeInTheDocument()
expect(compassBand(container)).toBeNull()
@@ -113,4 +265,503 @@ describe('MMapArea', () => {
expect(shell.openSheet).toHaveBeenCalledWith('transport', { reservationId: 7 })
})
+ it('FE-MOB-MAPAREA-008: on the stage the pins are the search and the fuel offers, and nothing else', () => {
+ const corridorHit = { osm_id: 'c1', name: 'Shell', lat: 53.5, lng: 9.8, category: 'fuel' }
+ const offered = { osm_id: 'r1', name: 'Aral', lat: 53.4, lng: 9.7, category: 'fuel' }
+ mocks.poi = { ...mocks.poi, pois: [{ osm_id: 'e1', name: 'Café', lat: 53.3, lng: 9.6, category: 'cafe' }] }
+ const base = buildPlanner()
+ renderArea({ trTab: 'roadtrip' }, {
+ roadtripCorridor: { ...base.roadtripCorridor, visible: [corridorHit] },
+ refuel: { ...base.refuel, offered: [offered] },
+ } as unknown as Partial)
+
+ const ids = (mocks.props.pois as Array<{ osm_id: string }>).map(p => p.osm_id)
+ expect(ids).toEqual(expect.arrayContaining(['c1', 'r1']))
+ // "What is around this piece of map" is a different question from "what is on the
+ // way", and its bar is off this tab, so its pins would be pins nobody could clear.
+ expect(ids).not.toContain('e1')
+ expect(screen.queryByLabelText('Cafés')).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-MAPAREA-009: off the stage a corridor hit is not drawn at all', () => {
+ const base = buildPlanner()
+ renderArea({ trTab: 'plan' }, {
+ roadtripCorridor: { ...base.roadtripCorridor, visible: [{ osm_id: 'c1', lat: 53.5, lng: 9.8, category: 'fuel' }] },
+ } as unknown as Partial)
+
+ // A pin with no route under it cannot explain where on the drive it sits.
+ expect((mocks.props.pois as Array<{ osm_id: string }>).map(p => p.osm_id)).not.toContain('c1')
+ })
+
+ it('FE-MOB-MAPAREA-010: a pin tapped on the stage goes through the road trip door', () => {
+ const { planner } = renderArea({ trTab: 'roadtrip' })
+
+ const marker = { osm_id: 'c1', name: 'Shell', lat: 53.5, lng: 9.8, category: 'fuel', alongKm: 82 }
+ ;(mocks.props.onPoiClick as (m: unknown) => void)(marker)
+
+ expect(planner.handlePoiClick).toHaveBeenCalledWith(marker)
+ expect(planner.openAddPlaceFromPoi).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-MAPAREA-011: on the plan tab it stays the plain place form, carrying the day', () => {
+ const { planner } = renderArea({ trTab: 'plan' }, { selectedDayId: 5 })
+
+ const marker = { osm_id: 'e1', name: 'Café', lat: 53.3, lng: 9.6, category: 'cafe' }
+ ;(mocks.props.onPoiClick as (m: unknown) => void)(marker)
+
+ expect(planner.openAddPlaceFromPoi).toHaveBeenCalledWith(marker, 5)
+ expect(planner.handlePoiClick).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-MAPAREA-012: a focused hit takes the camera; with nothing pending the stage frames itself', () => {
+ const focused = renderArea({ trTab: 'roadtrip' }, { mapFocusPoints: [[53.5, 9.8]] })
+ expect(mocks.props.focusPoints).toEqual([[53.5, 9.8]])
+ focused.unmount()
+
+ renderArea({ trTab: 'roadtrip' })
+ // The stage's own points, which is an array either way: going array → undefined →
+ // array is two dependency changes, and the second throws away the traveller's pan.
+ expect(Array.isArray(mocks.props.focusPoints)).toBe(true)
+ })
+
+ it('FE-MOB-MAPAREA-015: the compass never takes the base-layer switcher\'s slot, on either tab', () => {
+ for (const shellOver of [{ trTab: 'plan' }, { trTab: 'roadtrip', mapFront: true }] as Partial[]) {
+ const { container, unmount } = renderArea(shellOver)
+
+ expect(parseFloat(compassBand(container)?.style.left ?? '0'))
+ .toBeGreaterThanOrEqual(MAP_LAYER_SWITCHER_INSET + MAP_ROUND_CONTROL_SIZE)
+ // With the renderer mocked, the compass is still the one element in this layer
+ // that sets --bottom-nav-h inline; its left offset joined the same style object.
+ expect(container.querySelectorAll('[style*="--bottom-nav-h"]')).toHaveLength(1)
+ unmount()
+ }
+ })
+
+ it('FE-MOB-MAPAREA-016: a re-render with nothing new on the stage hands the map the same drawing', () => {
+ const planner = stagePlanner(3)
+ const shell = buildShell({ view: 'map', mapFront: true, trTab: 'roadtrip' })
+ const { rerender } = render()
+ const first = { ...mocks.props }
+
+ // The stage really is what is drawn, so the identities below are about something.
+ expect((first.places as Array<{ id: number }>).map(p => p.id)).toEqual([11, 12])
+ expect(first.route).toHaveLength(1)
+ expect(first.accessLines).toHaveLength(1)
+ expect(first.focusPoints).toEqual([[53.55, 9.99], [53.87, 10.69]])
+
+ // The shell re-renders on every store write, a satellite tap included. Fresh arrays
+ // here would refit the camera over the traveller's pan and set the map's sources
+ // again, which is also what kept the style too busy to draw the imagery.
+ rerender()
+
+ for (const key of DRAWN) expect(mocks.props[key]).toBe(first[key])
+ })
+
+ it('FE-MOB-MAPAREA-017: the all days view keeps its day colours between renders too', () => {
+ mocks.prefs = { roadtrip_day_colors: true }
+ const planner = stagePlanner(null)
+ const shell = buildShell({ view: 'map', mapFront: true, trTab: 'roadtrip' })
+ const { rerender } = render()
+ const first = { ...mocks.props }
+
+ // One colour per line, worked out per call, so without the memo a new array each time.
+ expect(first.routeColors).toHaveLength(1)
+ // Still an array with no stage, which FE-MOB-MAPAREA-012 depends on.
+ expect(Array.isArray(first.focusPoints)).toBe(true)
+
+ rerender()
+
+ for (const key of DRAWN) expect(mocks.props[key]).toBe(first[key])
+ })
+
+ it('FE-MOB-MAPAREA-018: what is kept still follows the stage, the day colours and the places', () => {
+ const planner = stagePlanner(3)
+ const shell = buildShell({ view: 'map', mapFront: true, trTab: 'roadtrip' })
+ const { rerender } = render()
+ expect(mocks.props.routeColors).toBeUndefined()
+
+ // Kept on its inputs, not frozen: each one below has to reach the map, or a memo
+ // missing it would leave the traveller looking at a stage they already left.
+ mocks.prefs = { roadtrip_day_colors: true }
+ rerender()
+ expect(mocks.props.routeColors).toHaveLength(1)
+
+ // The store is where the stage reads its places from, and a store write re-renders the area.
+ const renamed = buildPlace({ id: 12, name: 'Travemünde' })
+ const stored = useTripStore.getState().places
+ act(() => { useTripStore.setState({ places: [stored[0], renamed, stored[2]] }) })
+ expect(mocks.props.places).toContain(renamed)
+
+ const allDays = { ...planner, selectedDayId: null }
+ rerender()
+ expect((mocks.props.places as Place[]).map(p => p.id)).toEqual([11, 12])
+ expect(mocks.props.places).toContain(renamed)
+ expect(mocks.props.focusPoints).toEqual([])
+
+ // Off the tab the stage hands nothing through, so the plan tab frames itself again.
+ rerender()
+ expect(mocks.props.accessLines).toBeUndefined()
+ expect(mocks.props.focusPoints).toBeUndefined()
+ expect(mocks.props.places).toBe(allDays.mapPlaces)
+ })
+
+ it('FE-MOB-MAPAREA-019: a pin on the stage opens its stop on this card, never the place inspector', () => {
+ const planner = drivePlanner(3)
+ const shell = stageShell()
+ render()
+
+ // Lübeck is also a stop the day before; the stage on screen is the one it opens on.
+ tapPin(12)
+ expect(shell.openSheet).toHaveBeenLastCalledWith('rtstop', { dayId: 3, assignmentId: 32 })
+ // Hamburg is left in the morning and come back to at night: the pin opens the first visit.
+ tapPin(11)
+ expect(shell.openSheet).toHaveBeenLastCalledWith('rtstop', { dayId: 3, assignmentId: 31 })
+
+ // The planner's selection is what the place inspector opens off, so it is never moved.
+ expect(planner.handleMarkerClick).not.toHaveBeenCalled()
+ expect(planner.setSelectedPlaceId).not.toHaveBeenCalled()
+ expect(planner.selectAssignment).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-MAPAREA-020: over the whole drive a pin opens its first routed visit, and a place no day stops at gets the inspector', () => {
+ const planner = drivePlanner(null)
+ const shell = stageShell()
+ render()
+
+ tapPin(12)
+ expect(shell.openSheet).toHaveBeenLastCalledWith('rtstop', { dayId: 2, assignmentId: 21 })
+ tapPin(11)
+ expect(shell.openSheet).toHaveBeenLastCalledWith('rtstop', { dayId: 3, assignmentId: 31 })
+
+ tapPin(99)
+ expect(planner.handleMarkerClick).toHaveBeenCalledWith(99)
+ expect(shell.openSheet).toHaveBeenCalledTimes(2)
+ })
+
+ it('FE-MOB-MAPAREA-021: a picked day with no stage to show searches the whole drive, and falls back the same way', () => {
+ // A quiet day the routing round has no card for.
+ const quiet = drivePlanner(7)
+ const shell = stageShell()
+ const { unmount } = render()
+ tapPin(12)
+ expect(shell.openSheet).toHaveBeenLastCalledWith('rtstop', { dayId: 2, assignmentId: 21 })
+ tapPin(99)
+ expect(quiet.handleMarkerClick).toHaveBeenCalledWith(99)
+ unmount()
+
+ // Still routing: a day is picked, nothing has come back yet, and the inspector is all there is.
+ const base = drivePlanner(3)
+ const routing = { ...base, roadtripRoutes: { ...base.roadtripRoutes, days: [], loading: true } } as TripPlanner
+ const waiting = stageShell()
+ render()
+ tapPin(11)
+ expect(routing.handleMarkerClick).toHaveBeenCalledWith(11)
+ expect(waiting.openSheet).not.toHaveBeenCalled()
+ // A handler called without a place clears the way the planner's own does.
+ tapPin(undefined)
+ expect(routing.handleMarkerClick).toHaveBeenLastCalledWith(undefined)
+ })
+
+ it('FE-MOB-MAPAREA-022: the plan tab keeps the planner\'s own marker door, map tap and selection', () => {
+ const planner = drivePlanner(3, { selectedPlaceId: 12 })
+ const shell = buildShell({ view: 'map', mapFront: true, trTab: 'plan' })
+ render()
+
+ expect(mocks.props.onMarkerClick).toBe(planner.handleMarkerClick)
+ expect(mocks.props.onMapClick).toBe(planner.handleMapClick)
+ expect(mocks.props.selectedPlaceId).toBe(12)
+
+ tapPin(12)
+ expect(planner.handleMarkerClick).toHaveBeenCalledWith(12)
+ expect(shell.openSheet).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-MAPAREA-023: the stage\'s pin handler keeps its identity across renders and reads the latest stage', () => {
+ const planner = drivePlanner(3)
+ const shell = stageShell()
+ const { rerender } = render()
+ const first = mocks.props.onMarkerClick
+
+ // New planner and shell objects, the way the shell hands them over on every store write.
+ // Leaflet rebuilds every marker when this identity moves.
+ rerender()
+ expect(mocks.props.onMarkerClick).toBe(first)
+
+ // Swiped to the day before: the same handler now answers for that stage and that shell.
+ const next = stageShell()
+ rerender()
+ expect(mocks.props.onMarkerClick).toBe(first)
+ tapPin(12)
+ expect(next.openSheet).toHaveBeenCalledWith('rtstop', { dayId: 2, assignmentId: 21 })
+ expect(shell.openSheet).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-MAPAREA-024: stage pins are the stops of its chain, whatever the plan tab\'s declutter and filters hide', () => {
+ // A pump hidden from the day lists, and a category filter set in the places browser.
+ const pump = buildPlace({ id: 12, stop_type: 'fuel', category_id: 3 } as Partial)
+ seedStore(useTripStore, { placesFilter: 'unplanned', placesCategoryFilter: new Set(['9']) })
+ const planner = stagePlanner(3)
+ seedStore(useTripStore, { places: [buildPlace({ id: 11, category_id: 4 }), pump, buildPlace({ id: 99 })] })
+ // The plan tab's list after "all days" twice and a chip tap: its declutter still names
+ // the day before, so it carries none of this stage's places.
+ const decluttered = { ...planner, mapPlaces: [buildPlace({ id: 99 })] } as TripPlanner
+ render()
+
+ expect((mocks.props.places as Place[]).map(p => p.id)).toEqual([11, 12])
+
+ // A place without a position has nowhere to stand, on the stage as anywhere else.
+ act(() => {
+ useTripStore.setState({ places: [buildPlace({ id: 11 }), { ...pump, lat: null, lng: null } as unknown as Place] })
+ })
+ expect((mocks.props.places as Place[]).map(p => p.id)).toEqual([11])
+ })
+
+ it('FE-MOB-MAPAREA-025: a shown point holds the camera on its own day only, and a day change hands the frame back', () => {
+ const planner = drivePlanner(3)
+ const shell = stageShell()
+ const point: [number, number][] = [[50, 8]]
+ const { rerender } = render()
+ expect(mocks.props.focusPoints).toBe(point)
+
+ // The planner keeps the point until its next routing round. The swipe frames its stage anyway.
+ rerender()
+ expect(mocks.props.focusPoints).toEqual([[53.87, 10.69]])
+
+ // Coming back does not bring the old point back: the camera belongs to the stage now.
+ rerender()
+ expect(mocks.props.focusPoints).not.toBe(point)
+ expect(mocks.props.focusPoints).toEqual(expect.arrayContaining([[53.55, 9.99], [53.87, 10.69]]))
+
+ // A new point arriving together with its day, as Show on map from another card does, is held.
+ const shown: [number, number][] = [[53.87, 10.69]]
+ rerender()
+ expect(mocks.props.focusPoints).toBe(shown)
+ })
+
+ it('FE-MOB-MAPAREA-036: a stage keeps its own night pause and drops the other days', () => {
+ // A night pause is the moon pill where a travel day ends. The markers are built from
+ // the whole drive, so day 1 used to carry day 2's pill as well, in the middle of a map
+ // that draws day 1 only. `stagePlanner(3)` is day 1 of the drive (stageDay).
+ const own = { lat: 53.87, lng: 10.69, tone: 'default' as const, nightPause: { day: 1, atPlace: false } }
+ const other = { lat: 53.55, lng: 9.99, tone: 'default' as const, nightPause: { day: 2, atPlace: false } }
+ const plain = { lat: 53.6, lng: 10.2, tone: 'default' as const, label: 'Rest stop' }
+ const vias = [own, other, plain]
+
+ const stage = renderArea(
+ { trTab: 'roadtrip', mapFront: true },
+ { ...stagePlanner(3), roadtripMapVias: vias } as unknown as Partial,
+ )
+ // Its own night and everything that is not one; day 2's pill stays off this map.
+ expect(mocks.props.routeVias).toEqual([own, plain])
+ stage.unmount()
+
+ // Off a stage the list is left alone: in the all-days view every night belongs to a
+ // line that is actually drawn.
+ renderArea({ trTab: 'plan' }, { routeVias: vias })
+ expect(mocks.props.routeVias).toBe(vias)
+ })
+
+ it('FE-MOB-MAPAREA-026: the map layer carries no credit corner on either tab', () => {
+ const plan = renderArea()
+ const planLayer = plan.container.firstElementChild as HTMLElement
+ // The phone map shows no credit at all now (mobile.css), so the class that used to
+ // place one is gone rather than left behind pointing at nothing.
+ expect(planLayer.classList.contains('m-credit-corner')).toBe(false)
+ plan.unmount()
+
+ const { container } = renderArea({ trTab: 'roadtrip', mapFront: true })
+ const stageLayer = container.firstElementChild as HTMLElement
+ expect(stageLayer.classList.contains('m-credit-corner')).toBe(false)
+ })
+
+ it('FE-MOB-MAPAREA-028: on the stage the map draws the offered roads, and a tap on one only lights it', () => {
+ const { planner } = renderArea(
+ { trTab: 'roadtrip', rtView: 'map' },
+ withPicker(OFFERS, { highlightedAlternative: 1 }),
+ )
+
+ expect(mocks.props.alternativeRoutes).toBe(planner.alternativeOverlays)
+ expect(mocks.props.activeAlternative).toBe(1)
+
+ ;(mocks.props.onChooseAlternative as (index: number) => void)(0)
+ // Glass has no hover to preview with, so the desk's click that takes a road would save a
+ // via on the first touch. The bar's confirm is what takes it here.
+ expect(planner.setHighlightedAlternative).toHaveBeenCalledWith(0)
+ expect(planner.chooseRouteAlternative).not.toHaveBeenCalled()
+ // A touch fires emulated enter and leave events, and the leave would put the road out.
+ expect(mocks.props.onHighlightAlternative).toBeUndefined()
+ })
+
+ it('FE-MOB-MAPAREA-029: the plan tab draws no offered roads and frames nothing for them', () => {
+ renderArea({ trTab: 'plan' }, withPicker(OFFERS, { highlightedAlternative: 1 }))
+
+ expect(mocks.props.alternativeRoutes).toBeUndefined()
+ expect(mocks.props.activeAlternative).toBeUndefined()
+ expect(mocks.props.onChooseAlternative).toBeUndefined()
+ expect(mocks.props.fitPadding).toBeUndefined()
+ })
+
+ it('FE-MOB-MAPAREA-030: with the picker open the floor clears its taller bar, and the compass is still the one inline --bottom-nav-h', () => {
+ const { container, unmount } = renderArea({ trTab: 'roadtrip', mapFront: true }, withPicker([]))
+ const layer = container.firstElementChild as HTMLElement
+
+ // 174px of bar and the stage bar's 15px gap, as soon as the question is asked.
+ expect(layer.style.getPropertyValue('--m-stage-lift')).toBe(`${RT_ALT_BAR_LIFT}px`)
+ expect(layer.style.getPropertyValue('--m-stage-lift')).toBe('189px')
+ expect(layer.getAttribute('style')).not.toContain('--bottom-nav-h')
+ expect(container.querySelectorAll('[style*="--bottom-nav-h"]')).toHaveLength(1)
+ expect(compassBand(container)).not.toBeNull()
+ unmount()
+
+ // Behind the chain the bar is not on screen, so nothing lifts.
+ const behind = renderArea({ trTab: 'roadtrip', mapFront: false }, withPicker([]))
+ expect((behind.container.firstElementChild as HTMLElement).style.getPropertyValue('--m-stage-lift')).toBe('0px')
+ })
+
+ it('FE-MOB-MAPAREA-031: the offered roads are framed between the day chips and the bar, once they are there', () => {
+ const shell = stageShell()
+ const asking = buildPlanner(withPicker([]))
+ const { rerender } = render()
+ // Nothing to frame while the router is asked: a padding handed over now would refit
+ // the stage into a smaller frame just before the answer moves the camera again.
+ expect(mocks.props.fitPadding).toBeUndefined()
+
+ const answered = { ...asking, ...withPicker(OFFERS) } as TripPlanner
+ rerender()
+ // Top: 12 of --m-safe-top, the rail's 50 offset and 42 height, a 12 gap. Bottom: the
+ // dock's 74 and the bar's lift. The sides keep the phone's 20.
+ expect(mocks.props.fitPadding).toEqual({ top: 116, right: 20, bottom: 74 + RT_ALT_BAR_LIFT, left: 20 })
+ const first = mocks.props.fitPadding
+
+ // Kept between renders, for the reason the stage data is.
+ rerender()
+ expect(mocks.props.fitPadding).toBe(first)
+
+ // Closed, the stage frames itself with the engines' own margins again.
+ rerender()
+ expect(mocks.props.fitPadding).toBeUndefined()
+ })
+
+ it('FE-MOB-MAPAREA-032: on a phone with a notch the frame moves in by the safe area, and follows a turn of the phone', () => {
+ const style = notchedPhone('59px', '34px')
+ renderArea({ trTab: 'roadtrip', rtView: 'map' }, withPicker(OFFERS))
+
+ expect(mocks.props.fitPadding).toEqual({ top: 59 + 116, right: 20, bottom: 34 + 74 + RT_ALT_BAR_LIFT, left: 20 })
+
+ // Turned sideways the insets go to the edges, and the frame lets go of them.
+ style.mockRestore()
+ notchedPhone('0px', '21px')
+ act(() => { window.dispatchEvent(new Event('resize')) })
+ expect(mocks.props.fitPadding).toEqual({ top: 116, right: 20, bottom: 21 + 74 + RT_ALT_BAR_LIFT, left: 20 })
+ })
+
+ it('FE-MOB-MAPAREA-027: the layer sets only the lift inline, so the compass stays the one inline --bottom-nav-h', () => {
+ for (const shellOver of [{ trTab: 'plan' }, { trTab: 'roadtrip', mapFront: true }] as Partial[]) {
+ const { container, unmount } = renderArea(shellOver)
+ const inline = (container.firstElementChild as HTMLElement).getAttribute('style') ?? ''
+
+ // The floor and the band are classes: a second element naming --bottom-nav-h inline
+ // would leave nothing to tell the compass band apart by.
+ expect(inline).toContain('--m-stage-lift')
+ expect(inline).not.toContain('--bottom-nav-h')
+ expect(inline).not.toContain('--m-map-floor')
+ expect(inline).not.toContain('--m-credit')
+ expect(container.querySelectorAll('[style*="--bottom-nav-h"]')).toHaveLength(1)
+ expect(compassBand(container)).not.toBeNull()
+ unmount()
+ }
+ })
+
+ it('FE-MOB-MAPAREA-033: a point the planner hands back once offers or roads close does not take the camera again', () => {
+ const planner = drivePlanner(2)
+ const shell = stageShell()
+ const view = (dayId: number, mapFocusPoints: [number, number][], alternativeFocusPoints: [number, number][] = []) =>
+
+ const point: [number, number][] = [[50, 8]]
+ const { rerender } = render(view(2, point))
+ expect(mocks.props.focusPoints).toBe(point)
+
+ // Swiped on: the planner still keeps the point from day 2, and this stage frames itself.
+ rerender(view(3, point))
+ const stageFrame = mocks.props.focusPoints
+ expect(stageFrame).not.toBe(point)
+
+ // The fuel offers take the camera, and closing them hands the same point back. The chips
+ // still say day 3, so flying to day 2's stop would leave the map on a stage nobody picked.
+ const offers: [number, number][] = [[53.4, 9.7]]
+ rerender(view(3, offers))
+ expect(mocks.props.focusPoints).toBe(offers)
+ rerender(view(3, point))
+ expect(mocks.props.focusPoints).toBe(stageFrame)
+
+ // On its own day as well: the roads for a leg, cancelled, give the frame back to the stage.
+ const shown: [number, number][] = [[53.87, 10.69]]
+ rerender(view(3, shown))
+ expect(mocks.props.focusPoints).toBe(shown)
+ const roads: [number, number][] = [[53.55, 9.99], [53.7, 10.2], [53.87, 10.69]]
+ rerender(view(3, roads, roads))
+ expect(mocks.props.focusPoints).toBe(roads)
+ rerender(view(3, shown))
+ expect(mocks.props.focusPoints).toBe(stageFrame)
+
+ // And every time after: a second round of offers is new, the point behind it is not.
+ const again: [number, number][] = [[53.3, 9.6]]
+ rerender(view(3, again))
+ expect(mocks.props.focusPoints).toBe(again)
+ rerender(view(3, shown))
+ expect(mocks.props.focusPoints).toBe(stageFrame)
+ })
+
+ it('FE-MOB-MAPAREA-034: fuel offers asked over an open picker give the camera back to its roads when they close', () => {
+ const planner = drivePlanner(3)
+ const shell = stageShell()
+ const roads: [number, number][] = [[53.55, 9.99], [53.7, 10.2], [53.87, 10.69]]
+ const view = (mapFocusPoints: [number, number][], alternativeFocusPoints: [number, number][]) =>
+
+ const { rerender } = render(view(roads, roads))
+ expect(mocks.props.focusPoints).toBe(roads)
+
+ const offers: [number, number][] = [[53.4, 9.7]]
+ rerender(view(offers, roads))
+ expect(mocks.props.focusPoints).toBe(offers)
+
+ // The picker is still open and still asking about its leg, so its roads are framed again.
+ rerender(view(roads, roads))
+ expect(mocks.props.focusPoints).toBe(roads)
+
+ // Closed, nothing is pending and the stage frames itself.
+ const closed: [number, number][] = []
+ rerender(view(closed, closed))
+ expect(mocks.props.focusPoints).toEqual([[53.55, 9.99], [53.87, 10.69], [53.55, 9.99]])
+ })
+
+ it('FE-MOB-MAPAREA-035: the all days view pins every stored visit, a booked night and a hidden service stop included', () => {
+ const hotel = buildPlace({ id: 20 })
+ const pump = buildPlace({ id: 21, stop_type: 'fuel' } as Partial)
+ const base = drivePlanner(null)
+ // The places browser on 'unplanned' with a category picked, which empties the plan tab's map.
+ seedStore(useTripStore, {
+ places: [buildPlace({ id: 11 }), hotel, pump, buildPlace({ id: 99 })],
+ placesFilter: 'unplanned',
+ placesCategoryFilter: new Set(['9']),
+ })
+ const planner = {
+ ...base,
+ mapPlaces: [],
+ // The planner's planned list on a phone: its day lists leave the booked night and the
+ // hidden pump out, so it is not what the drive the routing round draws stops at.
+ roadtripMapPlaces: [buildPlace({ id: 11 })],
+ storedAssignments: {
+ '3': [
+ buildAssignment({ day_id: 3, place: buildPlace({ id: 11 }) }),
+ buildAssignment({ day_id: 3, place: pump }),
+ ],
+ '4': [buildAssignment({ day_id: 4, place: hotel, accommodation_id: 5 })],
+ },
+ } as TripPlanner
+ render()
+
+ expect((mocks.props.places as Place[]).map(p => p.id)).toEqual([11, 20, 21])
+ expect(mocks.props.places).not.toBe(planner.roadtripMapPlaces)
+ })
})
diff --git a/client/tests/unit/mobile/trip/MMehrSheet.test.tsx b/client/tests/unit/mobile/trip/MMehrSheet.test.tsx
index 2ec34d5bf..07a8fcad5 100644
--- a/client/tests/unit/mobile/trip/MMehrSheet.test.tsx
+++ b/client/tests/unit/mobile/trip/MMehrSheet.test.tsx
@@ -5,9 +5,9 @@ import type { MTripShellApi, TripPlanner } from '../../../../src/mobile/screens/
import type { TripFile, TripMember } from '../../../../src/types'
import { buildPlanner, buildShell } from '../../../helpers/mobileTrip'
import { resetAllStores } from '../../../helpers/store'
-import { fireEvent, render, screen } from '../../../helpers/render'
+import { fireEvent, render, screen, within } from '../../../helpers/render'
-// FE-MOB-MEHR-001 to FE-MOB-MEHR-012
+// FE-MOB-MEHR-001 to FE-MOB-MEHR-014
//
// The sheet takes its copy from the real TranslationProvider, so the visible
// strings are asserted in English.
@@ -133,4 +133,46 @@ describe('MMehrSheet', () => {
const rows = screen.getByRole('button', { name: 'Share Trip' }).parentElement
expect(rows).toHaveClass('mt-2')
})
+
+ // Both sides read the same priority list (dockTabs.ts). They used to be two
+ // hand-kept copies, and extending only one showed the same section in the dock AND
+ // as a tile here.
+ describe('the dock overflow', () => {
+ /** The sections with the road trip addon on, in the order the planner builds them. */
+ const WITH_ROADTRIP = [
+ { id: 'plan', label: 'Plan', icon: FolderOpen },
+ { id: 'transports', label: 'Transport', icon: FolderOpen },
+ { id: 'buchungen', label: 'Bookings', icon: FolderOpen },
+ { id: 'roadtrip', label: 'Road trip', icon: FolderOpen },
+ { id: 'listen', label: 'Lists', icon: FolderOpen },
+ { id: 'finanzplan', label: 'Budget', icon: FolderOpen },
+ { id: 'dateien', label: 'Files', icon: FolderOpen },
+ { id: 'collab', label: 'Collaboration', icon: Users },
+ ]
+
+ it('FE-MOB-MEHR-013: the section the drive pushed out of the dock lands here', () => {
+ renderSheet({ TRIP_TABS: WITH_ROADTRIP as TripPlanner['TRIP_TABS'] })
+
+ // Six sections do not fit the dock, so the packing list gives up its seat.
+ expect(screen.getByRole('button', { name: 'Lists' })).toBeInTheDocument()
+ // The drive itself never overflows: it sits second in the priority list.
+ expect(screen.queryByRole('button', { name: 'Road trip' })).not.toBeInTheDocument()
+ // Exactly the three the dock could not seat, nothing shown twice.
+ const grid = screen.getByRole('button', { name: 'Lists' }).parentElement
+ expect(within(grid as HTMLElement).getAllByRole('button')).toHaveLength(3)
+ })
+
+ it('FE-MOB-MEHR-014: a dock with room keeps the packing list, addon or no addon', () => {
+ renderSheet({
+ TRIP_TABS: WITH_ROADTRIP.filter(
+ tab => tab.id !== 'finanzplan' && tab.id !== 'dateien' && tab.id !== 'collab',
+ ) as TripPlanner['TRIP_TABS'],
+ })
+
+ // Five sections still fit beside the More button, so nothing overflows and the
+ // sheet is the action rows alone.
+ expect(screen.queryByRole('button', { name: 'Lists' })).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Share Trip' }).parentElement).not.toHaveClass('mt-2')
+ })
+ })
})
diff --git a/client/tests/unit/mobile/trip/MPlaceEditSheet.test.tsx b/client/tests/unit/mobile/trip/MPlaceEditSheet.test.tsx
index 0119b0671..120ed48bc 100644
--- a/client/tests/unit/mobile/trip/MPlaceEditSheet.test.tsx
+++ b/client/tests/unit/mobile/trip/MPlaceEditSheet.test.tsx
@@ -10,7 +10,7 @@ import { server } from '../../../helpers/msw/server'
import { resetAllStores, seedStore } from '../../../helpers/store'
import { fireEvent, render, screen, waitFor } from '../../../helpers/render'
-// FE-MOB-PLEDIT-001 to FE-MOB-PLEDIT-024, plus FE-MOB-PLEDIT-033 to -035
+// FE-MOB-PLEDIT-001 to FE-MOB-PLEDIT-040, plus the 009b, 025b and 029b variants
// planner.t echoes the key, so every label/placeholder is asserted as its key.
const CATEGORIES = [
@@ -93,7 +93,9 @@ describe('MPlaceEditSheet', () => {
id: 7, day_id: 2, place_id: 42, order_index: 0,
place: { ...EDITED, place_time: '14:00', end_time: '15:00' },
} as unknown as Assignment
- setup({ editingPlace: EDITED, editingAssignmentId: 7, assignments: { '2': [assignment] } })
+ // A visit the plan tab lists is in both of the planner's lists.
+ const visits = { '2': [assignment] }
+ setup({ editingPlace: EDITED, editingAssignmentId: 7, assignments: visits, storedAssignments: visits })
expect(screen.getByText('places.startTime')).toBeInTheDocument()
const times = screen.getAllByDisplayValue(/^1[45]:00$/)
expect(times.map(el => (el as HTMLInputElement).value)).toEqual(['14:00', '15:00'])
@@ -293,7 +295,8 @@ describe('MPlaceEditSheet', () => {
it('FE-MOB-PLEDIT-024: blocks the save while the end time is not after the start', () => {
const assignment = { id: 7, day_id: 2, place_id: 42, order_index: 0, place: EDITED } as unknown as Assignment
- setup({ editingPlace: EDITED, editingAssignmentId: 7, assignments: { '2': [assignment] } })
+ const visits = { '2': [assignment] }
+ setup({ editingPlace: EDITED, editingAssignmentId: 7, assignments: visits, storedAssignments: visits })
const [start, end] = screen.getAllByDisplayValue(/^0[89]:[0-3]0$/) as HTMLInputElement[]
expect(submit()).not.toBeDisabled()
fireEvent.change(end, { target: { value: '07:00' } })
@@ -466,4 +469,78 @@ describe('MPlaceEditSheet', () => {
expect(onOpenExpense).not.toHaveBeenCalled()
})
})
+
+ // ── A visit the day lists hide (the road trip stop sheet opens the editor on them) ──
+
+ describe('a visit the day lists hide', () => {
+ /**
+ * A booked night: the phone's filtered `assignments` never carries it, the stored
+ * map does. Its own times differ from the pool place's (08:00 to 09:30), so a
+ * lookup in the wrong list shows up as the wrong clock.
+ */
+ const NIGHT = {
+ id: 7, day_id: 2, place_id: 42, order_index: 0, accommodation_id: 9, notes: 'Late check-in',
+ place: { ...EDITED, place_time: '10:00', end_time: '11:00' },
+ } as unknown as Assignment
+
+ const openOnNight = (overrides: Partial = {}) => setup({
+ editingPlace: EDITED,
+ editingAssignmentId: 7,
+ assignments: {},
+ storedAssignments: { '2': [NIGHT] },
+ ...overrides,
+ })
+
+ it('FE-MOB-PLEDIT-036: reads the times and the day note off the stored visit', () => {
+ openOnNight()
+ const times = screen.getAllByDisplayValue(/^1[01]:00$/) as HTMLInputElement[]
+ expect(times.map(el => el.value)).toEqual(['10:00', '11:00'])
+ expect(screen.getByPlaceholderText('places.assignmentNotesPlaceholder')).toHaveValue('Late check-in')
+ })
+
+ it('FE-MOB-PLEDIT-037: saving it untouched keeps the pinned time and sends no note', async () => {
+ const { planner } = openOnNight()
+ fireEvent.click(submit())
+ await waitFor(() => expect(planner.handleSavePlace).toHaveBeenCalledTimes(1))
+ const payload = vi.mocked(planner.handleSavePlace).mock.calls[0][0]
+ expect(payload).toMatchObject({ place_time: '10:00', end_time: '11:00' })
+ expect(payload).not.toHaveProperty('assignment_notes')
+ })
+
+ it('FE-MOB-PLEDIT-038: an edited day note on it travels with the save', async () => {
+ const { planner } = openOnNight()
+ fireEvent.change(screen.getByPlaceholderText('places.assignmentNotesPlaceholder'), { target: { value: 'Key box at the door' } })
+ fireEvent.click(submit())
+ await waitFor(() => expect(planner.handleSavePlace).toHaveBeenCalledTimes(1))
+ expect(planner.handleSavePlace).toHaveBeenCalledWith(expect.objectContaining({ assignment_notes: 'Key box at the door' }))
+ })
+
+ it('FE-MOB-PLEDIT-039: clearing Start on it sends the empty time that unpins the stop', async () => {
+ const { planner } = openOnNight()
+ const [start] = screen.getAllByDisplayValue('10:00')
+ fireEvent.change(start, { target: { value: '' } })
+ fireEvent.click(submit())
+ await waitFor(() => expect(planner.handleSavePlace).toHaveBeenCalledTimes(1))
+ expect(planner.handleSavePlace).toHaveBeenCalledWith(expect.objectContaining({ place_time: '', end_time: '11:00' }))
+ })
+
+ it('FE-MOB-PLEDIT-040: the overlap warning names what the day lists show, never a hidden stop', () => {
+ const listed = {
+ id: 8, day_id: 2, place_id: 50, order_index: 1,
+ place: { id: 50, name: 'Kaminarimon', place_time: '10:30', end_time: '11:30' },
+ } as unknown as Assignment
+ const hiddenPump = {
+ id: 9, day_id: 2, place_id: 51, order_index: 2,
+ place: { id: 51, name: 'ENEOS Asakusa', stop_type: 'fuel', place_time: '10:15', end_time: '10:45' },
+ } as unknown as Assignment
+ openOnNight({
+ assignments: { '2': [listed] },
+ storedAssignments: { '2': [NIGHT, listed, hiddenPump] },
+ })
+ // The night itself is hidden too, and still gets warned: the warning reads its day off it.
+ const warning = screen.getByText(/places\.timeCollision/)
+ expect(warning).toHaveTextContent('Kaminarimon')
+ expect(warning).not.toHaveTextContent('ENEOS')
+ })
+ })
})
diff --git a/client/tests/unit/mobile/trip/MRoadtripRows.test.tsx b/client/tests/unit/mobile/trip/MRoadtripRows.test.tsx
new file mode 100644
index 000000000..c5972cc3b
--- /dev/null
+++ b/client/tests/unit/mobile/trip/MRoadtripRows.test.tsx
@@ -0,0 +1,627 @@
+import { describe, expect, it, vi } from 'vitest'
+import { fireEvent, render, screen } from '../../../helpers/render'
+import {
+ RtAutoRow, RtDryRow, RtLegRow, RtSpillRow, RtStopRow, type RowChrome,
+} from '../../../../src/mobile/screens/trip/roadtrip/MRoadtripRows'
+import type { StopRow } from '../../../../src/components/Roadtrip/roadtripRowModel'
+import type { RouteSegment, ScheduleWarning } from '@trek/shared/roadtrip'
+import type { TranslationFn } from '../../../../src/types'
+import type { RefuelSearch } from '../../../../src/components/Roadtrip/useRefuelSearch'
+import type { RefuelCandidate } from '../../../../src/components/Roadtrip/refuelSuggestion'
+
+// FE-MOB-RTROW-001 to FE-MOB-RTROW-046
+
+// Same echo strategy as tests/helpers/mobileTrip: assertions stay on keys, not copy.
+const t: TranslationFn = (key, params) =>
+ params ? `${key}:${Object.values(params).join(',')}` : key
+
+const chrome: RowChrome = { t, unit: 'metric' }
+
+function stopRow(over: Partial = {}): StopRow {
+ return {
+ kind: 'stop',
+ stop: {
+ assignmentId: 501, ownerDayId: 2, ownerIndex: 0, placeId: 101,
+ name: 'Kyoto Station', lat: 34.98, lng: 135.75,
+ time: null, dwellMinutes: null, legMode: null, incomingLegMode: null, stopType: null,
+ },
+ number: 2,
+ service: false,
+ entry: undefined,
+ time: '12:40',
+ pinned: false,
+ warning: null,
+ dwellMinutes: null,
+ offRoadMeters: null,
+ ...over,
+ } as StopRow
+}
+
+const SEG: RouteSegment = {
+ mid: [35.4, 138.6], from: [35.7, 139.8], to: [34.98, 135.75],
+ distance: 210_000, duration: 9_600,
+ // The two differ on purpose: durationText is the routed time, drivingText the
+ // fallback the older segments carry.
+ walkingText: '42 h', drivingText: '2 h 55 min', distanceText: '210 km', durationText: '2 h 40 min',
+}
+
+describe('RtStopRow', () => {
+ it('FE-MOB-RTROW-001: gives a destination its number and no kind icon', () => {
+ const { container } = render()
+
+ expect(screen.getByText('2')).toBeInTheDocument()
+ expect(container.querySelector('.lucide-fuel')).toBeNull()
+ })
+
+ it('FE-MOB-RTROW-002: gives a service stop its kind symbol in the kind colour instead of a number', () => {
+ const { container } = render(
+ ,
+ )
+
+ const disc = container.querySelector('.lucide-fuel')?.parentElement as HTMLElement
+ expect(disc).toBeTruthy()
+ // #E8590C is SERVICE_COLORS.fuel, the colour the stop wears on the map too.
+ expect(disc).toHaveStyle({ background: '#E8590C' })
+ expect(screen.queryByText('2')).toBeNull()
+ })
+
+ it('FE-MOB-RTROW-003: keeps at most two marks, a dwell and a warning push the road distance out', () => {
+ const { container } = render(
+ ,
+ )
+
+ expect(screen.getByText('45 min')).toBeInTheDocument()
+ expect(screen.getByText('+25 min')).toBeInTheDocument()
+ expect(screen.queryByText('120 m')).toBeNull()
+ expect(container.querySelector('.lucide-footprints')).toBeNull()
+ })
+
+ it('FE-MOB-RTROW-004: shows the road distance only when the row has neither dwell nor warning', () => {
+ render()
+
+ expect(screen.getByText('120 m')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTROW-005: gives a pinned time the pin and the full colour', () => {
+ render()
+
+ expect(screen.getByLabelText('roadtrip.stop.pinned')).toBeInTheDocument()
+ expect(screen.getByText('12:40').className).toContain('text-m-ink')
+ })
+
+ it('FE-MOB-RTROW-006: leaves a computed time unpinned and muted', () => {
+ render()
+
+ expect(screen.queryByLabelText('roadtrip.stop.pinned')).toBeNull()
+ const time = screen.getByText('12:40')
+ expect(time.className).toContain('text-m-faint')
+ expect(time.className).not.toContain('text-m-ink')
+ })
+
+ it('FE-MOB-RTROW-007: prints no clock for a stop the schedule could not time', () => {
+ render()
+
+ expect(screen.queryByText('12:40')).toBeNull()
+ expect(screen.getByText('Kyoto Station')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTROW-008: opens the stop on a tap and on the keyboard', () => {
+ const onOpen = vi.fn()
+ render()
+
+ const row = screen.getByRole('button')
+ fireEvent.click(row)
+ expect(onOpen).toHaveBeenCalledTimes(1)
+
+ fireEvent.keyDown(row, { key: 'Enter' })
+ expect(onOpen).toHaveBeenCalledTimes(2)
+
+ fireEvent.keyDown(row, { key: ' ' })
+ expect(onOpen).toHaveBeenCalledTimes(3)
+ })
+
+ it('FE-MOB-RTROW-009: ignores a key press that came from something inside the row', () => {
+ const onOpen = vi.fn()
+ render()
+
+ fireEvent.keyDown(screen.getByText('Kyoto Station'), { key: 'Enter' })
+
+ expect(onOpen).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-RTROW-010: writes a late warning as the minutes it costs', () => {
+ const warning: ScheduleWarning = { index: 1, code: 'late', minutes: 25 }
+ const { container } = render()
+
+ expect(screen.getByText('+25 min')).toBeInTheDocument()
+ expect(container.querySelector('.lucide-alert-triangle')).not.toBeNull()
+ })
+
+ it('FE-MOB-RTROW-011: writes a range warning as the distance driven since the last fill', () => {
+ const warning: ScheduleWarning = { index: 1, code: 'range', sinceKm: 520 }
+ const { container } = render()
+
+ expect(screen.getByText('520 km')).toBeInTheDocument()
+ expect(container.querySelector('.lucide-fuel')).not.toBeNull()
+ })
+
+ it('FE-MOB-RTROW-012: writes a leg warning as the time it runs over', () => {
+ const warning: ScheduleWarning = { index: 1, code: 'leg', overMinutes: 35 }
+ render()
+
+ expect(screen.getByText('35 min')).toBeInTheDocument()
+ })
+
+ // The disc as the control that switches a stop between a destination and a pause, the
+ // way the desktop rail's own disc does.
+ it('FE-MOB-RTROW-041: the disc is a button that asks for the kind, and the tap stops there', () => {
+ const onOpen = vi.fn()
+ const onPickKind = vi.fn()
+ render()
+
+ const disc = screen.getByRole('button', { name: 'roadtrip.stop.makeService' })
+ expect(disc).toHaveTextContent('2')
+
+ fireEvent.click(disc)
+
+ expect(onPickKind).toHaveBeenCalledTimes(1)
+ // The row opens the stop; a tap meant for the disc must not do both.
+ expect(onOpen).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-RTROW-042: the disc of a service stop asks the same question, named for what it already is', () => {
+ const onPickKind = vi.fn()
+ render(
+ ,
+ )
+
+ const disc = screen.getByRole('button', { name: 'roadtrip.stop.kind' })
+ // Still the kind's own symbol: the control is its own preview of what it changes.
+ expect(disc.querySelector('.lucide-fuel')).not.toBeNull()
+
+ fireEvent.click(disc)
+ expect(onPickKind).toHaveBeenCalledTimes(1)
+ })
+
+ it('FE-MOB-RTROW-043: without the handler the disc is not a button at all', () => {
+ // A traveller who may not edit places gets no handler, and a disabled-looking control
+ // for something they cannot do is worse than no control.
+ render()
+
+ expect(screen.queryByRole('button', { name: 'roadtrip.stop.makeService' })).toBeNull()
+ expect(screen.queryByRole('button', { name: 'roadtrip.stop.kind' })).toBeNull()
+ expect(screen.getByText('2')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTROW-013: writes an overnight warning as a word, since it has no figure', () => {
+ const warning: ScheduleWarning = { index: 1, code: 'overnight' }
+ const { container } = render()
+
+ expect(screen.getByText('roadtrip.warn.overnight')).toBeInTheDocument()
+ expect(container.querySelector('.lucide-moon')).not.toBeNull()
+ })
+})
+
+describe('RtLegRow', () => {
+ it('FE-MOB-RTROW-014: without a way to ask for other roads the leg is not a control, no button, no role, nothing focusable', () => {
+ const { container } = render()
+
+ expect(screen.queryByRole('button')).toBeNull()
+ expect(container.querySelector('button')).toBeNull()
+ expect(container.querySelector('[role]')).toBeNull()
+ expect(container.querySelector('[tabindex]')).toBeNull()
+ })
+
+ it('FE-MOB-RTROW-015: prints the drive and the car icon for a routed leg, falling back to the driving text', () => {
+ const bare = render()
+ expect(screen.getByText('roadtrip.leg.driveText:210 km,2 h 55 min')).toBeInTheDocument()
+ bare.unmount()
+
+ const { container } = render()
+
+ expect(screen.getByText('roadtrip.leg.driveText:210 km,2 h 40 min')).toBeInTheDocument()
+ expect(container.querySelector('.lucide-car-front')).not.toBeNull()
+ })
+
+ it('FE-MOB-RTROW-016: says the leg is pending while no segment has come back', () => {
+ render()
+
+ expect(screen.getByText('roadtrip.leg.pending')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTROW-044: a segment with no texts yet is read off its numbers, the way the desktop rail reads it', () => {
+ // A segment can reach the chain before its routing round has landed: metres and
+ // seconds are there, the pre-formatted texts are not.
+ render(
+ ,
+ )
+
+ expect(screen.getByText('roadtrip.leg.driveText:210 km,2 h 40 min')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTROW-045: a segment with neither texts nor numbers says pending, never a bare separator', () => {
+ // This printed the template with both slots empty, so the pill read " in " and said
+ // nothing at all. A leg that is not routed says so.
+ render(
+ ,
+ )
+
+ expect(screen.getByText('roadtrip.leg.pending')).toBeInTheDocument()
+ expect(screen.queryByText(/driveText/)).toBeNull()
+ })
+
+ it('FE-MOB-RTROW-046: half a segment is pending too, rather than a figure with a hole beside it', () => {
+ // A distance with no time would read "210 km in", which is worse than saying nothing:
+ // it looks like a sentence that was cut off.
+ render(
+ ,
+ )
+
+ expect(screen.getByText('roadtrip.leg.pending')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTROW-017: swaps the icon for a walked leg and for a plugin mode', () => {
+ const walk = render()
+ expect(walk.container.querySelector('.lucide-footprints')).not.toBeNull()
+ walk.unmount()
+
+ const plugin = render()
+ expect(plugin.container.querySelector('.lucide-zap')).not.toBeNull()
+ })
+
+ it('FE-MOB-RTROW-038: other ways are one round button beside the pill, and the pill stays text', () => {
+ const onAlternatives = vi.fn()
+ const { container } = render()
+
+ const buttons = screen.getAllByRole('button')
+ expect(buttons).toHaveLength(1)
+ const ask = screen.getByRole('button', { name: 'roadtrip.alt.ask' })
+ expect(ask.querySelector('.lucide-shuffle')).not.toBeNull()
+ // A separate 40px target: a tap that stops a scroll on the pill asks the router nothing.
+ expect(ask.className).toContain('h-10')
+ expect(ask.className).toContain('w-10')
+ const drive = screen.getByText('roadtrip.leg.driveText:210 km,2 h 40 min')
+ expect(ask.contains(drive)).toBe(false)
+ expect(drive.closest('[role]')).toBeNull()
+ fireEvent.click(drive)
+ expect(onAlternatives).not.toHaveBeenCalled()
+
+ fireEvent.click(ask)
+ expect(onAlternatives).toHaveBeenCalledTimes(1)
+ expect(container.querySelectorAll('[tabindex]')).toHaveLength(0)
+ })
+
+ it('FE-MOB-RTROW-039: shows pressed while its leg is open, in full ink rather than a filled button', () => {
+ const closed = render()
+ const idle = screen.getByRole('button', { name: 'roadtrip.alt.ask' })
+ expect(idle).toHaveAttribute('aria-pressed', 'false')
+ expect(idle.className).toContain('text-m-muted')
+ closed.unmount()
+
+ render()
+ const open = screen.getByRole('button', { name: 'roadtrip.alt.ask' })
+ expect(open).toHaveAttribute('aria-pressed', 'true')
+ expect(open.className).toContain('text-m-ink')
+ // A filled chip in a column of quiet rows reads as a button pressed and stuck.
+ expect(open.className).not.toContain('bg-m-act')
+ })
+
+ it('FE-MOB-RTROW-040: offline the button keeps its place but does nothing', () => {
+ const onAlternatives = vi.fn()
+ render()
+
+ const ask = screen.getByRole('button', { name: 'roadtrip.alt.ask' })
+ expect(ask).toBeDisabled()
+ fireEvent.click(ask)
+ expect(onAlternatives).not.toHaveBeenCalled()
+ })
+})
+
+describe('RtDryRow', () => {
+ const idle = {
+ openFor: null, loading: false, outcome: null, results: [], offered: [],
+ ask: vi.fn(), close: vi.fn(),
+ } as unknown as RefuelSearch
+ const props = { intoLegKm: 82, chrome, electric: false, offline: false, refuel: idle, dayId: 7, legIndex: 1 }
+
+ it('FE-MOB-RTROW-018: names the fuel wording and the distance into the leg for a combustion car', () => {
+ const { container } = render()
+
+ expect(screen.getByText('roadtrip.refuel.dry')).toBeInTheDocument()
+ expect(screen.getByText('roadtrip.refuel.after:82 km')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'roadtrip.refuel.find' })).toBeInTheDocument()
+ expect(container.querySelector('svg.trek--transport')).not.toBeNull()
+ })
+
+ it('FE-MOB-RTROW-019: swaps to the charging wording for an electric car', () => {
+ render()
+
+ expect(screen.getByText('roadtrip.refuel.dryElectric')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'roadtrip.refuel.findElectric' })).toBeInTheDocument()
+ expect(screen.queryByText('roadtrip.refuel.dry')).toBeNull()
+ })
+
+ it('FE-MOB-RTROW-020: searches from the button', () => {
+ const onSearch = vi.fn()
+ render()
+
+ fireEvent.click(screen.getByRole('button', { name: 'roadtrip.refuel.find' }))
+ expect(onSearch).toHaveBeenCalledTimes(1)
+ })
+
+ it('FE-MOB-RTROW-021: disables the search offline and says why underneath it', () => {
+ const onSearch = vi.fn()
+ render()
+
+ const button = screen.getByRole('button', { name: 'roadtrip.refuel.find' })
+ expect(button).toBeDisabled()
+ expect(screen.getByText('mobileTrip.rtSearchOffline')).toBeInTheDocument()
+ // The lamp stops glowing: a lamp that glows invites a press that cannot work.
+ expect(button.querySelector('svg.lucide-fuel')).not.toBeNull()
+ expect(button.querySelector('.trek-lowfuel')).toBeNull()
+
+ fireEvent.click(button)
+ expect(onSearch).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-RTROW-022: drops the button entirely without write permission, offline line included', () => {
+ const { container } = render()
+
+ expect(screen.queryByRole('button')).toBeNull()
+ expect(screen.queryByText('mobileTrip.rtSearchOffline')).toBeNull()
+ // The warning itself stays: it is information, not an action. The reserve lamp too,
+ // as a mark rather than a control.
+ expect(screen.getByText('roadtrip.refuel.dry')).toBeInTheDocument()
+ expect(container.querySelector('.trek-lowfuel')).not.toBeNull()
+ })
+ const offer = (over: Record = {}) => ({
+ osm_id: 'n1', name: 'Shell Ebina', lat: 35.44, lng: 139.39, category: 'fuel',
+ poi_type: 'amenity=fuel', address: null, website: null, phone: null,
+ opening_hours: null, cuisine: null, source: 'openstreetmap',
+ offRouteKm: 0.4, alongKm: 70, spareKm: 22, ...over,
+ }) as unknown as RefuelCandidate
+
+ const answering = (over: Partial = {}) => ({
+ ...idle, openFor: '7:1', ...over,
+ } as unknown as RefuelSearch)
+
+ it('FE-MOB-RTROW-027: says it is looking while the search runs', () => {
+ render()
+
+ expect(screen.getByText('roadtrip.refuel.looking')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTROW-028: offers what it found, with the detour and what is left in the tank', () => {
+ render(
+ ,
+ )
+
+ expect(screen.getByText('Shell Ebina')).toBeInTheDocument()
+ expect(screen.getByText('roadtrip.poi.offRoute:400 m · roadtrip.refuel.spare:22 km')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTROW-029: an offer three legs away does not light up this band', () => {
+ // One search is open at a time and it names the dry point it belongs to.
+ render(
+ ,
+ )
+
+ expect(screen.queryByText('Shell Ebina')).toBeNull()
+ })
+
+ it('FE-MOB-RTROW-030: taking an offer goes through the planner, and never without permission', () => {
+ const onAccept = vi.fn()
+ const refuel = answering({ outcome: 'found', results: [offer()] })
+ const view = render()
+
+ fireEvent.click(screen.getByRole('button', { name: 'roadtrip.refuel.add:Shell Ebina' }))
+ expect(onAccept).toHaveBeenCalledWith(expect.objectContaining({ osm_id: 'n1' }))
+ view.unmount()
+
+ render()
+ expect(screen.queryByRole('button', { name: 'roadtrip.refuel.add:Shell Ebina' })).toBeNull()
+ // The offer is still worth seeing: a reader can look up a station even if they
+ // cannot put it on the trip.
+ expect(screen.getByText('Shell Ebina')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTROW-031: three sentences for three different facts, and none of them "nothing here"', () => {
+ const none = render()
+ expect(screen.getByText('roadtrip.refuel.none')).toBeInTheDocument()
+ none.unmount()
+
+ const cut = render()
+ expect(screen.getByText('roadtrip.refuel.incomplete')).toBeInTheDocument()
+ cut.unmount()
+
+ render()
+ // A request that failed never checked the stretch, so it must not read as empty.
+ expect(screen.getByText('roadtrip.refuel.failed')).toBeInTheDocument()
+ expect(screen.queryByText('roadtrip.refuel.none')).toBeNull()
+ })
+
+ it('FE-MOB-RTROW-032: the mascot rides the skateboard, sad, in the band colour and on an opaque ground', () => {
+ const { container } = render()
+
+ const mascot = container.querySelector('svg.trek--transport') as SVGElement
+ // Expression eyes, not the default open ones, bent down rather than up.
+ expect(mascot.querySelectorAll('.trek-eye')).toHaveLength(0)
+ const eyes = mascot.querySelectorAll('.trek-body g[stroke] path')
+ expect(eyes).toHaveLength(2)
+ const [, startY, controlY] = /^M[\d.]+ ([\d.]+) Q[\d.]+ ([\d.]+)/.exec(eyes[0].getAttribute('d') ?? '') ?? []
+ expect(Number(controlY)).toBeGreaterThan(Number(startY))
+
+ // Renamed on the mascot's own span, against an opaque surface so the cut out eyes
+ // do not show the body through them.
+ const wrapper = mascot.parentElement as HTMLElement
+ expect(wrapper.style.getPropertyValue('--m-ink')).toBe('var(--m-st-danger)')
+ expect(wrapper.style.getPropertyValue('--m-bg')).toContain('--m-sheetop')
+ // And never on the band, where the offers read --m-ink and have to stay ink.
+ expect((container.firstElementChild as HTMLElement).style.getPropertyValue('--m-ink')).toBe('')
+ })
+
+ it('FE-MOB-RTROW-033: the reserve lamp is the button, with its words in the label only', () => {
+ const fuel = render()
+
+ const lamp = screen.getByRole('button', { name: 'roadtrip.refuel.find' })
+ expect(lamp.querySelector('svg.lucide-fuel.trek-lowfuel')).not.toBeNull()
+ // Not the black pill it replaced, and no visible label beside the mascot and title.
+ expect(lamp.className).not.toContain('bg-m-act')
+ expect(screen.queryByText('roadtrip.refuel.find')).toBeNull()
+ fuel.unmount()
+
+ render()
+ expect(screen.getByRole('button', { name: 'roadtrip.refuel.findElectric' }).querySelector('svg.lucide-zap')).not.toBeNull()
+ })
+
+ it('FE-MOB-RTROW-034: while the search runs or offers show, the lamp steps aside for a close', () => {
+ // The map draws the offers, and the band is where somebody lets those pins go.
+ const close = vi.fn()
+ const running = render()
+
+ expect(screen.queryByRole('button', { name: 'roadtrip.refuel.find' })).toBeNull()
+ fireEvent.click(screen.getByRole('button', { name: 'common.close' }))
+ expect(close).toHaveBeenCalledTimes(1)
+ running.unmount()
+
+ const found = render()
+ expect(screen.getByText('Shell Ebina')).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'roadtrip.refuel.find' })).toBeNull()
+ fireEvent.click(screen.getByRole('button', { name: 'common.close' }))
+ expect(close).toHaveBeenCalledTimes(2)
+ found.unmount()
+
+ // Offline the close still works, because closing is local, and with no dead control
+ // in the slot the sentence explaining one stands down.
+ render()
+ const closeOffline = screen.getByRole('button', { name: 'common.close' })
+ expect(closeOffline).toBeEnabled()
+ expect(screen.queryByText('mobileTrip.rtSearchOffline')).toBeNull()
+ fireEvent.click(closeOffline)
+ expect(close).toHaveBeenCalledTimes(3)
+ })
+
+ it('FE-MOB-RTROW-035: an empty answer leaves a retry rather than a dead end, and offline it waits', () => {
+ const onSearch = vi.fn()
+ const failed = render()
+
+ expect(screen.queryByRole('button', { name: 'roadtrip.refuel.find' })).toBeNull()
+ fireEvent.click(screen.getByRole('button', { name: 'roadtrip.refuel.again' }))
+ expect(onSearch).toHaveBeenCalledTimes(1)
+ failed.unmount()
+
+ const none = render()
+ expect(screen.getByRole('button', { name: 'roadtrip.refuel.again' })).toBeInTheDocument()
+ none.unmount()
+
+ render()
+ const again = screen.getByRole('button', { name: 'roadtrip.refuel.again' })
+ expect(again).toBeDisabled()
+ fireEvent.click(again)
+ expect(onSearch).toHaveBeenCalledTimes(1)
+ })
+
+ it('FE-MOB-RTROW-036: lists three offers at most, however many came back', () => {
+ const results = ['n1', 'n2', 'n3', 'n4'].map((id, i) => offer({ osm_id: id, name: `Station ${i + 1}` }))
+ const { container } = render()
+
+ expect(container.querySelectorAll('li')).toHaveLength(3)
+ expect(screen.queryByText('Station 4')).toBeNull()
+ })
+
+ it('FE-MOB-RTROW-037: the battery wording carries through to taking an offer', () => {
+ render(
+ ,
+ )
+
+ expect(screen.getByRole('button', { name: 'roadtrip.refuel.addElectric:Shell Ebina' })).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'roadtrip.refuel.add:Shell Ebina' })).toBeNull()
+ })
+})
+
+describe('RtAutoRow', () => {
+ it('FE-MOB-RTROW-023: marks the end of a day with the moon and the time it stopped', () => {
+ const { container } = render()
+
+ expect(screen.getByText('roadtrip.window.stop')).toBeInTheDocument()
+ expect(screen.getByText('22:00')).toBeInTheDocument()
+ expect(container.querySelector('.lucide-moon')).not.toBeNull()
+ })
+
+ it('FE-MOB-RTROW-024: marks the morning with the sunrise and no clock when there is none', () => {
+ const { container } = render()
+
+ expect(screen.getByText('roadtrip.window.resume')).toBeInTheDocument()
+ expect(container.querySelector('.lucide-sunrise')).not.toBeNull()
+ expect(screen.queryByText('22:00')).toBeNull()
+ })
+})
+
+describe('RtSpillRow', () => {
+ it('FE-MOB-RTROW-025: names the day the night drive came from and when it set off', () => {
+ render(
+
+ Fuji Viewpoint
+ ,
+ )
+
+ expect(screen.getByText('roadtrip.spill.title:1')).toBeInTheDocument()
+ expect(screen.getByText('roadtrip.spill.departs:23:10')).toBeInTheDocument()
+ expect(screen.getByText('Fuji Viewpoint')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTROW-026: leaves the departure off when the night drive has no time', () => {
+ render()
+
+ expect(screen.getByText('roadtrip.spill.title:1')).toBeInTheDocument()
+ expect(screen.queryByText(/roadtrip\.spill\.departs/)).toBeNull()
+ })
+})
diff --git a/client/tests/unit/mobile/trip/MRoadtripTab.test.tsx b/client/tests/unit/mobile/trip/MRoadtripTab.test.tsx
new file mode 100644
index 000000000..e5119f827
--- /dev/null
+++ b/client/tests/unit/mobile/trip/MRoadtripTab.test.tsx
@@ -0,0 +1,721 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { fireEvent, render, screen, within } from '../../../helpers/render'
+import { buildPlanner, buildShell } from '../../../helpers/mobileTrip'
+import { resetAllStores, seedStore } from '../../../helpers/store'
+import { useTripStore } from '../../../../src/store/tripStore'
+import MRoadtripTab from '../../../../src/mobile/screens/trip/roadtrip/MRoadtripTab'
+import type { MTripShellApi, TripPlanner } from '../../../../src/mobile/screens/trip/MTripShell'
+import type { Day, Place } from '../../../../src/types'
+import type { RoadtripDay, RoadtripRoutes, RouteSegment } from '@trek/shared/roadtrip'
+import type { LegAlternatives } from '../../../../src/components/Roadtrip/useRouteAlternatives'
+
+// FE-MOB-RTTAB-001 to FE-MOB-RTTAB-050
+//
+// The stage bar pictures the place its day ends at. It reads that place out of the trip
+// store rather than the planner, the unfiltered list, so the picture tests seed the store.
+
+// The preference store is a zustand slice keyed by user and trip; the tab only ever
+// reads two flags out of it, so the hook is the smaller seam.
+const mocks = vi.hoisted(() => ({
+ prefs: {} as Record,
+ swipe: {} as { onSelectDay: (id: number) => void; describeDay: (i: number, n: number) => string },
+}))
+
+vi.mock('../../../../src/hooks/useRoadtripSettings', () => ({
+ useRoadtripSettings: (select: (p: Record) => unknown) => select(mocks.prefs),
+}))
+
+// The picture asks the photo service for any place without an image of its own. Stubbed to
+// know nothing and fetch nothing, so no test of the bar ever reaches for the network.
+vi.mock('../../../../src/services/photoService', () => ({
+ getCached: () => null,
+ isLoading: () => false,
+ fetchPhoto: vi.fn(),
+ onThumbReady: () => () => {},
+}))
+
+// The swipe itself is the plan tab's, tested there; this keeps the real hook and only
+// records what the road trip tab hands it.
+vi.mock('../../../../src/mobile/screens/trip/plan/useMPlanDaySwipe', async importOriginal => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ useMPlanDaySwipe: (config: Parameters[0]) => {
+ mocks.swipe = config as unknown as typeof mocks.swipe
+ return actual.useMPlanDaySwipe(config)
+ },
+ }
+})
+
+const DAYS = [
+ { id: 1, trip_id: 7, day_number: 1, date: '2026-05-01', title: null },
+ { id: 2, trip_id: 7, day_number: 2, date: '2026-05-02', title: null },
+] as unknown as Day[]
+
+const PLACES = [
+ { id: 101, trip_id: 7, name: 'Fuji Viewpoint', lat: 35.36, lng: 138.73 },
+ { id: 103, trip_id: 7, name: 'Kyoto Station', lat: 34.98, lng: 135.75 },
+] as unknown as Place[]
+
+const seg = (distanceText: string, durationText: string): RouteSegment => ({
+ mid: [35.4, 138.6], from: [35.7, 139.8], to: [34.98, 135.75],
+ distance: 210_000, duration: 9_600,
+ walkingText: '42 h', drivingText: durationText, distanceText, durationText,
+})
+
+/**
+ * One stage with all five row kinds on it.
+ *
+ * The first stop is stored on day 1: it was reached after midnight, so it is drawn on
+ * this card behind a spill band while still belonging to the day before. That is the
+ * case the sheet id has to survive.
+ */
+function stage(over: Partial = {}): RoadtripDay {
+ return {
+ dayId: 2,
+ dayNumber: 2,
+ date: '2026-05-02',
+ title: null,
+ stops: [
+ {
+ assignmentId: 501, ownerDayId: 1, ownerIndex: 3, placeId: 101, name: 'Fuji Viewpoint',
+ lat: 35.36, lng: 138.73, time: null, dwellMinutes: 45,
+ legMode: null, incomingLegMode: null, stopType: null,
+ },
+ {
+ assignmentId: 502, ownerDayId: 2, ownerIndex: 0, placeId: 102, name: 'Shell Ebina',
+ lat: 35.44, lng: 139.39, time: null, dwellMinutes: 10,
+ legMode: null, incomingLegMode: null, stopType: 'fuel',
+ },
+ {
+ assignmentId: 503, ownerDayId: 2, ownerIndex: 1, placeId: 103, name: 'Kyoto Station',
+ lat: 34.98, lng: 135.75, time: null, dwellMinutes: null,
+ legMode: null, incomingLegMode: null, stopType: null,
+ },
+ {
+ assignmentId: 504, ownerDayId: 2, ownerIndex: 2, placeId: 104, name: 'Day end',
+ lat: 34.9, lng: 135.7, time: null, dwellMinutes: null,
+ legMode: null, incomingLegMode: null, stopType: null,
+ automaticNight: { phase: 'end', fromDayNumber: 2 },
+ },
+ ],
+ legs: [seg('62 km', '1 h'), seg('210 km', '2 h 40 min'), undefined],
+ schedule: {
+ entries: [
+ { arrival: '08:30', departure: '09:15', anchored: true, dayOffset: 0 },
+ { arrival: '10:05', departure: '10:15', anchored: false, dayOffset: 0 },
+ { arrival: '12:40', departure: null, anchored: false, dayOffset: 0 },
+ { arrival: '22:00', departure: null, anchored: false, dayOffset: 0 },
+ ],
+ warnings: [],
+ },
+ legVias: [[], [], []],
+ geometry: [],
+ distance: 412_000,
+ duration: 18_000,
+ driveWarnings: [{ index: 2, code: 'late', minutes: 25 }],
+ dayWarning: null,
+ spills: [{ at: 0, count: 1, fromDayNumber: 1, departure: '23:10', leg: undefined }],
+ dryPoints: [{ legIndex: 1, intoLegKm: 82, drivenMeters: 82_000, sinceKm: 520, lat: 35.2, lng: 137.5 }],
+ ...over,
+ } as unknown as RoadtripDay
+}
+
+function routes(over: Partial = {}): RoadtripRoutes {
+ return {
+ days: [stage()],
+ quietDays: [], lines: [], lineDays: [], accessLines: [], vias: [], segments: [],
+ totalDistance: 980_000, totalDuration: 54_000, totalStops: 4, loading: false,
+ ...over,
+ } as unknown as RoadtripRoutes
+}
+
+function planner(over: Partial = {}): TripPlanner {
+ return buildPlanner({
+ tripId: 7,
+ days: DAYS,
+ places: PLACES,
+ selectedDayId: 2,
+ roadtripRoutes: routes(),
+ askRefuel: vi.fn(),
+ ...over,
+ } as Partial)
+}
+
+function renderTab(p: TripPlanner = planner(), shell: MTripShellApi = buildShell()) {
+ const view = render()
+ return { ...view, planner: p, shell }
+}
+
+/** Freezes the clock and hands back the stage's own date, whatever the runner's zone. */
+function freezeAt(hour: number, minute: number): string {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date(2026, 4, 2, hour, minute))
+ return new Date().toISOString().slice(0, 10)
+}
+
+function today(date: string): Partial {
+ return {
+ days: DAYS.map(d => (d.id === 2 ? { ...d, date } : d)) as unknown as Day[],
+ roadtripRoutes: routes({ days: [stage({ date })] }),
+ }
+}
+
+describe('MRoadtripTab', () => {
+ beforeEach(() => {
+ resetAllStores()
+ mocks.prefs = {}
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ describe('list half', () => {
+ it('FE-MOB-RTTAB-001: heads the stage with its start, its arrival, the day total and the stop count', () => {
+ renderTab()
+
+ // The start is the first stop's ARRIVAL (08:30), the clock its row prints, not its
+ // departure (09:15). Nor is it the spill band's 23:10: that one belongs to the day before.
+ const start = screen.getByText('mobileTrip.rtStart').parentElement as HTMLElement
+ expect(within(start).getByText('08:30')).toBeInTheDocument()
+ expect(within(start).queryByText('09:15')).toBeNull()
+ expect(within(start).queryByText('23:10')).toBeNull()
+ const arrive = screen.getByText('roadtrip.stay.arrive').parentElement as HTMLElement
+ expect(within(arrive).getByText('12:40')).toBeInTheDocument()
+ // Both clocks keep their digit order in an RTL locale, like the ones on the rows.
+ expect(within(start).getByText('08:30')).toHaveAttribute('dir', 'ltr')
+ expect(within(arrive).getByText('12:40')).toHaveAttribute('dir', 'ltr')
+
+ expect(screen.getByText('roadtrip.leg.driveText:412 km,5 h')).toBeInTheDocument()
+ expect(screen.getByText('roadtrip.day.stopCount:2')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTTAB-002: dates the head card, and falls back to the day number without a date', () => {
+ renderTab()
+ expect(screen.getByText(/May 2/)).toBeInTheDocument()
+
+ const undated = planner({ days: DAYS.map(d => ({ ...d, date: null })) as unknown as Day[] })
+ const second = render()
+ expect(within(second.container).getByText('roadtrip.day:2')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTTAB-003: draws one row per stop, in the order of the model', () => {
+ renderTab()
+
+ const names = screen.getAllByText(/^(Fuji Viewpoint|Shell Ebina|Kyoto Station)$/).map(n => n.textContent)
+ expect(names).toEqual(['Fuji Viewpoint', 'Shell Ebina', 'Kyoto Station'])
+ // The petrol stop takes no number, so the destination after it is still 2.
+ expect(screen.getByText('1')).toBeInTheDocument()
+ expect(screen.getByText('2')).toBeInTheDocument()
+ expect(screen.queryByText('3')).toBeNull()
+ // And the automatic night is a band, not a stop.
+ expect(screen.queryByText('Day end')).toBeNull()
+ expect(screen.getByText('roadtrip.window.stop')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTTAB-004: opens a stop on the day it is stored on, not the card it is drawn on', () => {
+ const { shell } = renderTab()
+
+ fireEvent.click(screen.getByText('Fuji Viewpoint'))
+
+ expect(shell.openSheet).toHaveBeenCalledWith('rtstop', { dayId: 1, assignmentId: 501 })
+ })
+
+ it('FE-MOB-RTTAB-005: opens a stop of this day with this day', () => {
+ const { shell } = renderTab()
+
+ fireEvent.click(screen.getByText('Kyoto Station'))
+
+ expect(shell.openSheet).toHaveBeenCalledWith('rtstop', { dayId: 2, assignmentId: 503 })
+ })
+
+ it('FE-MOB-RTTAB-051: the disc asks which kind of stop it is, without opening the stop', () => {
+ const { shell } = renderTab()
+
+ // Kyoto Station is a destination, so its disc offers to make it a stop on the way.
+ fireEvent.click(screen.getAllByRole('button', { name: 'roadtrip.stop.makeService' })[1])
+
+ expect(shell.openSheet).toHaveBeenCalledWith('rtkind', {
+ placeId: 103,
+ stopType: null,
+ name: 'Kyoto Station',
+ })
+ // The row's own tap opens the stop; the disc's must not do both.
+ expect(shell.openSheet).toHaveBeenCalledTimes(1)
+ })
+
+ it('FE-MOB-RTTAB-052: a traveller who may not edit places gets a disc that is not a control', () => {
+ renderTab(planner({ can: () => false }))
+
+ expect(screen.queryByRole('button', { name: 'roadtrip.stop.makeService' })).toBeNull()
+ expect(screen.queryByRole('button', { name: 'roadtrip.stop.kind' })).toBeNull()
+ })
+
+ it('FE-MOB-RTTAB-006: writes the day warning out with the sentence the desktop hides in a tooltip', () => {
+ const over = stage({ dayWarning: { code: 'dayDriving', minutes: 620, limitMinutes: 540 } })
+ renderTab(planner({ roadtripRoutes: routes({ days: [over] }) }))
+
+ expect(screen.getByText('roadtrip.limit.dayOver:1 h 20 min')).toBeInTheDocument()
+ expect(screen.getByText('roadtrip.limit.hint')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTTAB-007: leaves the day warning off a stage that stays inside its limit', () => {
+ renderTab()
+
+ expect(screen.queryByText(/roadtrip\.limit\.dayOver/)).toBeNull()
+ expect(screen.queryByText('roadtrip.limit.hint')).toBeNull()
+ })
+
+ it('FE-MOB-RTTAB-008: shows the empty stage without a summary card full of zeroes', () => {
+ renderTab(planner({ roadtripRoutes: routes({ days: [] }) }))
+
+ expect(screen.getByText('roadtrip.empty.title')).toBeInTheDocument()
+ expect(screen.getByText('mobileTrip.rtPlanOnDesktop')).toBeInTheDocument()
+ expect(screen.queryByText('mobileTrip.rtStart')).toBeNull()
+ expect(screen.queryByText(/roadtrip\.day\.stopCount/)).toBeNull()
+ })
+
+ it('FE-MOB-RTTAB-009: shows the partial hint instead of the empty state while the round is still running', () => {
+ renderTab(planner({ roadtripRoutes: routes({ days: [], loading: true }) }))
+
+ expect(screen.getByText('roadtrip.summary.partial')).toBeInTheDocument()
+ expect(screen.queryByText('roadtrip.empty.title')).toBeNull()
+ expect(screen.queryByText('mobileTrip.rtPlanOnDesktop')).toBeNull()
+ })
+
+ it('FE-MOB-RTTAB-010: draws no day colour dot in the head card, even with the day colours on', () => {
+ // The colour keys the day's line on the map, which lies under the list on this half,
+ // so a dot here had nothing on screen to explain it.
+ mocks.prefs = { roadtrip_day_colors: true }
+ renderTab()
+
+ const card = screen.getByText('mobileTrip.rtStart').closest('section') as HTMLElement
+ // The dot was the card's only inline paint (this stage carries no day warning).
+ expect(card.querySelectorAll('[style]')).toHaveLength(0)
+ expect(card.querySelector('[aria-hidden="true"]')).toBeNull()
+ // The date is text and nothing else, with no swatch leading or trailing it.
+ expect(screen.getByText(/May 2/).children).toHaveLength(0)
+ })
+
+ it('FE-MOB-RTTAB-011: dashes the two figures for a stage the routing could not time', () => {
+ const untimed = stage({
+ schedule: { entries: [0, 1, 2, 3].map(() => ({ arrival: null, departure: null, anchored: false, dayOffset: 0 })), warnings: [] },
+ } as unknown as Partial)
+ renderTab(planner({ roadtripRoutes: routes({ days: [untimed] }) }))
+
+ const start = screen.getByText('mobileTrip.rtStart').parentElement as HTMLElement
+ expect(within(start).getByText('-')).toBeInTheDocument()
+ const arrive = screen.getByText('roadtrip.stay.arrive').parentElement as HTMLElement
+ expect(within(arrive).getByText('-')).toBeInTheDocument()
+ // The chain itself still stands, it just carries no clocks.
+ expect(screen.getByText('Kyoto Station')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTTAB-012: says the day total is still partial while the distance is zero', () => {
+ renderTab(planner({ roadtripRoutes: routes({ days: [stage({ distance: 0 })] }) }))
+
+ expect(screen.getByText('roadtrip.summary.partial')).toBeInTheDocument()
+ expect(screen.queryByText(/roadtrip\.leg\.driveText:412/)).toBeNull()
+ })
+
+ it('FE-MOB-RTTAB-032: heads the card with the clock the first row prints, not the end of its stay', () => {
+ // The reported stage: Hamburg Speicherstadt pinned at 10:00 with an hour and a half
+ // there, Sanssouci reached at 19:33. The card used to read LEAVE 11:30, a clock no row
+ // shows, which hid the pinned appointment behind its own stay.
+ const reported = stage({
+ spills: [],
+ stops: [
+ {
+ assignmentId: 601, ownerDayId: 2, ownerIndex: 0, placeId: 201, name: 'Hamburg Speicherstadt',
+ lat: 53.54, lng: 9.99, time: '10:00', dwellMinutes: 90,
+ legMode: null, incomingLegMode: null, stopType: null,
+ },
+ {
+ assignmentId: 602, ownerDayId: 2, ownerIndex: 1, placeId: 202, name: 'Sanssouci Palace',
+ lat: 52.4, lng: 13.04, time: null, dwellMinutes: 120,
+ legMode: null, incomingLegMode: null, stopType: null,
+ },
+ ],
+ legs: [seg('290 km', '3 h')],
+ legVias: [[]],
+ schedule: {
+ entries: [
+ { arrival: '10:00', departure: '11:30', anchored: true, dayOffset: 0 },
+ { arrival: '19:33', departure: '21:33', anchored: false, dayOffset: 0 },
+ ],
+ warnings: [],
+ },
+ dryPoints: [],
+ driveWarnings: [],
+ } as unknown as Partial)
+ renderTab(planner({ roadtripRoutes: routes({ days: [reported] }) }))
+
+ const start = screen.getByText('mobileTrip.rtStart').parentElement as HTMLElement
+ expect(within(start).getByText('10:00')).toBeInTheDocument()
+ const arrive = screen.getByText('roadtrip.stay.arrive').parentElement as HTMLElement
+ expect(within(arrive).getByText('19:33')).toBeInTheDocument()
+ // Neither departure is printed anywhere on the screen, and the word for one is gone.
+ expect(screen.queryByText('11:30')).toBeNull()
+ expect(screen.queryByText('21:33')).toBeNull()
+ expect(screen.queryByText('roadtrip.stay.leave')).toBeNull()
+ // The figure is the very clock the first row carries.
+ const firstRow = screen.getByText('Hamburg Speicherstadt').closest('[role=button]') as HTMLElement
+ expect(within(firstRow).getByText('10:00')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTTAB-042: carries the day\'s facts on the date line as badges, above the clocks', () => {
+ renderTab()
+
+ const date = screen.getByText(/May 2/)
+ const line = date.parentElement as HTMLElement
+ // The date takes the start and the badges pack to the end, and the line may wrap.
+ expect(date.className).toContain('me-auto')
+ expect(line.className).toContain('flex-wrap')
+ const drive = within(line).getByText('roadtrip.leg.driveText:412 km,5 h').closest('.rounded-full') as HTMLElement
+ const stops = within(line).getByText('roadtrip.day.stopCount:2').closest('.rounded-full') as HTMLElement
+ expect(drive).not.toBeNull()
+ expect(stops).not.toBeNull()
+ expect(drive).not.toBe(stops)
+ // The two share one wrapper beside the date, so they wrap under it as a pair and a long
+ // drive never leaves the count alone on the next line, away from the drive.
+ const pair = drive.parentElement as HTMLElement
+ expect(stops.parentElement).toBe(pair)
+ expect(pair.parentElement).toBe(line)
+ expect(pair.className).toContain('flex-wrap')
+ expect(pair.className).toContain('max-w-full')
+ // The distance keeps its unit's case; the count is a word, in caps like the stage bar's.
+ expect(drive.className).not.toContain('uppercase')
+ expect(stops.className).toContain('uppercase')
+ // The clocks are the band under the line, not part of it.
+ expect(within(line).queryByText('mobileTrip.rtStart')).toBeNull()
+ const clocks = screen.getByText('mobileTrip.rtStart')
+ expect(line.compareDocumentPosition(clocks) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
+ })
+
+ it('FE-MOB-RTTAB-043: puts the partial total on the date line in a badge that may wrap', () => {
+ renderTab(planner({ roadtripRoutes: routes({ days: [stage({ distance: 0 })] }) }))
+
+ const line = screen.getByText(/May 2/).parentElement as HTMLElement
+ const badge = within(line).getByText('roadtrip.summary.partial')
+ // The sentence breaks inside its badge rather than pushing past the card, and the
+ // badge stops at the line's width and grows with the text instead of clipping it.
+ expect(badge.className).toContain('rounded-full')
+ expect(badge.className).toContain('whitespace-normal')
+ expect(badge.className).toContain('max-w-full')
+ expect(badge.className).not.toMatch(/(^|\s)h-\[18px\]/)
+ expect(badge.className).not.toContain('uppercase')
+ // The stop count beside it is a figure, and stays on one line.
+ expect(within(line).getByText('roadtrip.day.stopCount:2').className).toContain('whitespace-nowrap')
+ })
+
+ it('FE-MOB-RTTAB-044: sets the clocks smaller and draws no divider band, so the card stays a header', () => {
+ renderTab()
+
+ for (const [label, clock] of [['mobileTrip.rtStart', '08:30'], ['roadtrip.stay.arrive', '12:40']] as const) {
+ const value = within(screen.getByText(label).parentElement as HTMLElement).getByText(clock)
+ expect(value.className).toContain('text-[1.5rem]')
+ expect(value.className).not.toContain('text-[1.875rem]')
+ }
+ const card = screen.getByText('mobileTrip.rtStart').closest('section') as HTMLElement
+ expect(card.querySelector('[class*="border-t"]')).toBeNull()
+ const padding = card.className.split(' ')
+ expect(padding).toContain('py-3')
+ expect(padding).not.toContain('py-3.5')
+ })
+ })
+
+ describe('up next', () => {
+ it('FE-MOB-RTTAB-013: counts down to the next stop still ahead, on the day it actually is', () => {
+ const date = freezeAt(7, 0)
+ renderTab(planner(today(date)))
+
+ const card = screen.getByText('mobileTrip.upNext').closest('section') as HTMLElement
+ expect(within(card).getByText('Fuji Viewpoint')).toBeInTheDocument()
+ expect(within(card).getByText('mobileTrip.inCountdown:1 h 30 min')).toBeInTheDocument()
+ expect(within(card).getByText('08:30')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTTAB-014: shows no countdown on a day that is not today', () => {
+ const date = freezeAt(7, 0)
+ const shifted = new Date(`${date}T00:00:00Z`)
+ shifted.setUTCDate(shifted.getUTCDate() + 7)
+ renderTab(planner(today(shifted.toISOString().slice(0, 10))))
+
+ // Same clock, same stage, a week further on: the countdown is about the date.
+ expect(screen.queryByText('mobileTrip.upNext')).toBeNull()
+ expect(screen.getByText('mobileTrip.rtStart')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTTAB-015: shows no countdown once the last stop is behind you', () => {
+ const date = freezeAt(23, 30)
+ renderTab(planner(today(date)))
+
+ expect(screen.queryByText('mobileTrip.upNext')).toBeNull()
+ })
+
+ it('FE-MOB-RTTAB-016: opens the stop from the countdown card', () => {
+ const date = freezeAt(7, 0)
+ const { shell } = renderTab(planner(today(date)))
+
+ fireEvent.click(screen.getByText('mobileTrip.upNext'))
+
+ expect(shell.openSheet).toHaveBeenCalledWith('rtstop', { dayId: 1, assignmentId: 501 })
+ })
+
+ it('FE-MOB-RTTAB-017: shows the next stop on the map half by moving the camera, not the place selection', () => {
+ const date = freezeAt(7, 0)
+ const p = planner(today(date))
+ const { shell } = renderTab(p)
+
+ fireEvent.click(screen.getByLabelText('mobileTrip.showOnMap'))
+
+ expect(p.focusRoadtripPoint).toHaveBeenCalledWith(35.36, 138.73)
+ expect(shell.toggleRtView).toHaveBeenCalledTimes(1)
+ // The place inspector opens off the selection and would come up over the stage.
+ expect(p.setSelectedPlaceId).not.toHaveBeenCalled()
+ // Up next is always a stop of the stage on screen, so the day stays where it is.
+ expect(p.handleSelectDay).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-RTTAB-018: leaves the navigate link dead when the stop has no place row behind it', () => {
+ const date = freezeAt(7, 0)
+ const enabled = renderTab(planner(today(date)))
+ expect(screen.getByText('places.navigate').closest('a')).toHaveAttribute('aria-disabled', 'false')
+ enabled.unmount()
+
+ renderTab(planner({ ...today(date), places: [] }))
+ const link = screen.getByText('places.navigate').closest('a') as HTMLElement
+ expect(link).toHaveAttribute('aria-disabled', 'true')
+ expect(link).toHaveAttribute('href', '#')
+ })
+ })
+
+ describe('refuel', () => {
+ it('FE-MOB-RTTAB-019: asks for a refuel with the dry point of the leg the band sits on', () => {
+ const p = planner()
+ renderTab(p)
+
+ fireEvent.click(screen.getByRole('button', { name: 'roadtrip.refuel.find' }))
+
+ expect(p.askRefuel).toHaveBeenCalledWith(2, expect.objectContaining({ legIndex: 1, intoLegKm: 82 }))
+ })
+
+ it('FE-MOB-RTTAB-020: offers no refuel search to a member who cannot edit the day', () => {
+ renderTab(planner({ can: vi.fn(() => false) }))
+
+ expect(screen.getByText('roadtrip.refuel.dry')).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'roadtrip.refuel.find' })).toBeNull()
+ })
+
+ it('FE-MOB-RTTAB-021: reads the vehicle out of the trip preferences', () => {
+ mocks.prefs = { roadtrip_vehicle: 'electric' }
+ renderTab()
+
+ expect(screen.getByText('roadtrip.refuel.dryElectric')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'roadtrip.refuel.findElectric' })).toBeInTheDocument()
+ })
+ })
+
+ describe('map half', () => {
+ const mapShell = () => buildShell({ rtView: 'map' })
+
+ it('FE-MOB-RTTAB-022: leaves the map to itself, with no bar of its own over it', () => {
+ const { container } = renderTab(planner(), mapShell())
+
+ expect((container.firstChild as HTMLElement).className).toContain('pointer-events-none')
+ expect(screen.queryByText('mobileTrip.rtStart')).toBeNull()
+ expect(screen.queryByText('Shell Ebina')).toBeNull()
+ expect(screen.queryByText('roadtrip.refuel.dry')).toBeNull()
+ expect(screen.queryByText('roadtrip.window.stop')).toBeNull()
+
+ // A stage bar used to stand over the dock here, naming the day's destination with its
+ // picture, stop count, arrival and distance. The day and the distance are in the
+ // shell's stage header already, and on a map that fills the screen a permanent card
+ // over the bottom edge cost more than the three facts it added. Nothing is left of it:
+ // not the destination, not its badges, and not an empty wrapper over the map's own
+ // buttons. The picker's bar still uses that slot (FE-MOB-RTTAB-048).
+ expect(screen.queryByText('Kyoto Station')).toBeNull()
+ expect(screen.queryByText('roadtrip.day.stopCount:2')).toBeNull()
+ expect(screen.queryByText('412 km')).toBeNull()
+ expect(screen.queryByRole('button', { name: /Kyoto Station/ })).toBeNull()
+ // The search bar is still up top; what is gone is the wrapper down at the dock.
+ expect(container.querySelector('[class*="bottom-[calc(var(--bottom-nav-h"]')).toBeNull()
+ })
+
+ })
+
+ describe('the corridor search', () => {
+ const mapShell = () => buildShell({ rtView: 'map' })
+
+ it('FE-MOB-RTTAB-028: the search bar stands in the same band on both halves', () => {
+ const list = renderTab()
+ const inList = screen.getByText('roadtrip.poi.title').closest('div[class*="top-[calc"]')
+ expect(inList).not.toBeNull()
+ list.unmount()
+
+ renderTab(planner(), mapShell())
+ const onMap = screen.getByText('roadtrip.poi.title').closest('div[class*="top-[calc"]')
+ // Literally the same offset: one stage seen two ways, and a control that jumps
+ // between them is a control you have to find twice.
+ expect(onMap?.className).toBe(inList?.className)
+ })
+
+ it('FE-MOB-RTTAB-029: it opens the search sheet', () => {
+ const { shell } = renderTab()
+
+ fireEvent.click(screen.getByText('roadtrip.poi.title'))
+ expect(shell.openSheet).toHaveBeenCalledWith('rtsearch')
+ })
+
+ it('FE-MOB-RTTAB-030: the chain starts below the bar rather than under it', () => {
+ const { container } = renderTab()
+
+ const scroller = container.querySelector('[class*="overflow-y-auto"]') as HTMLElement
+ // 96px band plus a 44px bar plus its gap. A padding left at the old 102 would
+ // put the head card's first line behind the glass.
+ expect(scroller.className).toContain('pt-[calc(var(--m-safe-top,12px)+150px)]')
+ })
+ it('FE-MOB-RTTAB-031: no stage, no search bar, and the chain keeps its old top', () => {
+ // Without a stage the corridor falls back to the trip's first routed day, which
+ // is not the one on screen: every distance it answered with would be measured
+ // against a road nobody is looking at.
+ const { container } = renderTab(planner({ selectedDayId: null }))
+
+ expect(screen.queryByText('roadtrip.poi.title')).toBeNull()
+ const scroller = container.querySelector('[class*="overflow-y-auto"]') as HTMLElement
+ expect(scroller.className).toContain('pt-[calc(var(--m-safe-top,12px)+102px)]')
+ })
+ })
+
+ describe('other ways of driving a leg', () => {
+ const askButtons = () => screen.queryAllByRole('button', { name: 'roadtrip.alt.ask' })
+
+ /** The planner with a picker open on one leg, still asking the router. */
+ function withPicker(open: Partial, over: Partial = {}): TripPlanner {
+ const base = buildPlanner()
+ return planner({
+ routeAlternatives: { ...base.routeAlternatives, open: { dayId: 2, index: 0, routes: [], loading: true, error: false, ...open } },
+ ...over,
+ })
+ }
+
+ it('FE-MOB-RTTAB-045: offers the question on the legs the desk rail offers it on, and only to an editor', () => {
+ const full = renderTab()
+ // Two routed legs between real stops. The third runs into the automatic day end,
+ // which is the shell's own marker and not a road anyone can reshape.
+ expect(askButtons()).toHaveLength(2)
+ const kyotoLeg = screen.getByText('roadtrip.leg.driveText:210 km,2 h 40 min').closest('.grid') as HTMLElement
+ expect(within(kyotoLeg).getByRole('button', { name: 'roadtrip.alt.ask' })).toBeInTheDocument()
+ full.unmount()
+
+ // Routed or not, that last leg stays a line of text: the fixture leaves it unrouted
+ // too, so a routed one pins that the day end, not the missing route, is the reason.
+ const intoNight = renderTab(planner({
+ roadtripRoutes: routes({ days: [stage({ legs: [seg('62 km', '1 h'), seg('210 km', '2 h 40 min'), seg('12 km', '10 min')] })] }),
+ }))
+ expect(askButtons()).toHaveLength(2)
+ const nightLeg = screen.getByText('roadtrip.leg.driveText:12 km,10 min').closest('.grid') as HTMLElement
+ expect(within(nightLeg).queryByRole('button')).toBeNull()
+ intoNight.unmount()
+
+ // A leg the routing has not answered for has nothing to weigh an offer against.
+ const unrouted = renderTab(planner({ roadtripRoutes: routes({ days: [stage({ legs: [seg('62 km', '1 h'), undefined, undefined] })] }) }))
+ expect(askButtons()).toHaveLength(1)
+ // Both unanswered legs are drawn, only neither of them asks.
+ expect(screen.getAllByText('roadtrip.leg.pending')).toHaveLength(2)
+ unrouted.unmount()
+
+ renderTab(planner({ can: vi.fn(() => false) }))
+ expect(askButtons()).toHaveLength(0)
+ })
+
+ it('FE-MOB-RTTAB-046: asks with the card\'s day, clears the old pick and the fuel search, and goes to the map', () => {
+ const p = planner()
+ const { shell } = renderTab(p)
+
+ fireEvent.click(askButtons()[0])
+
+ expect(p.setHighlightedAlternative).toHaveBeenCalledWith(null)
+ expect(p.refuel.close).toHaveBeenCalledTimes(1)
+ // Day 2, the card: the leg's first stop is stored on day 1, and the planner works
+ // that out from the card itself, the way the desk rail asks.
+ expect(p.askRouteAlternatives).toHaveBeenCalledWith(2, 0)
+ expect(p.askRouteAlternatives).not.toHaveBeenCalledWith(1, expect.anything())
+ expect(shell.toggleRtView).toHaveBeenCalledTimes(1)
+ })
+
+ it('FE-MOB-RTTAB-047: the leg with the picker open shows pressed, and tapping it goes back to the answer without asking again', () => {
+ const p = withPicker({ index: 0 })
+ const { shell } = renderTab(p)
+
+ const [open, other] = askButtons()
+ expect(open).toHaveAttribute('aria-pressed', 'true')
+ expect(other).toHaveAttribute('aria-pressed', 'false')
+
+ fireEvent.click(open)
+
+ // The planner toggles an open leg shut, and the traveller came back for its answer.
+ expect(p.askRouteAlternatives).not.toHaveBeenCalled()
+ expect(p.routeAlternatives.close).not.toHaveBeenCalled()
+ expect(shell.toggleRtView).toHaveBeenCalledTimes(1)
+ })
+
+ it('FE-MOB-RTTAB-048: on the map the picker stands over the dock and the search bar steps away', () => {
+ const shell = buildShell({ rtView: 'map' })
+ const open = renderTab(withPicker({}), shell)
+
+ const bar = screen.getByRole('region', { name: 'roadtrip.alt.title' })
+ expect(within(bar).getByText('roadtrip.alt.loading')).toBeInTheDocument()
+ // Just above the dock, in the slot the stage bar used to hold the whole time.
+ expect((bar.parentElement as HTMLElement).className).toContain('bottom-[calc(var(--bottom-nav-h,84px)+4px)]')
+ expect(screen.queryByText('roadtrip.poi.title')).toBeNull()
+ open.unmount()
+
+ // Closed, that slot is empty and the map has it back: the wrapper is mounted with the
+ // bar rather than left lying over the map's own buttons.
+ const { container } = renderTab(planner(), shell)
+ expect(screen.queryByRole('region', { name: 'roadtrip.alt.title' })).toBeNull()
+ expect(container.querySelector('[class*="bottom-[calc(var(--bottom-nav-h"]')).toBeNull()
+ expect(screen.getByText('roadtrip.poi.title')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTTAB-049: offline the leg buttons stay where they are and do nothing', () => {
+ const base = buildPlanner()
+ const p = planner({ roadtripVias: { ...base.roadtripVias, editable: false } })
+ renderTab(p)
+
+ expect(askButtons()).toHaveLength(2)
+ for (const button of askButtons()) expect(button).toBeDisabled()
+ fireEvent.click(askButtons()[0])
+ expect(p.askRouteAlternatives).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-RTTAB-050: a picker left open on another stage is closed, and one on this stage survives the list', () => {
+ const elsewhere = withPicker({ dayId: 1 })
+ const first = renderTab(elsewhere)
+ expect(elsewhere.routeAlternatives.close).toHaveBeenCalledTimes(1)
+ first.unmount()
+
+ // The chain is a look back at the stage, not a way out of the question.
+ const here = withPicker({ dayId: 2, index: 1 })
+ renderTab(here)
+ expect(here.routeAlternatives.close).not.toHaveBeenCalled()
+ expect(askButtons()[1]).toHaveAttribute('aria-pressed', 'true')
+ })
+ })
+
+ describe('day swipe', () => {
+ it('FE-MOB-RTTAB-027: steps the stage without refitting the map, and announces the day it landed on', () => {
+ const p = planner()
+ renderTab(p)
+
+ mocks.swipe.onSelectDay(1)
+
+ // The second argument is skipFit: the map stays where it is, the stage's own
+ // focus points frame it.
+ expect(p.handleSelectDay).toHaveBeenCalledWith(1, true)
+ expect(mocks.swipe.describeDay(0, 2)).toBe('mobileTrip.dayAnnounce:1,2')
+ })
+ })
+})
diff --git a/client/tests/unit/mobile/trip/MRtAlternativesBar.test.tsx b/client/tests/unit/mobile/trip/MRtAlternativesBar.test.tsx
new file mode 100644
index 000000000..3d8509e50
--- /dev/null
+++ b/client/tests/unit/mobile/trip/MRtAlternativesBar.test.tsx
@@ -0,0 +1,204 @@
+import { describe, expect, it, vi } from 'vitest'
+import { act, fireEvent, render, screen, within } from '../../../helpers/render'
+import { buildPlanner, buildShell } from '../../../helpers/mobileTrip'
+import MRtAlternativesBar from '../../../../src/mobile/screens/trip/roadtrip/MRtAlternativesBar'
+import { RT_ALT_BAR_HEIGHT, useMRtAlternatives } from '../../../../src/mobile/screens/trip/roadtrip/useMRtAlternatives'
+import { buildAlternativeOverlays } from '../../../../src/components/Roadtrip/alternativeOverlays'
+import type { LegAlternatives, OfferedRoute } from '../../../../src/components/Roadtrip/useRouteAlternatives'
+import type { TripPlanner } from '../../../../src/mobile/screens/trip/MTripShell'
+
+// FE-MOB-RTALT-001 to FE-MOB-RTALT-011
+//
+// Rendered through the real controller hook, so a tap is checked all the way to what the
+// planner is asked to do, and the pending state is the transition's own.
+
+/**
+ * Three ways of driving one leg: the road already driven, a slower offer, and a road
+ * without the motorway that the avoidance router priced.
+ */
+const ROUTES: OfferedRoute[] = [
+ { coordinates: [[35.7, 139.8], [35.4, 138.6], [34.98, 135.75]], distance: 210_000, duration: 9_600, divergence: null, current: true },
+ { coordinates: [[35.7, 139.8], [35.9, 138.2], [34.98, 135.75]], distance: 198_000, duration: 10_320, divergence: { lat: 35.9, lng: 138.2 } },
+ { coordinates: [[35.7, 139.8], [35.2, 138.9], [34.98, 135.75]], distance: 236_000, duration: 11_400, divergence: { lat: 35.2, lng: 138.9 }, avoids: 'motorway', engine: 'valhalla' },
+]
+
+function overlays(routes: OfferedRoute[] = ROUTES) {
+ return buildAlternativeOverlays(routes, {
+ fastest: 'Fastest', current: 'Current', noMotorway: 'No motorway', noToll: 'No tolls', noFerry: 'No ferry',
+ })
+}
+
+function planner(open: Partial | null, over: Partial = {}): TripPlanner {
+ const base = buildPlanner()
+ const leg = open ? { dayId: 2, index: 0, routes: ROUTES, loading: false, error: false, ...open } : null
+ return buildPlanner({
+ selectedDayId: 2,
+ routeAlternatives: { ...base.routeAlternatives, open: leg },
+ alternativeOverlays: leg ? overlays(leg.routes) : [],
+ ...over,
+ } as Partial)
+}
+
+function Harness({ planner: p }: { planner: TripPlanner }) {
+ const alts = useMRtAlternatives(p, buildShell({ rtView: 'map' }))
+ return
+}
+
+function renderBar(p: TripPlanner) {
+ return { planner: p, ...render() }
+}
+
+const confirmButton = () => screen.getByRole('button', { name: 'common.confirm' })
+const chips = () => screen.queryAllByRole('button', { pressed: false }).concat(screen.queryAllByRole('button', { pressed: true }))
+
+describe('MRtAlternativesBar', () => {
+ it('FE-MOB-RTALT-001: while the router is asked it says so, offers nothing and confirms nothing', () => {
+ renderBar(planner({ loading: true, routes: [] }))
+
+ const bar = screen.getByRole('region', { name: 'roadtrip.alt.title' })
+ expect(within(bar).getByRole('status')).toHaveTextContent('roadtrip.alt.loading')
+ expect(chips()).toHaveLength(0)
+ expect(confirmButton()).toBeDisabled()
+ })
+
+ it('FE-MOB-RTALT-002: a router that did not answer is a failure, never a leg with one way', () => {
+ renderBar(planner({ error: true, routes: [] }))
+
+ expect(screen.getByRole('status')).toHaveTextContent('roadtrip.alt.failed')
+ expect(screen.queryByText('roadtrip.alt.onlyOne')).toBeNull()
+ expect(chips()).toHaveLength(0)
+ expect(confirmButton()).toBeDisabled()
+ })
+
+ it('FE-MOB-RTALT-003: one road back is the only sensible way, with nothing to pick', () => {
+ renderBar(planner({ routes: [ROUTES[0]] }))
+
+ expect(screen.getByRole('status')).toHaveTextContent('roadtrip.alt.onlyOne')
+ expect(chips()).toHaveLength(0)
+ expect(confirmButton()).toBeDisabled()
+ })
+
+ it('FE-MOB-RTALT-004: one chip per road, its drive time first, then its length and what sets it apart', () => {
+ const p = planner({})
+ renderBar(p)
+
+ const offered = chips()
+ expect(offered).toHaveLength(3)
+ const [driven, slower, noMotorway] = p.alternativeOverlays
+
+ const second = screen.getByRole('button', { name: `${slower.label}, 198 km, roadtrip.alt.slower:12 min` })
+ // The time pill's text leads, because that text is what ties the chip to its line.
+ expect(second.textContent).toBe(`${slower.label}198 kmroadtrip.alt.slower:12 min`)
+ // The length is a figure in a badge, in its unit's own case.
+ const badge = within(second).getByText('198 km')
+ expect(badge.className).toContain('rounded-full')
+ expect(badge.className).not.toContain('uppercase')
+ // The swatch is painted in the very colour the road is drawn in.
+ const swatch = second.querySelector('[aria-hidden="true"]') as HTMLElement
+ expect(swatch).toHaveStyle({ background: slower.color })
+
+ // Its own note wins over the difference: the road driven, the road without the motorway.
+ expect(screen.getByRole('button', { name: `${driven.label}, 210 km, Current` })).toHaveAttribute('aria-pressed', 'false')
+ expect(screen.getByRole('button', { name: `${noMotorway.label}, 236 km, No motorway` })).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTALT-005: a tap on a chip lights its road and writes nothing', () => {
+ const p = planner({})
+ renderBar(p)
+
+ fireEvent.click(chips()[1])
+
+ expect(p.setHighlightedAlternative).toHaveBeenCalledWith(1)
+ expect(p.chooseRouteAlternative).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-RTALT-006: confirm waits for a road other than the one driven, then takes it once', async () => {
+ const none = renderBar(planner({}))
+ expect(confirmButton()).toBeDisabled()
+ none.unmount()
+
+ const driven = renderBar(planner({}, { highlightedAlternative: 0 }))
+ expect(screen.getByRole('button', { pressed: true })).toHaveAccessibleName(/Current/)
+ expect(confirmButton()).toBeDisabled()
+ driven.unmount()
+
+ const { planner: p } = renderBar(planner({}, { highlightedAlternative: 1 }))
+ expect(confirmButton()).toBeEnabled()
+ // Awaited so the write the tap starts has landed before the test ends.
+ await act(async () => { fireEvent.click(confirmButton()) })
+ expect(p.chooseRouteAlternative).toHaveBeenCalledTimes(1)
+ expect(p.chooseRouteAlternative).toHaveBeenCalledWith(1)
+ })
+
+ it('FE-MOB-RTALT-007: while the choice is saved nothing can be tapped twice, and it all comes back after', async () => {
+ let land: () => void = () => {}
+ const p = planner({}, {
+ highlightedAlternative: 1,
+ chooseRouteAlternative: vi.fn(() => new Promise(resolve => { land = resolve })),
+ })
+ renderBar(p)
+
+ fireEvent.click(confirmButton())
+
+ const busy = confirmButton()
+ expect(busy).toBeDisabled()
+ expect(busy).toHaveAttribute('aria-busy', 'true')
+ expect(busy.querySelector('.animate-spin')).not.toBeNull()
+ // Still filled: the button is busy with the choice, not unavailable.
+ expect(busy.className).not.toContain('disabled:bg-')
+ for (const chip of chips()) expect(chip).toBeDisabled()
+ fireEvent.click(busy)
+ expect(p.chooseRouteAlternative).toHaveBeenCalledTimes(1)
+
+ await act(async () => { land() })
+
+ expect(confirmButton()).toBeEnabled()
+ expect(confirmButton().querySelector('.animate-spin')).toBeNull()
+ for (const chip of chips()) expect(chip).toBeEnabled()
+ })
+
+ it('FE-MOB-RTALT-008: the close button closes the picker', () => {
+ const p = planner({})
+ renderBar(p)
+
+ fireEvent.click(screen.getByRole('button', { name: 'common.close' }))
+
+ expect(p.routeAlternatives.close).toHaveBeenCalledTimes(1)
+ })
+
+ it('FE-MOB-RTALT-009: a road timed by the other router says so beside the button, and only then', () => {
+ const other = renderBar(planner({}, { highlightedAlternative: 2 }))
+ const note = screen.getByText('roadtrip.alt.otherEngine')
+ expect(note.className).toContain('line-clamp-2')
+ // Beside the button it qualifies, which gives up its full width for the sentence.
+ expect(note.parentElement).toBe(confirmButton().parentElement)
+ expect(confirmButton().className).toContain('flex-none')
+ other.unmount()
+
+ renderBar(planner({}, { highlightedAlternative: 1 }))
+ expect(screen.queryByText('roadtrip.alt.otherEngine')).toBeNull()
+ expect(confirmButton().className).toContain('flex-1')
+ })
+
+ it('FE-MOB-RTALT-010: offline a valid pick still cannot be confirmed', () => {
+ const base = buildPlanner()
+ renderBar(planner({}, { highlightedAlternative: 1, roadtripVias: { ...base.roadtripVias, editable: false } }))
+
+ expect(screen.getByRole('button', { pressed: true })).toBeInTheDocument()
+ expect(confirmButton()).toBeDisabled()
+ })
+
+ it('FE-MOB-RTALT-011: the bar stands at the height the map lifts by, and says nothing once closed', () => {
+ const open = renderBar(planner({}))
+ const bar = screen.getByRole('region', { name: 'roadtrip.alt.title' })
+ expect(bar).toHaveStyle({ height: `${RT_ALT_BAR_HEIGHT}px` })
+ // A fixed height cannot take a second line, so the title truncates rather than wraps.
+ expect(within(bar).getByText('roadtrip.alt.title').className).toContain('truncate')
+ open.unmount()
+
+ // The render the picker closes in: no leg, so no sentence about one.
+ renderBar(planner(null))
+ expect(screen.queryByRole('status')).toBeNull()
+ expect(chips()).toHaveLength(0)
+ })
+})
diff --git a/client/tests/unit/mobile/trip/MRtCorridorBar.test.tsx b/client/tests/unit/mobile/trip/MRtCorridorBar.test.tsx
new file mode 100644
index 000000000..2444098f9
--- /dev/null
+++ b/client/tests/unit/mobile/trip/MRtCorridorBar.test.tsx
@@ -0,0 +1,96 @@
+import { describe, expect, it, vi } from 'vitest'
+import { fireEvent, render, screen } from '../../../helpers/render'
+import { buildPlanner } from '../../../helpers/mobileTrip'
+import MRtCorridorBar from '../../../../src/mobile/screens/trip/roadtrip/MRtCorridorBar'
+import type { MRtCorridorController } from '../../../../src/mobile/screens/trip/roadtrip/useMRtCorridor'
+import type { CorridorPoi } from '../../../../src/components/Roadtrip/useCorridorPois'
+
+// FE-MOB-RTBAR-001 to FE-MOB-RTBAR-009
+
+const hits = (count: number) =>
+ Array.from({ length: count }, (_, i) => ({ osm_id: `h${i}` })) as unknown as CorridorPoi[]
+
+function corridor(over: Partial = {}): MRtCorridorController {
+ return {
+ categories: ['fuel'], toggleCategory: vi.fn(),
+ reach: 'ahead', setReach: vi.fn(), reachKm: 50, anchored: false,
+ run: vi.fn(), clear: vi.fn(), canSearch: true,
+ loading: false, progress: { done: 0, total: 0 }, hits: [], answered: false,
+ offline: false, error: false, capped: false, failedAreas: 0, truncatedAreas: 0,
+ ...over,
+ }
+}
+
+function renderBar(over: Partial = {}) {
+ const c = corridor(over)
+ const onOpen = vi.fn()
+ const view = render()
+ return { ...view, corridor: c, onOpen }
+}
+
+describe('MRtCorridorBar', () => {
+ it('FE-MOB-RTBAR-001: idle it names the question and how far the next search reaches', () => {
+ renderBar()
+
+ expect(screen.getByText('roadtrip.poi.title')).toBeInTheDocument()
+ expect(screen.getByText('mobileTrip.rtReachAhead:50 km')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTBAR-002: a whole-stage search says so instead of quoting a distance', () => {
+ renderBar({ reach: 'stage' })
+
+ expect(screen.getByText('roadtrip.poi.wholeDay')).toBeInTheDocument()
+ expect(screen.queryByText('mobileTrip.rtReachAhead:50 km')).toBeNull()
+ })
+
+ it('FE-MOB-RTBAR-003: idle there is nothing to clear, so no second button', () => {
+ renderBar()
+
+ // The bar is one target until there is an answer or a run to stop. A permanently
+ // present X would be a control that does nothing most of the time.
+ expect(screen.getAllByRole('button')).toHaveLength(1)
+ })
+
+ it('FE-MOB-RTBAR-004: running it counts the boxes and offers to stop', () => {
+ const { corridor: c } = renderBar({ loading: true, progress: { done: 2, total: 5 } })
+
+ expect(screen.getByText('roadtrip.poi.searching:2,5')).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'common.cancel' }))
+ expect(c.clear).toHaveBeenCalledTimes(1)
+ })
+
+ it('FE-MOB-RTBAR-005: answered it counts what is on the way and offers to drop it', () => {
+ const { corridor: c } = renderBar({ answered: true, hits: hits(7) })
+
+ expect(screen.getByText('roadtrip.poi.found:7')).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'roadtrip.poi.clearResults' }))
+ expect(c.clear).toHaveBeenCalledTimes(1)
+ })
+
+ it('FE-MOB-RTBAR-006: an answer of none still counts, rather than looking unasked', () => {
+ renderBar({ answered: true, hits: [] })
+
+ expect(screen.getByText('roadtrip.poi.found:0')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTBAR-007: offline it says why instead of pretending it can search', () => {
+ renderBar({ offline: true, canSearch: false })
+
+ expect(screen.getByText('mobileTrip.rtSearchOffline')).toBeInTheDocument()
+ expect(screen.queryByText('roadtrip.poi.title')).toBeNull()
+ })
+
+ it('FE-MOB-RTBAR-008: the bar itself opens the sheet', () => {
+ const { onOpen } = renderBar()
+
+ fireEvent.click(screen.getByText('roadtrip.poi.title'))
+ expect(onOpen).toHaveBeenCalledTimes(1)
+ })
+ it('FE-MOB-RTBAR-009: a failed search is not a count of nothing', () => {
+ renderBar({ answered: true, error: true, hits: [] })
+
+ expect(screen.getByText('roadtrip.poi.failed')).toBeInTheDocument()
+ // "0 on the way" after a search that never checked reads as an empty stretch of road.
+ expect(screen.queryByText('roadtrip.poi.found:0')).toBeNull()
+ })
+})
diff --git a/client/tests/unit/mobile/trip/MRtCorridorSheet.test.tsx b/client/tests/unit/mobile/trip/MRtCorridorSheet.test.tsx
new file mode 100644
index 000000000..a48bc9eaa
--- /dev/null
+++ b/client/tests/unit/mobile/trip/MRtCorridorSheet.test.tsx
@@ -0,0 +1,188 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { fireEvent, render, screen } from '../../../helpers/render'
+import { buildPlanner, buildShell } from '../../../helpers/mobileTrip'
+import MRtCorridorSheet from '../../../../src/mobile/screens/trip/roadtrip/MRtCorridorSheet'
+import type { MTripShellApi, TripPlanner } from '../../../../src/mobile/screens/trip/MTripShell'
+import type { MRtCorridorController } from '../../../../src/mobile/screens/trip/roadtrip/useMRtCorridor'
+import type { CorridorPoi } from '../../../../src/components/Roadtrip/useCorridorPois'
+
+// FE-MOB-RTSRCH-001 to FE-MOB-RTSRCH-015
+
+// The controller is exercised on its own in useMRtCorridor.test; here the sheet is
+// the unit, so what it reads is handed to it rather than derived from a planner.
+const mocks = vi.hoisted(() => ({ corridor: {} as MRtCorridorController }))
+vi.mock('../../../../src/mobile/screens/trip/roadtrip/useMRtCorridor', () => ({
+ useMRtCorridor: () => mocks.corridor,
+}))
+
+const hit = (over: Partial = {}): CorridorPoi => ({
+ osm_id: 'n1', name: 'Shell Ebina', lat: 35.44, lng: 139.39,
+ category: 'fuel', poi_type: 'amenity=fuel',
+ address: null, website: null, phone: null, opening_hours: null, cuisine: null,
+ source: 'openstreetmap', offRouteKm: 0.4, alongKm: 82,
+ ...over,
+} as unknown as CorridorPoi)
+
+function corridor(over: Partial = {}): MRtCorridorController {
+ return {
+ categories: ['fuel'], toggleCategory: vi.fn(),
+ reach: 'ahead', setReach: vi.fn(), reachKm: 50, anchored: false,
+ run: vi.fn(), clear: vi.fn(), canSearch: true,
+ loading: false, progress: { done: 0, total: 0 }, hits: [], answered: false,
+ offline: false, error: false, capped: false, failedAreas: 0, truncatedAreas: 0,
+ ...over,
+ }
+}
+
+function renderSheet(
+ over: Partial = {},
+ p: Partial = {},
+ shellOver: Partial = {},
+) {
+ mocks.corridor = corridor(over)
+ const planner = buildPlanner({ can: () => true, ...p } as Partial)
+ const shell = buildShell({ sheet: { id: 'rtsearch' }, ...shellOver })
+ const view = render()
+ return { ...view, planner, shell, corridor: mocks.corridor }
+}
+
+beforeEach(() => { mocks.corridor = corridor() })
+
+describe('MRtCorridorSheet', () => {
+ it('FE-MOB-RTSRCH-001: offers every corridor category, with the active ones pressed', () => {
+ renderSheet({ categories: ['fuel', 'charging'] })
+
+ // Several at once, not one at a time: the kinds ride one query per box, so a
+ // second category is free and a picker that forces one is three searches.
+ expect(screen.getByText('roadtrip.poi.fuel')).toBeInTheDocument()
+ expect(screen.getByText('roadtrip.poi.charging')).toBeInTheDocument()
+ expect(screen.getByText('roadtrip.poi.rest')).toBeInTheDocument()
+ expect(screen.getByText('poi.cat.hotels')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSRCH-002: tapping a category toggles it', () => {
+ const { corridor: c } = renderSheet()
+
+ fireEvent.click(screen.getByText('roadtrip.poi.charging'))
+ expect(c.toggleCategory).toHaveBeenCalledWith('charging')
+ })
+
+ it('FE-MOB-RTSRCH-003: the two reaches are the whole of the narrowing', () => {
+ renderSheet()
+
+ expect(screen.getByText('mobileTrip.rtReach')).toBeInTheDocument()
+ expect(screen.getByText('mobileTrip.rtReachAhead:50 km')).toBeInTheDocument()
+ expect(screen.getByText('roadtrip.poi.wholeDay')).toBeInTheDocument()
+ // No corridor width, no section, no plug type, no minimum power: four ways of
+ // narrowing an answer already on screen are a desk activity.
+ expect(screen.queryByText('roadtrip.poi.within')).toBeNull()
+ expect(screen.queryByText('roadtrip.poi.anySocket')).toBeNull()
+ })
+
+ it('FE-MOB-RTSRCH-004: picking a reach goes through the controller', () => {
+ const { corridor: c } = renderSheet()
+
+ fireEvent.click(screen.getByText('roadtrip.poi.wholeDay'))
+ expect(c.setReach).toHaveBeenCalledWith('stage')
+ })
+
+ it('FE-MOB-RTSRCH-005: says where "ahead" starts, because that is what it means', () => {
+ const fromStart = renderSheet()
+ expect(screen.getByText('mobileTrip.rtFromStart')).toBeInTheDocument()
+ fromStart.unmount()
+
+ renderSheet({ anchored: true })
+ expect(screen.getByText('mobileTrip.rtFromNext')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSRCH-006: the search button asks, and counts the boxes while it runs', () => {
+ const idle = renderSheet()
+ fireEvent.click(screen.getByRole('button', { name: /roadtrip.poi.search/ }))
+ expect(idle.corridor.run).toHaveBeenCalledTimes(1)
+ idle.unmount()
+
+ renderSheet({ loading: true, progress: { done: 1, total: 3 } })
+ expect(screen.getByRole('button', { name: /roadtrip.poi.searching:1,3/ })).toBeDisabled()
+ })
+
+ it('FE-MOB-RTSRCH-007: a search nothing can answer is a dead button, so it is disabled', () => {
+ renderSheet({ canSearch: false, categories: [] })
+
+ expect(screen.getByRole('button', { name: /roadtrip.poi.search/ })).toBeDisabled()
+ expect(screen.getByText('roadtrip.poi.empty')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSRCH-008: offline it says so rather than counting an empty answer', () => {
+ renderSheet({ offline: true, canSearch: false, answered: true })
+
+ expect(screen.getByText('mobileTrip.rtSearchOffline')).toBeInTheDocument()
+ expect(screen.queryByText('mobileTrip.rtNoneAhead')).toBeNull()
+ })
+
+ it('FE-MOB-RTSRCH-009: a failed search is not an empty stretch of road', () => {
+ renderSheet({ error: true, answered: true })
+
+ expect(screen.getByText('roadtrip.poi.failed')).toBeInTheDocument()
+ expect(screen.queryByText('mobileTrip.rtNoneAhead')).toBeNull()
+ })
+
+ it('FE-MOB-RTSRCH-010: nothing ahead points at the second tap; nothing on the stage does not', () => {
+ const ahead = renderSheet({ answered: true, hits: [] })
+ expect(screen.getByText('mobileTrip.rtNoneAhead')).toBeInTheDocument()
+ ahead.unmount()
+
+ renderSheet({ answered: true, hits: [], reach: 'stage' })
+ expect(screen.getByText('mobileTrip.rtNoneOnStage')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSRCH-011: says what the search could not cover, so a short list is not read as a complete one', () => {
+ renderSheet({ answered: true, hits: [hit()], capped: true, failedAreas: 2, truncatedAreas: 1 })
+
+ expect(screen.getByText('roadtrip.poi.capped')).toBeInTheDocument()
+ expect(screen.getByText('roadtrip.poi.partial:2')).toBeInTheDocument()
+ // The phone's own wording: the desk's ends in "narrow the corridor", and the
+ // corridor width is a control this screen does not have.
+ expect(screen.getByText('mobileTrip.rtTruncated:1')).toBeInTheDocument()
+ expect(screen.queryByText('roadtrip.poi.truncated:1')).toBeNull()
+ })
+
+ it('FE-MOB-RTSRCH-012: a hit says what it is and where on the drive it sits', () => {
+ renderSheet({ answered: true, hits: [hit()] })
+
+ expect(screen.getByText('Shell Ebina')).toBeInTheDocument()
+ expect(screen.getByText('roadtrip.poi.alongRoute:82 km · roadtrip.poi.offRoute:400 m')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSRCH-013: tapping a hit shows it on the map, which means closing and switching', () => {
+ const { planner, shell } = renderSheet({ answered: true, hits: [hit()] })
+
+ fireEvent.click(screen.getByText('Shell Ebina'))
+
+ expect(shell.closeSheet).toHaveBeenCalledTimes(1)
+ expect(planner.focusRoadtripPoint).toHaveBeenCalledWith(35.44, 139.39)
+ expect(shell.toggleRtView).toHaveBeenCalledTimes(1)
+ })
+
+ it('FE-MOB-RTSRCH-014: adding a hit goes through the road trip door, and never without permission', () => {
+ const allowed = renderSheet({ answered: true, hits: [hit()] })
+ fireEvent.click(screen.getByRole('button', { name: 'roadtrip.poi.add' }))
+ // The planner's own handler: it reads the distance the hit carries and sends it to
+ // the draft sheet with the stop kind and the position in the chain worked out.
+ expect(allowed.planner.handlePoiClick).toHaveBeenCalledWith(expect.objectContaining({ osm_id: 'n1' }))
+ expect(allowed.shell.closeSheet).toHaveBeenCalledTimes(1)
+ allowed.unmount()
+
+ renderSheet({ answered: true, hits: [hit()] }, { can: () => false })
+ expect(screen.queryByRole('button', { name: 'roadtrip.poi.add' })).toBeNull()
+ })
+ it('FE-MOB-RTSRCH-015: a very long answer stops at sixty rows and says how many there were', () => {
+ const many = Array.from({ length: 84 }, (_, i) => hit({ osm_id: `n${i}`, name: `Stop ${i}` }))
+ renderSheet({ answered: true, hits: many })
+
+ expect(screen.getByText('Stop 59')).toBeInTheDocument()
+ expect(screen.queryByText('Stop 60')).toBeNull()
+ // Silently cutting the list would read as the whole answer; the rest are pins on
+ // the map behind this sheet.
+ expect(screen.getByText('roadtrip.poi.foundFiltered:60,84')).toBeInTheDocument()
+ })
+})
diff --git a/client/tests/unit/mobile/trip/MRtDraftSheet.test.tsx b/client/tests/unit/mobile/trip/MRtDraftSheet.test.tsx
new file mode 100644
index 000000000..747586673
--- /dev/null
+++ b/client/tests/unit/mobile/trip/MRtDraftSheet.test.tsx
@@ -0,0 +1,172 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import MRtDraftSheet from '../../../../src/mobile/screens/trip/roadtrip/MRtDraftSheet'
+import type { TripPlanner } from '../../../../src/mobile/screens/trip/MTripShell'
+import type { RoadtripStopDraft } from '../../../../src/components/Roadtrip/RoadtripStopPopup'
+import { buildPlanner } from '../../../helpers/mobileTrip'
+import { resetAllStores } from '../../../helpers/store'
+import { fireEvent, render, screen, waitFor } from '../../../helpers/render'
+
+// FE-MOB-RTDRAFT-001 to FE-MOB-RTDRAFT-015
+//
+// The sheet takes its copy from `planner.t`, which the fixture echoes, so the
+// assertions are on keys rather than on the English wording. Durations come out
+// of formatDurationShort and are real text.
+
+function draftOf(category: string, over: Partial = {}): RoadtripStopDraft {
+ return {
+ poi: {
+ osm_id: `node/${category}`,
+ name: 'Aral Dammtor',
+ lat: 53.5,
+ lng: 9.9,
+ category,
+ poi_type: category,
+ address: 'B4, Hamburg',
+ website: null,
+ phone: null,
+ opening_hours: null,
+ cuisine: null,
+ offRouteKm: 0.2,
+ alongKm: 43,
+ },
+ dayId: 11,
+ dayNumber: 1,
+ position: 2,
+ ...over,
+ } as RoadtripStopDraft
+}
+
+function renderSheet(overrides: Record = {}) {
+ const planner = buildPlanner({
+ stopDraft: draftOf('fuel'),
+ setStopDraft: vi.fn(),
+ saveStopDraft: vi.fn(async () => undefined),
+ stopDraftDuplicate: null,
+ ...overrides,
+ } as unknown as Partial)
+ render()
+ return { planner }
+}
+
+const kind = (key: string) => screen.getByRole('button', { name: `roadtrip.poi.${key}` })
+const dwell = (label: string) => screen.getByRole('button', { name: label })
+const isActive = (el: HTMLElement) => el.classList.contains('bg-m-act')
+
+describe('MRtDraftSheet', () => {
+ beforeEach(() => {
+ resetAllStores()
+ })
+
+ it('FE-MOB-RTDRAFT-001: renders nothing while no draft is in play', () => {
+ renderSheet({ stopDraft: null })
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTDRAFT-002: opens as soon as the planner carries a draft, whoever set it', () => {
+ renderSheet()
+ expect(screen.getByRole('dialog', { name: 'Aral Dammtor' })).toBeInTheDocument()
+ expect(screen.getByText('B4, Hamburg')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTDRAFT-003: says which day and which position the stop lands on, counted from one', () => {
+ renderSheet()
+ expect(screen.getByText('roadtrip.stop.landsOn:1,3')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTDRAFT-004: preselects the kind from the hit and the stay from that kind', () => {
+ renderSheet()
+ expect(isActive(kind('fuel'))).toBe(true)
+ expect(isActive(dwell('10 min'))).toBe(true)
+ })
+
+ it('FE-MOB-RTDRAFT-005: a charging hit is a charge, not a fuel stop, and takes its own half hour', () => {
+ renderSheet({ stopDraft: draftOf('charging') })
+ expect(isActive(kind('charging'))).toBe(true)
+ expect(isActive(dwell('30 min'))).toBe(true)
+ })
+
+ it('FE-MOB-RTDRAFT-006: an unknown category leaves the kind open and falls back to 30 minutes', () => {
+ renderSheet({ stopDraft: draftOf('pharmacy') })
+ for (const key of ['fuel', 'charging', 'rest', 'food', 'sights']) {
+ expect(isActive(kind(key))).toBe(false)
+ }
+ expect(isActive(dwell('30 min'))).toBe(true)
+ })
+
+ it('FE-MOB-RTDRAFT-007: changing the kind pulls its usual length along', () => {
+ renderSheet()
+ fireEvent.click(kind('rest'))
+ expect(isActive(kind('rest'))).toBe(true)
+ expect(isActive(dwell('20 min'))).toBe(true)
+ expect(isActive(dwell('10 min'))).toBe(false)
+ })
+
+ it('FE-MOB-RTDRAFT-008: tapping the kind already chosen leaves a hand-set length standing', () => {
+ renderSheet()
+ fireEvent.click(kind('charging'))
+ expect(isActive(dwell('30 min'))).toBe(true)
+ fireEvent.click(dwell('45 min'))
+ fireEvent.click(kind('charging'))
+ expect(isActive(dwell('45 min'))).toBe(true)
+ expect(isActive(dwell('30 min'))).toBe(false)
+ })
+
+ it('FE-MOB-RTDRAFT-009: saving hands the kind and the length to the planner', async () => {
+ const { planner } = renderSheet()
+ fireEvent.click(kind('charging'))
+ fireEvent.click(dwell('45 min'))
+ fireEvent.click(screen.getByRole('button', { name: 'roadtrip.poi.add' }))
+ await waitFor(() => expect(planner.saveStopDraft).toHaveBeenCalledWith({ stopType: 'charging', dwellMinutes: 45 }))
+ })
+
+ it('FE-MOB-RTDRAFT-010: an edit answers with what the stop already says, and saves rather than adds', async () => {
+ const { planner } = renderSheet({
+ stopDraft: draftOf('fuel', { editing: { placeId: 908, dwellMinutes: 20, stopType: 'rest_area' } }),
+ })
+ expect(isActive(kind('rest'))).toBe(true)
+ expect(isActive(dwell('20 min'))).toBe(true)
+ expect(screen.queryByRole('button', { name: 'roadtrip.poi.add' })).not.toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'common.save' }))
+ await waitFor(() => expect(planner.saveStopDraft).toHaveBeenCalledWith({ stopType: 'rest_area', dwellMinutes: 20 }))
+ })
+
+ it('FE-MOB-RTDRAFT-011: warns about a stop this trip already has', () => {
+ renderSheet({ stopDraftDuplicate: 'Aral A1' })
+ expect(screen.getByText('roadtrip.stop.duplicate:Aral A1')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTDRAFT-012: a hotel is a night, so it points at the desktop and offers no save', () => {
+ renderSheet({ stopDraft: draftOf('hotel') })
+ expect(screen.getByText('mobileTrip.rtNightDesktopOnly')).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'roadtrip.poi.add' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'common.save' })).not.toBeInTheDocument()
+ // Only the way out and the way to drop it.
+ expect(screen.getAllByRole('button')).toHaveLength(2)
+ expect(screen.getByRole('button', { name: 'common.close' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'common.discard' })).toBeInTheDocument()
+ // Neither question is asked, because neither answer could be written.
+ expect(screen.queryByText('roadtrip.stop.kind')).not.toBeInTheDocument()
+ expect(screen.queryByText('roadtrip.stop.stay')).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTDRAFT-013: a campsite is treated the same way, because a night can be booked there too', () => {
+ renderSheet({ stopDraft: draftOf('campsite') })
+ expect(screen.getByText('mobileTrip.rtNightDesktopOnly')).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'roadtrip.poi.add' })).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTDRAFT-014: a draft that already carries an overnight offer is night-only whatever its category', () => {
+ renderSheet({
+ stopDraft: draftOf('fuel', { overnight: { days: [{ id: 11, number: 1, date: '2026-05-01' }], defaultEndDayId: 12 } }),
+ })
+ expect(screen.getByText('mobileTrip.rtNightDesktopOnly')).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'roadtrip.poi.add' })).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTDRAFT-015: discarding clears the draft and writes nothing', () => {
+ const { planner } = renderSheet()
+ fireEvent.click(screen.getByRole('button', { name: 'common.discard' }))
+ expect(planner.setStopDraft).toHaveBeenCalledWith(null)
+ expect(planner.saveStopDraft).not.toHaveBeenCalled()
+ })
+})
diff --git a/client/tests/unit/mobile/trip/MRtInfoSheet.test.tsx b/client/tests/unit/mobile/trip/MRtInfoSheet.test.tsx
new file mode 100644
index 000000000..0c2b3c133
--- /dev/null
+++ b/client/tests/unit/mobile/trip/MRtInfoSheet.test.tsx
@@ -0,0 +1,168 @@
+import { beforeEach, describe, expect, it } from 'vitest'
+import MRtInfoSheet from '../../../../src/mobile/screens/trip/roadtrip/MRtInfoSheet'
+import type { MTripShellApi, TripPlanner } from '../../../../src/mobile/screens/trip/MTripShell'
+import { useAuthStore } from '../../../../src/store/authStore'
+import { useSettingsStore } from '../../../../src/store/settingsStore'
+import { useRoadtripPreferencesStore } from '../../../../src/store/roadtripPreferencesStore'
+import type { RoadtripPreferences } from '@trek/shared'
+import { buildPlanner, buildShell } from '../../../helpers/mobileTrip'
+import { resetAllStores, seedStore } from '../../../helpers/store'
+import { render, screen } from '../../../helpers/render'
+
+// FE-MOB-RTINFO-001 to FE-MOB-RTINFO-015
+//
+// The sheet renders inside the real TranslationProvider, so the copy is asserted
+// in English. Everything it shows comes out of the roadtrip preferences store,
+// which is keyed by ":".
+
+const USER_ID = 7
+const TRIP_ID = 4
+
+/** An electric car with every limit filled in, so each row has a value to show. */
+const FULL: RoadtripPreferences = {
+ roadtrip_vehicle: 'electric',
+ roadtrip_battery_kwh: 77,
+ roadtrip_kwh_per_100: 18,
+ roadtrip_battery_degradation: 8,
+ roadtrip_fill_percent: 80,
+ roadtrip_leg_minutes: 240,
+ roadtrip_day_minutes: 480,
+ roadtrip_day_start: '08:00',
+ roadtrip_day_end: '19:00',
+ roadtrip_avoid: 'toll,ferry',
+}
+
+function seedPreferences(preferences: RoadtripPreferences): void {
+ useRoadtripPreferencesStore.setState({ byTrip: { [`${USER_ID}:${TRIP_ID}`]: preferences } })
+}
+
+function renderSheet(preferences: RoadtripPreferences = FULL, shellOverrides: Record = {}) {
+ seedPreferences(preferences)
+ const planner = buildPlanner({ tripId: TRIP_ID } as unknown as Partial)
+ const shell = buildShell({ sheet: { id: 'rtinfo' }, ...shellOverrides } as unknown as Partial)
+ render()
+ return { planner, shell }
+}
+
+/** The value cell of one limit row, found through its label. */
+function limitValue(label: string): string {
+ const row = screen.getByText(label).parentElement
+ return row?.lastElementChild?.textContent ?? ''
+}
+
+describe('MRtInfoSheet', () => {
+ beforeEach(() => {
+ resetAllStores()
+ useRoadtripPreferencesStore.setState({ byTrip: {} })
+ seedStore(useAuthStore, { user: { id: USER_ID } as never })
+ })
+
+ it('FE-MOB-RTINFO-001: stays closed while another sheet id is active', () => {
+ renderSheet(FULL, { sheet: { id: 'rtstop' } })
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTINFO-002: opens as the driving figures of the trip', () => {
+ renderSheet()
+ expect(screen.getByRole('dialog', { name: 'Driving figures' })).toBeInTheDocument()
+ expect(screen.getByText('Vehicle')).toBeInTheDocument()
+ expect(screen.getByText('Driving settings')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTINFO-003: shows the range the stage plans with, worked out from the battery', () => {
+ renderSheet()
+ // 77 kWh less 8 % wear, at 18 kWh/100 km.
+ expect(screen.getByText('394')).toBeInTheDocument()
+ expect(screen.getByText('km')).toBeInTheDocument()
+ expect(screen.getByText('per charge')).toBeInTheDocument()
+ expect(screen.getByRole('img', { name: '394 km per charge' })).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTINFO-004: explains the fill, the block size and the battery wear under the bar', () => {
+ renderSheet()
+ expect(screen.getByText('A 80 % stop gives 315.2 km · One block = 50 km · 8 % lost to age')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTINFO-005: reads the range in miles on an imperial account', () => {
+ seedStore(useSettingsStore, { settings: { ...useSettingsStore.getState().settings, distance_unit: 'imperial' } })
+ renderSheet()
+ expect(screen.getByText('244.8')).toBeInTheDocument()
+ expect(screen.getByText('mi')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTINFO-006: prints every limit as its own value', () => {
+ renderSheet()
+ expect(limitValue('Longest drive at once')).toBe('4 h')
+ expect(limitValue('Driving per day')).toBe('8 h')
+ expect(limitValue('Daily travel times')).toBe('08:00 · 19:00')
+ expect(limitValue('Fill up to')).toBe('80 %')
+ expect(limitValue('Avoid where possible')).toBe('2 avoided')
+ })
+
+ it('FE-MOB-RTINFO-007: an unset limit reads "off" rather than zero', () => {
+ renderSheet({})
+ expect(limitValue('Longest drive at once')).toBe('off')
+ expect(limitValue('Driving per day')).toBe('off')
+ expect(limitValue('Daily travel times')).toBe('off')
+ expect(limitValue('Avoid where possible')).toBe('off')
+ expect(screen.queryByText('0')).not.toBeInTheDocument()
+ expect(screen.queryByText('0 min')).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTINFO-008: an unset fill reads "full", because not saying means filling right up', () => {
+ renderSheet({})
+ expect(limitValue('Fill up to')).toBe('full')
+ expect(screen.queryByText('100 %')).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTINFO-009: with no range the figure is a dash and the hint says where to set one', () => {
+ renderSheet({})
+ expect(screen.getByText('-')).toBeInTheDocument()
+ expect(screen.getByRole('img', { name: 'No range set' })).toBeInTheDocument()
+ expect(screen.getByText('Type a range, or fill in the figures below and TREK works it out.')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTINFO-010: a half-set day window counts as no window at all', () => {
+ renderSheet({ ...FULL, roadtrip_day_end: '' })
+ expect(limitValue('Daily travel times')).toBe('off')
+ })
+
+ it('FE-MOB-RTINFO-011: stored avoidance reads "off" when no second routing engine can honour it', () => {
+ // A self-hosted router and no Valhalla: the classes are stored but nothing applies them.
+ seedStore(useSettingsStore, {
+ settings: { ...useSettingsStore.getState().settings, routing_base_url: 'https://osrm.example', valhalla_base_url: '' },
+ })
+ renderSheet()
+ expect(limitValue('Avoid where possible')).toBe('off')
+ })
+
+ it('FE-MOB-RTINFO-012: carries no control of any kind, only the way out', () => {
+ renderSheet()
+ const dialog = screen.getByRole('dialog', { name: 'Driving figures' })
+ expect(screen.getAllByRole('button')).toHaveLength(1)
+ expect(screen.getByRole('button', { name: 'Close' })).toBeInTheDocument()
+ expect(dialog.querySelectorAll('input, select, textarea')).toHaveLength(0)
+ for (const role of ['textbox', 'spinbutton', 'slider', 'switch', 'checkbox', 'combobox', 'radio'] as const) {
+ expect(screen.queryByRole(role)).not.toBeInTheDocument()
+ }
+ })
+
+ it('FE-MOB-RTINFO-013: closes with the footnote that names the desktop as the place to change them', () => {
+ renderSheet()
+ expect(screen.getByText(/These figures are set on the desktop/)).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTINFO-014: a combustion car reads per tank, out of tank size and consumption', () => {
+ renderSheet({ roadtrip_vehicle: 'combustion', roadtrip_tank_litres: 60, roadtrip_litres_per_100: 7 })
+ // 60 litres at 7 L/100 km, with no battery wear to take off it.
+ expect(screen.getByRole('img', { name: '857 km per tank' })).toBeInTheDocument()
+ expect(screen.getByText('One block = 50 km')).toBeInTheDocument()
+ expect(screen.queryByText(/lost to age/)).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTINFO-015: a range too long to count in blocks gets a solid bar and no note', () => {
+ renderSheet({ roadtrip_range_km: 2000 })
+ expect(screen.getByRole('img', { name: '2000 km per tank' })).toBeInTheDocument()
+ expect(screen.queryByText(/One block/)).not.toBeInTheDocument()
+ })
+})
diff --git a/client/tests/unit/mobile/trip/MRtKindSheet.test.tsx b/client/tests/unit/mobile/trip/MRtKindSheet.test.tsx
new file mode 100644
index 000000000..b76a87e41
--- /dev/null
+++ b/client/tests/unit/mobile/trip/MRtKindSheet.test.tsx
@@ -0,0 +1,122 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import MRtKindSheet from '../../../../src/mobile/screens/trip/roadtrip/MRtKindSheet'
+import type { MTripShellApi, TripPlanner } from '../../../../src/mobile/screens/trip/MTripShell'
+import { buildPlanner, buildShell } from '../../../helpers/mobileTrip'
+import { resetAllStores } from '../../../helpers/store'
+import { fireEvent, render, screen, waitFor } from '../../../helpers/render'
+
+// FE-MOB-RTKIND-001 to FE-MOB-RTKIND-008
+//
+// The sheet renders inside the real TranslationProvider, so the copy is asserted in
+// English. It writes through the very call the desktop rail makes, so what these hold is
+// the phone's half: which stop, which kind, and that a second tap undoes it.
+
+function makePlanner(overrides: Record = {}) {
+ return buildPlanner({
+ tripId: 4,
+ setRoadtripStopKind: vi.fn(async () => undefined),
+ ...overrides,
+ } as unknown as Partial)
+}
+
+function makeShell(overrides: Record = {}) {
+ return buildShell({
+ sheet: { id: 'rtkind', payload: { placeId: 202, stopType: null, name: 'Bremen Marktplatz' } },
+ ...overrides,
+ } as unknown as Partial)
+}
+
+function renderSheet(plannerOverrides: Record = {}, shellOverrides: Record = {}) {
+ const planner = makePlanner(plannerOverrides)
+ const shell = makeShell(shellOverrides)
+ render()
+ return { planner, shell }
+}
+
+describe('MRtKindSheet', () => {
+ beforeEach(() => {
+ resetAllStores()
+ })
+
+ it('FE-MOB-RTKIND-001: stays closed while another sheet id is active', () => {
+ renderSheet({}, { sheet: { id: 'rtstop', payload: { placeId: 202 } } })
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTKIND-002: opens on the stop it was asked about, with every kind offered', () => {
+ renderSheet()
+
+ expect(screen.getByRole('dialog', { name: 'Kind of stop' })).toBeInTheDocument()
+ expect(screen.getByText('Bremen Marktplatz')).toBeInTheDocument()
+ // The seven the desktop palette offers, each named for a screen reader although the
+ // disc itself is the label on screen.
+ for (const name of ['Accommodation', 'Fuel', 'Charging', 'Rest area', 'Campsite', 'Food', 'Sights']) {
+ expect(screen.getByRole('button', { name, pressed: false })).toBeInTheDocument()
+ }
+ })
+
+ it('FE-MOB-RTKIND-003: picking a kind writes it to the place and closes', async () => {
+ const { planner, shell } = renderSheet()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Fuel' }))
+
+ await waitFor(() => expect(planner.setRoadtripStopKind).toHaveBeenCalledWith(202, 'fuel'))
+ await waitFor(() => expect(shell.closeSheet).toHaveBeenCalledTimes(1))
+ })
+
+ it('FE-MOB-RTKIND-004: the kind a stop already is shows as chosen, and tapping it again takes it back', async () => {
+ const { planner } = renderSheet({}, {
+ sheet: { id: 'rtkind', payload: { placeId: 202, stopType: 'fuel', name: 'Bremen Marktplatz' } },
+ })
+
+ expect(screen.getByRole('button', { name: 'Fuel', pressed: true })).toBeInTheDocument()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Fuel' }))
+
+ // Null is what turns a pause back into a destination, and it is the same write.
+ await waitFor(() => expect(planner.setRoadtripStopKind).toHaveBeenCalledWith(202, null))
+ })
+
+ it('FE-MOB-RTKIND-005: the way back is offered only once there is something to undo', async () => {
+ renderSheet()
+ // On a destination it would be a button saying "leave everything as it is".
+ expect(screen.queryByRole('button', { name: 'Back to a destination' })).toBeNull()
+
+ const { planner } = renderSheet({}, {
+ sheet: { id: 'rtkind', payload: { placeId: 202, stopType: 'rest_area', name: 'Bremen Marktplatz' } },
+ })
+
+ fireEvent.click(screen.getAllByRole('button', { name: 'Back to a destination' })[0])
+
+ await waitFor(() => expect(planner.setRoadtripStopKind).toHaveBeenCalledWith(202, null))
+ })
+
+ it('FE-MOB-RTKIND-006: a traveller who may not edit places can open it but change nothing', () => {
+ const { planner } = renderSheet({ can: () => false })
+
+ for (const name of ['Fuel', 'Accommodation']) {
+ expect(screen.getByRole('button', { name })).toBeDisabled()
+ }
+
+ fireEvent.click(screen.getByRole('button', { name: 'Fuel' }))
+ expect(planner.setRoadtripStopKind).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-RTKIND-007: a payload without a place is not a sheet', () => {
+ renderSheet({}, { sheet: { id: 'rtkind', payload: {} } })
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTKIND-008: a failing write leaves the sheet open rather than claiming it saved', async () => {
+ const { shell } = renderSheet({
+ setRoadtripStopKind: vi.fn(async () => { throw new Error('offline') }),
+ })
+
+ fireEvent.click(screen.getByRole('button', { name: 'Fuel' }))
+
+ // The planner's own call reports the failure; what matters here is that the sheet does
+ // not close on a write that never landed.
+ await waitFor(() => expect(screen.getByRole('dialog', { name: 'Kind of stop' })).toBeInTheDocument())
+ expect(shell.closeSheet).not.toHaveBeenCalled()
+ })
+})
diff --git a/client/tests/unit/mobile/trip/MRtStaySheet.test.tsx b/client/tests/unit/mobile/trip/MRtStaySheet.test.tsx
new file mode 100644
index 000000000..0a715913a
--- /dev/null
+++ b/client/tests/unit/mobile/trip/MRtStaySheet.test.tsx
@@ -0,0 +1,214 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import MRtStaySheet from '../../../../src/mobile/screens/trip/roadtrip/MRtStaySheet'
+import type { MTripShellApi, TripPlanner } from '../../../../src/mobile/screens/trip/MTripShell'
+import { useSettingsStore } from '../../../../src/store/settingsStore'
+import type { RoadtripDay } from '@trek/shared/roadtrip'
+import { buildPlanner, buildShell } from '../../../helpers/mobileTrip'
+import { resetAllStores, seedStore } from '../../../helpers/store'
+import { fireEvent, render, screen, waitFor } from '../../../helpers/render'
+
+// FE-MOB-RTSTAY-001 to FE-MOB-RTSTAY-018
+//
+// The sheet renders inside the real TranslationProvider, so the copy is asserted
+// in English.
+
+/** Arrives late in the evening, so a long stay has to carry into the next day. */
+const STAGE = {
+ dayId: 11,
+ dayNumber: 1,
+ date: '2026-05-01',
+ title: null,
+ stops: [
+ { assignmentId: 101, ownerDayId: 11, ownerIndex: 0, placeId: 201, name: 'Hamburg Hafen', lat: 53.54, lng: 9.98, time: null, dwellMinutes: 30, legMode: null, incomingLegMode: null, stopType: null },
+ { assignmentId: 102, ownerDayId: 11, ownerIndex: 1, placeId: 202, name: 'Bremen Marktplatz', lat: 53.07, lng: 8.8, time: null, dwellMinutes: 30, legMode: null, incomingLegMode: null, stopType: null },
+ ],
+ legs: [undefined, undefined],
+ legVias: [[], []],
+ geometry: [],
+ distance: 0,
+ duration: 0,
+ dayWarning: null,
+ schedule: {
+ entries: [
+ { arrival: '09:15', departure: '09:45', anchored: false, dayOffset: 0 },
+ { arrival: '22:30', departure: '23:00', anchored: false, dayOffset: 0 },
+ ],
+ warnings: [],
+ },
+ driveWarnings: [],
+} as unknown as RoadtripDay
+
+function makePlanner(overrides: Record = {}) {
+ return buildPlanner({
+ tripId: 4,
+ selectedDayId: 11,
+ roadtripRoutes: { days: [STAGE] },
+ setRoadtripStay: vi.fn(async () => undefined),
+ ...overrides,
+ } as unknown as Partial)
+}
+
+function makeShell(overrides: Record = {}) {
+ return buildShell({
+ sheet: { id: 'rtstay', payload: { placeId: 202, minutes: 30, name: 'Bremen Marktplatz' } },
+ ...overrides,
+ } as unknown as Partial)
+}
+
+function renderSheet(plannerOverrides: Record = {}, shellOverrides: Record = {}) {
+ const planner = makePlanner(plannerOverrides)
+ const shell = makeShell(shellOverrides)
+ render()
+ return { planner, shell }
+}
+
+const minus = () => screen.getByRole('button', { name: '5 minutes less' })
+const plus = () => screen.getByRole('button', { name: '5 minutes more' })
+const value = () => screen.getByText('Minutes').previousElementSibling
+
+describe('MRtStaySheet', () => {
+ beforeEach(() => {
+ resetAllStores()
+ })
+
+ it('FE-MOB-RTSTAY-001: stays closed while another sheet id is active', () => {
+ renderSheet({}, { sheet: { id: 'rtstop', payload: { placeId: 202, minutes: 30 } } })
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSTAY-002: opens on the stay the place carries, named and scoped', () => {
+ renderSheet()
+ expect(screen.getByRole('dialog', { name: 'Add a stay' })).toBeInTheDocument()
+ expect(screen.getByText('Bremen Marktplatz')).toBeInTheDocument()
+ expect(screen.getByText('The stay belongs to the place, so it counts on every day this stop is planned.')).toBeInTheDocument()
+ expect(value()).toHaveTextContent('30')
+ })
+
+ it('FE-MOB-RTSTAY-003: plus and minus move the value in five-minute steps', () => {
+ renderSheet()
+ fireEvent.click(plus())
+ expect(value()).toHaveTextContent('35')
+ fireEvent.click(plus())
+ expect(value()).toHaveTextContent('40')
+ fireEvent.click(minus())
+ expect(value()).toHaveTextContent('35')
+ })
+
+ it('FE-MOB-RTSTAY-004: minus stops at zero instead of going negative', () => {
+ renderSheet({}, { sheet: { id: 'rtstay', payload: { placeId: 202, minutes: 3, name: 'Bremen Marktplatz' } } })
+ fireEvent.click(minus())
+ expect(value()).toHaveTextContent('0')
+ expect(minus()).toBeDisabled()
+ })
+
+ it('FE-MOB-RTSTAY-005: plus stops at a full day', () => {
+ renderSheet({}, { sheet: { id: 'rtstay', payload: { placeId: 202, minutes: 1438, name: 'Bremen Marktplatz' } } })
+ fireEvent.click(plus())
+ expect(value()).toHaveTextContent('1440')
+ expect(plus()).toBeDisabled()
+ })
+
+ it('FE-MOB-RTSTAY-006: a preset sets the value outright rather than adding to it', () => {
+ renderSheet()
+ fireEvent.click(screen.getByRole('button', { name: '2 h' }))
+ expect(value()).toHaveTextContent('120')
+ fireEvent.click(screen.getByRole('button', { name: '45 min' }))
+ expect(value()).toHaveTextContent('45')
+ })
+
+ it('FE-MOB-RTSTAY-007: previews the new departure as arrival plus the stay', () => {
+ renderSheet({}, { sheet: { id: 'rtstay', payload: { placeId: 201, minutes: 30, name: 'Hamburg Hafen' } } })
+ expect(screen.getByText('09:15')).toBeInTheDocument()
+ expect(screen.getByText('09:45')).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: '1 h' }))
+ expect(screen.getByText('10:15')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSTAY-008: carries the preview into the next day when the stay runs past midnight', () => {
+ renderSheet()
+ // Arrives 22:30; two hours of it land at 00:30 the following day.
+ fireEvent.click(screen.getByRole('button', { name: '2 h' }))
+ expect(screen.getByText('00:30')).toBeInTheDocument()
+ expect(screen.getByText('+1')).toBeInTheDocument()
+ expect(screen.getByText('Next day')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSTAY-009: no carry mark while the departure stays on the same day', () => {
+ renderSheet()
+ fireEvent.click(screen.getByRole('button', { name: '30 min' }))
+ expect(screen.getByText('23:00')).toBeInTheDocument()
+ expect(screen.queryByText('+1')).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSTAY-010: reads the preview clocks in the 12h setting', () => {
+ seedStore(useSettingsStore, { settings: { ...useSettingsStore.getState().settings, time_format: '12h' } })
+ renderSheet({}, { sheet: { id: 'rtstay', payload: { placeId: 201, minutes: 30, name: 'Hamburg Hafen' } } })
+ expect(screen.getByText('9:15 AM')).toBeInTheDocument()
+ expect(screen.getByText('9:45 AM')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSTAY-011: drops the preview when the stop is not on the stage', () => {
+ renderSheet({ selectedDayId: 99 })
+ expect(screen.queryByText('Arrive')).not.toBeInTheDocument()
+ expect(screen.queryByText('Leave')).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSTAY-012: saving writes the place and the minutes, then hands back to the stop', async () => {
+ const { planner, shell } = renderSheet()
+ fireEvent.click(plus())
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))
+ await waitFor(() => expect(planner.setRoadtripStay).toHaveBeenCalledWith(202, 35))
+ expect(shell.openSheet).toHaveBeenCalledWith('rtstop', { placeId: 202, minutes: 35, name: 'Bremen Marktplatz' })
+ })
+
+ it('FE-MOB-RTSTAY-013: clearing the stay is a save of zero, not a second write path', async () => {
+ const { planner, shell } = renderSheet()
+ fireEvent.click(screen.getByRole('button', { name: 'No stay' }))
+ expect(planner.setRoadtripStay).not.toHaveBeenCalled()
+ expect(value()).toHaveTextContent('0')
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))
+ await waitFor(() => expect(planner.setRoadtripStay).toHaveBeenCalledWith(202, 0))
+ expect(shell.openSheet).toHaveBeenCalledWith('rtstop', { placeId: 202, minutes: 0, name: 'Bremen Marktplatz' })
+ })
+
+ it('FE-MOB-RTSTAY-014: closing without saving writes nothing and does not reopen the stop', () => {
+ const { planner, shell } = renderSheet()
+ fireEvent.click(plus())
+ fireEvent.click(screen.getByRole('button', { name: 'Close' }))
+ expect(shell.closeSheet).toHaveBeenCalledTimes(1)
+ expect(planner.setRoadtripStay).not.toHaveBeenCalled()
+ expect(shell.openSheet).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-RTSTAY-015: a failed write puts the stored value back and says so', async () => {
+ const { planner, shell } = renderSheet({
+ setRoadtripStay: vi.fn(async () => { throw new Error('offline') }),
+ })
+ fireEvent.click(screen.getByRole('button', { name: '2 h' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))
+ await waitFor(() => expect(planner.toast.error).toHaveBeenCalledWith('Unknown error'))
+ expect(value()).toHaveTextContent('30')
+ expect(shell.openSheet).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-RTSTAY-016: without place_edit there is nothing to set the stay with', () => {
+ renderSheet({ can: vi.fn(() => false) })
+ expect(minus()).toBeDisabled()
+ expect(plus()).toBeDisabled()
+ expect(screen.queryByRole('button', { name: '2 h' })).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'No stay' })).toBeDisabled()
+ })
+
+ it('FE-MOB-RTSTAY-017: a stop that carries no stay yet opens on zero', () => {
+ renderSheet({}, { sheet: { id: 'rtstay', payload: { placeId: 202, name: 'Bremen Marktplatz' } } })
+ expect(value()).toHaveTextContent('0')
+ expect(minus()).toBeDisabled()
+ })
+
+ it('FE-MOB-RTSTAY-018: a place the stage does not stop at gets no preview either', () => {
+ renderSheet({}, { sheet: { id: 'rtstay', payload: { placeId: 909, minutes: 30, name: 'Elsewhere' } } })
+ expect(screen.getByRole('dialog', { name: 'Add a stay' })).toBeInTheDocument()
+ expect(screen.queryByText('Arrive')).not.toBeInTheDocument()
+ })
+})
diff --git a/client/tests/unit/mobile/trip/MRtStopSheet.test.tsx b/client/tests/unit/mobile/trip/MRtStopSheet.test.tsx
new file mode 100644
index 000000000..c212d565c
--- /dev/null
+++ b/client/tests/unit/mobile/trip/MRtStopSheet.test.tsx
@@ -0,0 +1,481 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import MRtStopSheet from '../../../../src/mobile/screens/trip/roadtrip/MRtStopSheet'
+import type { MTripShellApi, TripPlanner } from '../../../../src/mobile/screens/trip/MTripShell'
+import type { Place } from '../../../../src/types'
+import type { RoadtripDay, RoadtripStop } from '@trek/shared/roadtrip'
+import { buildPlanner, buildShell } from '../../../helpers/mobileTrip'
+import { useTripStore } from '../../../../src/store/tripStore'
+import { resetAllStores, seedStore } from '../../../helpers/store'
+import { fireEvent, render, screen, waitFor } from '../../../helpers/render'
+
+// FE-MOB-RTSTOP-001 to FE-MOB-RTSTOP-035
+//
+// The sheet renders inside the real TranslationProvider, so the copy is asserted
+// in English. `planner.t` from the fixture is never consulted here.
+//
+// The place rows come from the trip store, not from the planner: the sheet reads the
+// unfiltered list, so renderSheet seeds the store and the planner keeps its empty one.
+
+// The charging panel polls a repo of its own every minute; stubbed so the sheet's
+// wiring can be asserted without a live availability lookup in the background.
+vi.mock('../../../../src/components/Roadtrip/ChargingInfo', () => ({
+ default: ({ placeId }: { placeId?: number }) =>
{placeId}
,
+}))
+
+function stop(over: Partial & Pick): RoadtripStop {
+ return {
+ ownerDayId: 11,
+ ownerIndex: 0,
+ lat: 53.55,
+ lng: 9.99,
+ time: null,
+ dwellMinutes: null,
+ legMode: 'driving',
+ incomingLegMode: 'driving',
+ stopType: null,
+ ...over,
+ } as RoadtripStop
+}
+
+/** Stop 1 is pinned, stop 2 is a fuel stop off the road, stop 3 collects three findings. */
+const HAMBURG = stop({ assignmentId: 101, placeId: 201, name: 'Hamburg Hafen', ownerIndex: 0, time: '09:00', dwellMinutes: 60 })
+const ARAL = stop({ assignmentId: 102, placeId: 202, name: 'Aral Dammtor', ownerIndex: 1, stopType: 'fuel', dwellMinutes: 10, offRoadMeters: 450 })
+const BREMEN = stop({ assignmentId: 103, placeId: 203, name: 'Bremen Marktplatz', ownerIndex: 2, dwellMinutes: 90 })
+/** Set off from on day 11, reached on day 12: stored on one card, drawn on the other. */
+const KASSEL = stop({ assignmentId: 104, placeId: 204, name: 'Kassel Rathaus', ownerDayId: 11, ownerIndex: 3 })
+
+const DAY_A = {
+ dayId: 11,
+ dayNumber: 1,
+ date: '2026-05-01',
+ title: null,
+ stops: [HAMBURG, ARAL, BREMEN],
+ legs: [undefined, undefined, undefined],
+ legVias: [[], [], []],
+ geometry: [],
+ distance: 0,
+ duration: 0,
+ dayWarning: null,
+ schedule: {
+ entries: [
+ { arrival: '09:00', departure: '10:00', anchored: true, dayOffset: 0 },
+ { arrival: '11:30', departure: '11:40', anchored: false, dayOffset: 0 },
+ { arrival: '13:05', departure: '14:35', anchored: false, dayOffset: 0 },
+ ],
+ warnings: [{ index: 2, code: 'late', minutes: 25 }],
+ },
+ driveWarnings: [
+ { index: 2, code: 'leg', overMinutes: 40 },
+ { index: 2, code: 'range', sinceKm: 520 },
+ ],
+} as unknown as RoadtripDay
+
+const DAY_B = {
+ dayId: 12,
+ dayNumber: 2,
+ date: '2026-05-02',
+ title: null,
+ stops: [KASSEL],
+ legs: [undefined],
+ legVias: [[]],
+ geometry: [],
+ distance: 0,
+ duration: 0,
+ dayWarning: null,
+ schedule: {
+ entries: [{ arrival: '08:11', departure: '08:41', anchored: false, dayOffset: 0 }],
+ warnings: [{ index: 0, code: 'late', minutes: 12 }],
+ },
+ driveWarnings: [],
+} as unknown as RoadtripDay
+
+const PLACES = [
+ { id: 201, name: 'Hamburg Hafen', lat: 53.54, lng: 9.98, address: 'Bei den St. Pauli-Landungsbrücken' },
+ { id: 203, name: 'Bremen Marktplatz', lat: 53.07, lng: 8.8, address: 'Am Markt' },
+] as unknown as Place[]
+
+function makePlanner(overrides: Record = {}) {
+ return buildPlanner({
+ tripId: 4,
+ dailyTimesActive: true,
+ setRoadtripEndDay: vi.fn(async () => undefined),
+ roadtripRoutes: { days: [DAY_A, DAY_B] },
+ ...overrides,
+ } as unknown as Partial)
+}
+
+function makeShell(overrides: Record = {}) {
+ return buildShell({
+ sheet: { id: 'rtstop', payload: { dayId: 11, assignmentId: 103 } },
+ ...overrides,
+ } as unknown as Partial)
+}
+
+function renderSheet(
+ plannerOverrides: Record = {},
+ shellOverrides: Record = {},
+ storePlaces: Place[] = PLACES,
+) {
+ seedStore(useTripStore, { places: storePlaces })
+ const planner = makePlanner(plannerOverrides)
+ const shell = makeShell(shellOverrides)
+ render()
+ return { planner, shell }
+}
+
+describe('MRtStopSheet', () => {
+ beforeEach(() => {
+ resetAllStores()
+ })
+
+ it('FE-MOB-RTSTOP-001: stays closed while another sheet id is active', () => {
+ renderSheet({}, { sheet: { id: 'rtstay', payload: { dayId: 11, assignmentId: 103 } } })
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSTOP-002: stays closed when no routed day carries the assignment', () => {
+ renderSheet({}, { sheet: { id: 'rtstop', payload: { dayId: 11, assignmentId: 999 } } })
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSTOP-003: shows arrival and departure large, and says the time was set by hand', () => {
+ renderSheet({}, { sheet: { id: 'rtstop', payload: { dayId: 11, assignmentId: 101 } } })
+ expect(screen.getByRole('dialog', { name: 'Hamburg Hafen' })).toBeInTheDocument()
+ expect(screen.getByText('Arrive')).toBeInTheDocument()
+ expect(screen.getByText('09:00')).toBeInTheDocument()
+ expect(screen.getByText('Leave')).toBeInTheDocument()
+ expect(screen.getByText('10:00')).toBeInTheDocument()
+ expect(screen.getByText('Time you set')).toBeInTheDocument()
+ expect(screen.queryByText('Calculated from the drive')).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSTOP-004: says the clock was worked out when the stop is not anchored', () => {
+ renderSheet()
+ expect(screen.getByText('13:05')).toBeInTheDocument()
+ expect(screen.getByText('14:35')).toBeInTheDocument()
+ expect(screen.getByText('Calculated from the drive')).toBeInTheDocument()
+ expect(screen.queryByText('Time you set')).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSTOP-005: lists every finding of the stop, not just the one the chain has room for', () => {
+ renderSheet()
+ // The chain picks 'range' out of the drive warnings and shows nothing else.
+ expect(screen.getByText('Arrives 25 min after the time you set')).toBeInTheDocument()
+ expect(screen.getByText('40 min over your longest drive')).toBeInTheDocument()
+ expect(screen.getByText('520 km since the last fill-up')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSTOP-006: spells out the stay and how far the stop sits off the road', () => {
+ renderSheet({}, { sheet: { id: 'rtstop', payload: { dayId: 11, assignmentId: 102 } } })
+ expect(screen.getByText('450 m from the road')).toBeInTheDocument()
+ expect(screen.getAllByText('10 min').length).toBeGreaterThan(0)
+ })
+
+ it('FE-MOB-RTSTOP-007: finds the stop on the card it is drawn on, not the day it is stored on', () => {
+ // ownerDayId 11 names day A; the stop only exists in day B's chain after a night drive.
+ renderSheet({}, { sheet: { id: 'rtstop', payload: { dayId: 11, assignmentId: 104 } } })
+ expect(screen.getByRole('dialog', { name: 'Kassel Rathaus' })).toBeInTheDocument()
+ // Day B's own schedule and day B's own warning, filed under day B's index.
+ expect(screen.getByText('08:11')).toBeInTheDocument()
+ expect(screen.getByText('Arrives 12 min after the time you set')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSTOP-008: keeps the navigation tile without any write permission', () => {
+ renderSheet({ can: vi.fn(() => false) })
+ expect(screen.getByRole('button', { name: 'Navigation' })).toBeInTheDocument()
+ // The stay tile loses its handler and stays a plain box rather than going dead.
+ expect(screen.queryByRole('button', { name: /^Stay/ })).not.toBeInTheDocument()
+ const stayLabels = screen.getAllByText('Stay')
+ expect(stayLabels).toHaveLength(2)
+ expect(stayLabels[1].closest('button')).toBeNull()
+ })
+
+ it('FE-MOB-RTSTOP-009: offers the map apps built from the stop itself when no place row matches', () => {
+ renderSheet({}, {}, [])
+ fireEvent.click(screen.getByRole('button', { name: 'Navigation' }))
+ expect(screen.getByRole('menu')).toBeInTheDocument()
+ expect(screen.getByRole('menuitem', { name: 'Google Maps' })).toBeInTheDocument()
+ expect(screen.getByRole('menuitem', { name: 'Waze' })).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSTOP-010: has no delete, no reorder and no stop-kind control at all', () => {
+ renderSheet()
+ // Close, edit, navigation, stay, show-on-map, plus the end-day switch, which is a switch.
+ // Edit is a hand-over to the place editor, not a control of this sheet (RTSTOP-030).
+ expect(screen.getAllByRole('button')).toHaveLength(5)
+ expect(screen.getByRole('button', { name: 'Close' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Edit' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Navigation' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: /^Stay/ })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Show on map' })).toBeInTheDocument()
+ expect(screen.getAllByRole('switch')).toHaveLength(1)
+ // The desktop-only copy is absent rather than disabled.
+ expect(screen.queryByText('Remove stop')).not.toBeInTheDocument()
+ expect(screen.queryByText('Kind of stop')).not.toBeInTheDocument()
+ expect(screen.queryByText('Set how full this stop fills')).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSTOP-011: the stay tile hands the stop over to the stay sheet', () => {
+ const { shell } = renderSheet()
+ fireEvent.click(screen.getByRole('button', { name: /^Stay/ }))
+ expect(shell.openSheet).toHaveBeenCalledWith('rtstay', { placeId: 203, minutes: 90 })
+ })
+
+ it('FE-MOB-RTSTOP-012: ending the day here calls the stop-addressed writer with that very stop', async () => {
+ const { planner } = renderSheet()
+ const toggle = screen.getByRole('switch', { name: 'End the day here' })
+ expect(toggle).toHaveAttribute('aria-checked', 'false')
+ fireEvent.click(toggle)
+ expect(planner.setRoadtripEndDay).toHaveBeenCalledWith(BREMEN)
+ // Reads as switched the moment it is tapped, before the write lands.
+ await waitFor(() => expect(toggle).toHaveAttribute('aria-checked', 'true'))
+ })
+
+ it('FE-MOB-RTSTOP-013: rolls the switch back and reports when the write fails', async () => {
+ const { planner } = renderSheet({
+ setRoadtripEndDay: vi.fn(async () => { throw new Error('Day boundary refused') }),
+ })
+ const toggle = screen.getByRole('switch', { name: 'End the day here' })
+ fireEvent.click(toggle)
+ await waitFor(() => expect(planner.toast.error).toHaveBeenCalledWith('Day boundary refused'))
+ expect(toggle).toHaveAttribute('aria-checked', 'false')
+ })
+
+ it('FE-MOB-RTSTOP-014: dropping the day window takes the end-day switch away entirely', () => {
+ renderSheet({ dailyTimesActive: false })
+ expect(screen.queryByRole('switch')).not.toBeInTheDocument()
+ expect(screen.queryByText('End the day here')).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSTOP-015: showing the stop on the map flips the stage over and brings the stop into view', () => {
+ const { planner, shell } = renderSheet({ selectedDayId: 11 }, { rtView: 'list' })
+ fireEvent.click(screen.getByRole('button', { name: 'Show on map' }))
+ expect(shell.toggleRtView).toHaveBeenCalledTimes(1)
+ expect(planner.focusRoadtripPoint).toHaveBeenCalledWith(BREMEN.lat, BREMEN.lng)
+ expect(shell.closeSheet).toHaveBeenCalledTimes(1)
+ // Not the place selection: the place inspector opens off it and would cover the map.
+ expect(planner.setSelectedPlaceId).not.toHaveBeenCalled()
+ // Already the stage on screen, so the day stays put.
+ expect(planner.handleSelectDay).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-RTSTOP-016: leaves the stage alone when the map is already the front layer', () => {
+ const { shell } = renderSheet({}, { rtView: 'map' })
+ fireEvent.click(screen.getByRole('button', { name: 'Show on map' }))
+ expect(shell.toggleRtView).not.toHaveBeenCalled()
+ expect(shell.closeSheet).toHaveBeenCalledTimes(1)
+ })
+
+ it('FE-MOB-RTSTOP-017: the disc counts destinations, so the third stop on the card is number two', () => {
+ // Hamburg is 1, the fuel stop between them takes no number, Bremen is 2.
+ renderSheet()
+ const heading = screen.getByRole('heading', { name: 'Bremen Marktplatz' })
+ expect(heading.previousElementSibling).toHaveTextContent('2')
+ })
+
+ it('FE-MOB-RTSTOP-018: a service stop is drawn by its kind, not by a position in the chain', () => {
+ renderSheet({}, { sheet: { id: 'rtstop', payload: { dayId: 11, assignmentId: 102 } } })
+ const disc = screen.getByRole('heading', { name: 'Aral Dammtor' }).previousElementSibling
+ // The kind's own colour, shared with the map marker, rather than a numbered disc.
+ expect(disc).toHaveStyle({ background: '#E8590C' })
+ expect(disc?.querySelector('svg')).not.toBeNull()
+ expect(disc?.textContent).toBe('')
+ })
+
+ it('FE-MOB-RTSTOP-019: a stop the routing round has no clock for drops the clock card entirely', () => {
+ const day = {
+ ...DAY_A,
+ stops: [BREMEN],
+ schedule: { entries: [], warnings: [] },
+ driveWarnings: [],
+ } as unknown as RoadtripDay
+ renderSheet({ roadtripRoutes: { days: [day] } }, { sheet: { id: 'rtstop', payload: { dayId: 11, assignmentId: 103 } } })
+ expect(screen.queryByText('Arrive')).not.toBeInTheDocument()
+ expect(screen.queryByText('Leave')).not.toBeInTheDocument()
+ expect(screen.queryByText('Calculated from the drive')).not.toBeInTheDocument()
+ // The stay is still filed, so the sheet is not empty.
+ expect(screen.getAllByText('1 h 30 min').length).toBeGreaterThan(0)
+ })
+
+ it('FE-MOB-RTSTOP-020: an arrival without a departure shows one clock, not an empty second one', () => {
+ const day = {
+ ...DAY_A,
+ stops: [HAMBURG],
+ schedule: { entries: [{ arrival: '09:00', departure: null, anchored: false, dayOffset: 0 }], warnings: [] },
+ driveWarnings: [],
+ } as unknown as RoadtripDay
+ renderSheet({ roadtripRoutes: { days: [day] } }, { sheet: { id: 'rtstop', payload: { dayId: 11, assignmentId: 101 } } })
+ expect(screen.getByText('Arrive')).toBeInTheDocument()
+ expect(screen.queryByText('Leave')).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSTOP-021: a stop with no stay says so on the tile and files no stay finding', () => {
+ const day = {
+ ...DAY_A,
+ stops: [{ ...BREMEN, dwellMinutes: null }],
+ schedule: { entries: [{ arrival: '13:05', departure: '13:05', anchored: false, dayOffset: 0 }], warnings: [] },
+ driveWarnings: [],
+ } as unknown as RoadtripDay
+ renderSheet({ roadtripRoutes: { days: [day] } }, { sheet: { id: 'rtstop', payload: { dayId: 11, assignmentId: 103 } } })
+ expect(screen.getByText('No stay')).toBeInTheDocument()
+ expect(screen.getAllByText('Stay')).toHaveLength(1)
+ })
+
+ it('FE-MOB-RTSTOP-022: one map app means no picker, the tap opens it and names it on the tile', () => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(null)
+ // Name only: no coordinates and no address, so only the OSM search link survives.
+ renderSheet({}, {}, [{ id: 203, name: 'Bremen Marktplatz', lat: null, lng: null, address: null }] as unknown as Place[])
+ const tile = screen.getByRole('button', { name: /^Navigation/ })
+ expect(tile).toHaveTextContent('OpenStreetMap')
+ fireEvent.click(tile)
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+ expect(open).toHaveBeenCalledWith(
+ 'https://www.openstreetmap.org/search?query=Bremen%20Marktplatz',
+ '_blank',
+ 'noopener,noreferrer',
+ )
+ open.mockRestore()
+ })
+
+ it('FE-MOB-RTSTOP-023: no reachable map app at all drops the tile instead of leaving a dead one', () => {
+ renderSheet({}, {}, [{ id: 203, name: '', lat: null, lng: null, address: null }] as unknown as Place[])
+ expect(screen.queryByRole('button', { name: /Navigation/ })).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: /^Stay/ })).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSTOP-024: the map-app picker closes again on a tap outside it', () => {
+ renderSheet()
+ fireEvent.click(screen.getByRole('button', { name: 'Navigation' }))
+ expect(screen.getByRole('menu')).toBeInTheDocument()
+ fireEvent.mouseDown(document.body)
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSTOP-025: a payload without an assignment names no stop, so nothing opens', () => {
+ renderSheet({}, { sheet: { id: 'rtstop', payload: {} } })
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSTOP-026: a charger gets the live availability panel, a pump does not', () => {
+ const charger = stop({ assignmentId: 106, placeId: 206, name: 'Ionity Bremen', stopType: 'charging' })
+ const day = {
+ ...DAY_A,
+ stops: [charger],
+ schedule: { entries: [{ arrival: '12:00', departure: '12:30', anchored: false, dayOffset: 0 }], warnings: [] },
+ driveWarnings: [],
+ } as unknown as RoadtripDay
+ renderSheet({ roadtripRoutes: { days: [day] } }, { sheet: { id: 'rtstop', payload: { dayId: 11, assignmentId: 106 } } })
+ expect(screen.getByTestId('charging-info')).toHaveTextContent('206')
+ })
+
+ it('FE-MOB-RTSTOP-027: no availability panel on a stop that is not a charger', () => {
+ renderSheet({}, { sheet: { id: 'rtstop', payload: { dayId: 11, assignmentId: 102 } } })
+ expect(screen.queryByTestId('charging-info')).not.toBeInTheDocument()
+ })
+
+ // jsdom has no layout, so the two header tests pin the class contract rather than pixels.
+ it('FE-MOB-RTSTOP-028: the header centres the name on the disc instead of hanging it from the top', () => {
+ renderSheet()
+ const heading = screen.getByRole('heading', { name: 'Bremen Marktplatz' })
+ const header = heading.parentElement
+ expect(header).toHaveClass('items-center')
+ expect(header).not.toHaveClass('items-start')
+ // Disc, name and buttons are one row, so they share that one cross-axis alignment.
+ expect(heading.previousElementSibling).toHaveTextContent('2')
+ const buttons = heading.nextElementSibling
+ expect(buttons).toHaveClass('items-center')
+ expect(buttons).toContainElement(screen.getByRole('button', { name: 'Close' }))
+ expect(buttons).toContainElement(screen.getByRole('button', { name: 'Edit' }))
+ })
+
+ it('FE-MOB-RTSTOP-029: a service stop with a long name centres the same way and wraps rather than truncating', () => {
+ const longName = 'Aral Tankstelle an der Autobahnausfahrt Hamburg Dammtor Nord'
+ renderSheet(
+ { roadtripRoutes: { days: [{ ...DAY_A, stops: [HAMBURG, { ...ARAL, name: longName }, BREMEN] }, DAY_B] } },
+ { sheet: { id: 'rtstop', payload: { dayId: 11, assignmentId: 102 } } },
+ )
+ const heading = screen.getByRole('heading', { name: longName })
+ expect(heading.parentElement).toHaveClass('items-center')
+ expect(heading).toHaveClass('line-clamp-2')
+ expect(heading).not.toHaveClass('truncate')
+ expect(heading.previousElementSibling?.querySelector('svg')).not.toBeNull()
+ })
+
+ it('FE-MOB-RTSTOP-030: the pencil opens the place editor on this very visit and closes the sheet', () => {
+ const { planner, shell } = renderSheet()
+ const edit = screen.getByRole('button', { name: 'Edit' })
+ // Before the way out, so the close button keeps the corner it has on every sheet.
+ expect(edit.compareDocumentPosition(screen.getByRole('button', { name: 'Close' })) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
+ fireEvent.click(edit)
+ expect(planner.openPlaceEditor).toHaveBeenCalledTimes(1)
+ expect(planner.openPlaceEditor).toHaveBeenCalledWith(expect.objectContaining({ id: 203, address: 'Am Markt' }), 103)
+ expect(shell.closeSheet).toHaveBeenCalledTimes(1)
+ // The stop sheet does not hand over to a stay or a map on the way.
+ expect(shell.openSheet).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-RTSTOP-031: somebody who may not edit places gets no pencil at all', () => {
+ // Every right but place_edit, so it is that one right the pencil answers to.
+ const { planner } = renderSheet({ can: vi.fn((action: string) => action !== 'place_edit') })
+ // Absent rather than disabled, the same rule as every other write on this sheet.
+ expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Close' })).toBeInTheDocument()
+ // The night switch answers to day_edit and stays, so no other right took the pencil away.
+ expect(screen.getByRole('switch', { name: 'End the day here' })).toBeInTheDocument()
+ expect(planner.can).toHaveBeenCalledWith('place_edit', planner.trip)
+ })
+
+ it('FE-MOB-RTSTOP-032: a pump hidden from the day lists is still editable from the stage', () => {
+ // The planner's filtered list lacks the pump, the store still holds it.
+ const pump = { id: 202, name: 'Aral Dammtor', lat: 53.56, lng: 9.99, stop_type: 'fuel' } as unknown as Place
+ const { planner } = renderSheet(
+ { places: PLACES },
+ { sheet: { id: 'rtstop', payload: { dayId: 11, assignmentId: 102 } } },
+ [...PLACES, pump],
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))
+ expect(planner.openPlaceEditor).toHaveBeenCalledWith(expect.objectContaining({ id: 202 }), 102)
+ })
+
+ it('FE-MOB-RTSTOP-033: a stop still being saved under its optimistic id offers no pencil yet', () => {
+ const saving = stop({ assignmentId: -5, placeId: 203, name: 'Bremen Marktplatz', ownerIndex: 0, dwellMinutes: 90 })
+ const day = {
+ ...DAY_A,
+ stops: [saving],
+ schedule: { entries: [{ arrival: '13:05', departure: '14:35', anchored: false, dayOffset: 0 }], warnings: [] },
+ driveWarnings: [],
+ } as unknown as RoadtripDay
+ const { planner } = renderSheet({ roadtripRoutes: { days: [day] } }, { sheet: { id: 'rtstop', payload: { dayId: 11, assignmentId: -5 } } })
+ expect(screen.getByRole('dialog', { name: 'Bremen Marktplatz' })).toBeInTheDocument()
+ // Neither the temporary id nor a null the planner would resolve back to that same row.
+ expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument()
+ expect(planner.openPlaceEditor).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-RTSTOP-034: a stop whose place row is not in the trip store offers no pencil', () => {
+ // The editor needs the whole row; the stop's name and position are enough for directions only.
+ renderSheet({}, {}, [])
+ expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Navigation' })).toBeInTheDocument()
+ })
+
+ it('FE-MOB-RTSTOP-035: a stop drawn on another card makes that card the stage before the camera moves', () => {
+ // Kassel is stored on day 11 and drawn on day 12 after a night drive, while day 11 is on screen.
+ const { planner, shell } = renderSheet(
+ { selectedDayId: 11 },
+ { rtView: 'map', sheet: { id: 'rtstop', payload: { dayId: 11, assignmentId: 104 } } },
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'Show on map' }))
+
+ // The card, not the stored day, and without a refit of its own: the stop is the frame.
+ expect(planner.handleSelectDay).toHaveBeenCalledWith(12, true)
+ expect(planner.focusRoadtripPoint).toHaveBeenCalledWith(KASSEL.lat, KASSEL.lng)
+ // The day first, so the map holds the point to the day it arrives with.
+ const selectDay = vi.mocked(planner.handleSelectDay).mock.invocationCallOrder[0]
+ const focus = vi.mocked(planner.focusRoadtripPoint).mock.invocationCallOrder[0]
+ expect(selectDay).toBeLessThan(focus)
+ expect(shell.toggleRtView).not.toHaveBeenCalled()
+ expect(shell.closeSheet).toHaveBeenCalledTimes(1)
+ expect(planner.setSelectedPlaceId).not.toHaveBeenCalled()
+ })
+})
diff --git a/client/tests/unit/mobile/trip/MTripSheets.test.tsx b/client/tests/unit/mobile/trip/MTripSheets.test.tsx
index a75b4bfdf..164cb638e 100644
--- a/client/tests/unit/mobile/trip/MTripSheets.test.tsx
+++ b/client/tests/unit/mobile/trip/MTripSheets.test.tsx
@@ -11,7 +11,7 @@ import { buildPlanner, buildShell } from '../../../helpers/mobileTrip'
import { resetAllStores, seedStore } from '../../../helpers/store'
import { fireEvent, render, screen, waitFor } from '../../../helpers/render'
-// FE-MOB-SHOST-001 to FE-MOB-SHOST-027
+// FE-MOB-SHOST-001 to FE-MOB-SHOST-028
//
// Every child sheet is stubbed: this file is about the host — which sheet is
// mounted for which shell.sheet id, and how the host's own callbacks wire the
@@ -34,6 +34,10 @@ vi.mock('../../../../src/mobile/screens/trip/sheets/MTransportSheet', () => ({ d
vi.mock('../../../../src/mobile/screens/trip/sheets/MBrowseActionsSheet', () => ({ default: selfRouted('stub-bract') }))
vi.mock('../../../../src/mobile/screens/trip/sheets/MMehrSheet', () => ({ default: selfRouted('stub-mehr') }))
vi.mock('../../../../src/mobile/screens/trip/sheets/MExportSheet', () => ({ default: selfRouted('stub-export') }))
+vi.mock('../../../../src/mobile/screens/trip/roadtrip/MRtCorridorSheet', () => ({ default: selfRouted('stub-rtsearch') }))
+vi.mock('../../../../src/mobile/screens/trip/roadtrip/MRtDraftSheet', () => ({
+ default: ({ planner }: { planner: TripPlanner }) => ,
+}))
vi.mock('../../../../src/mobile/screens/trip/sheets/MNoteSheet', () => ({
default: ({ open, payload, onClose }: { open: boolean; payload?: { dayId?: number }; onClose: () => void }) => (
@@ -432,4 +436,17 @@ describe('MTripSheets', () => {
renderHost({ deletePlaceId: 101, showPlaceForm: true })
expect(screen.queryByTestId('stub-confirm')).not.toBeInTheDocument()
})
+
+ it('FE-MOB-SHOST-028: the search sheet is mounted before the draft it opens', () => {
+ renderHost({}, { sheet: null })
+
+ const order = [...document.querySelectorAll('[data-testid]')]
+ .map(el => el.getAttribute('data-testid'))
+ .filter(id => id === 'stub-rtsearch' || id === 'stub-rtdraft')
+
+ // Both sit at the same z. Portal order is what decides which paints on top, and
+ // taking a hit onto the trip has to open the draft OVER the search it came from.
+ expect(order).toEqual(['stub-rtsearch', 'stub-rtdraft'])
+ })
+
})
diff --git a/client/tests/unit/mobile/trip/MTripShell.test.tsx b/client/tests/unit/mobile/trip/MTripShell.test.tsx
index ff3437c12..96b9893e0 100644
--- a/client/tests/unit/mobile/trip/MTripShell.test.tsx
+++ b/client/tests/unit/mobile/trip/MTripShell.test.tsx
@@ -1,10 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { act, fireEvent, render, screen } from '../../../helpers/render'
+import { act, fireEvent, render, screen, within } from '../../../helpers/render'
import { buildPlanner, buildShell } from '../../../helpers/mobileTrip'
import type { MTripShellApi, TripPlanner } from '../../../../src/mobile/screens/trip/MTripShell'
import type { Day, PackingItem, TodoItem } from '../../../../src/types'
-// FE-MOB-SHELL-001 to FE-MOB-SHELL-051
+// FE-MOB-SHELL-001 to FE-MOB-SHELL-066
const mocks = vi.hoisted(() => ({ planner: {} as TripPlanner }))
@@ -32,6 +32,16 @@ function slot(testId: string) {
}
}
+/**
+ * One identity per slot, created once. Built inside the wrapper's render body instead,
+ * every rerender hands the shell four brand-new component types and React remounts all
+ * of them, which would quietly mask the one thing FE-MOB-SHELL-054 is watching for.
+ */
+const PlanTimelineSlot = slot('plan-timeline')
+const MapAreaSlot = slot('map-area')
+const PlacesBrowserSlot = slot('places-browser')
+const SheetsSlot = slot('sheets')
+
function TabSlot({ shell, tab }: { planner: TripPlanner; shell: MTripShellApi; tab: string }) {
shellApi = shell
return
{tab}
@@ -52,6 +62,33 @@ const DAYS = [
{ id: 12, trip_id: 1, day_number: 2, date: '2026-05-03', title: null },
] as unknown as Day[]
+/**
+ * The same sections with the road trip addon on, in the order the planner hook builds
+ * them, which is NOT the dock's order. The dock seats by its own priority list, so a
+ * fixture that mirrors the hook is the only one that can tell the two apart.
+ */
+const RT_TABS = [
+ { id: 'plan', label: 'Plan' },
+ { id: 'transports', label: 'Transport' },
+ { id: 'buchungen', label: 'Bookings' },
+ { id: 'roadtrip', label: 'Road trip' },
+ { id: 'listen', label: 'Lists' },
+ { id: 'finanzplan', label: 'Budget' },
+ { id: 'dateien', label: 'Files' },
+ { id: 'collab', label: 'Collaboration' },
+]
+
+/** One routed stage, as the addon reports it. */
+const stage = (over: Record = {}) => ({
+ dayId: 11, dayNumber: 1, date: '2026-05-02', title: null, distance: 123000, duration: 5400,
+ stops: [], legs: [], legVias: [], geometry: [], schedule: { entries: [] }, driveWarnings: [],
+ ...over,
+})
+
+/** The dock's seats, in order, plus the More button at the end. */
+const dockLabels = () =>
+ within(screen.getByRole('navigation')).getAllByRole('button').map(b => b.getAttribute('aria-label'))
+
function todayIso(): string {
const now = new Date()
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
@@ -66,11 +103,11 @@ function renderShell(overrides: Partial = {}) {
} as Partial)
const Shell = () => (
)
const view = render()
@@ -573,6 +610,207 @@ describe('MTripShell', () => {
expect(planner.handleSelectDay).not.toHaveBeenCalled()
})
})
+
+ // The road trip tab. The drive is a second reading of the same trip on the same map,
+ // so it does not get a map of its own: the shell's single instance now lies under
+ // BOTH tabs, and everything floating over it keys off `mapFront` rather than off
+ // `view`, which only ever meant the plan tab.
+ describe('the road trip tab', () => {
+ /** Commit a tab change the way the planner would, and redraw. */
+ function goToTab(planner: TripPlanner, rerenderShell: () => void, tabId: string) {
+ ;(planner as { activeTab: string }).activeTab = tabId
+ rerenderShell()
+ }
+
+ const rtSwitch = () => screen.getByRole('button', { name: 'mobileTrip.mapView' })
+ const backToList = () => screen.getByRole('button', { name: 'mobileTrip.listView' })
+
+ it('FE-MOB-SHELL-052: the drive takes the second dock seat and the packing list loses its own', () => {
+ renderShell({ TRIP_TABS: RT_TABS } as Partial)
+ // Second seat, not fourth: the dock orders by its own priority list, so the drive
+ // sits beside the plan however late the hook appends it.
+ expect(dockLabels()).toEqual(['Plan', 'Road trip', 'Transport', 'Bookings', 'Budget', 'mobileTrip.more'])
+ // Six sections would leave 3px between the circles, so the cap cuts the last one
+ // and the More sheet picks it up.
+ expect(screen.queryByRole('button', { name: 'Lists' })).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-SHELL-053: without the addon the dock is exactly what it was', () => {
+ renderShell()
+ expect(dockLabels()).toEqual(['Plan', 'Transport', 'Bookings', 'Budget', 'Lists', 'mobileTrip.more'])
+ })
+
+ it('FE-MOB-SHELL-054: the map survives the move between the plan tab and the drive', () => {
+ const { planner, rerenderShell } = renderShell({ TRIP_TABS: RT_TABS } as Partial)
+ const map = screen.getByTestId('map-area')
+
+ goToTab(planner, rerenderShell, 'roadtrip')
+ expect(screen.getByTestId('tab-panel')).toHaveTextContent('roadtrip')
+ // Identity, not presence. Written as two JSX positions the map remounts here,
+ // which tears down the WebGL context and reloads every tile, a flash on the
+ // device that a presence check would happily call a pass.
+ expect(screen.getByTestId('map-area')).toBe(map)
+
+ goToTab(planner, rerenderShell, 'plan')
+ expect(screen.getByTestId('map-area')).toBe(map)
+ expect(screen.getByTestId('plan-timeline')).toBeInTheDocument()
+ })
+
+ it('FE-MOB-SHELL-055: a tab with no map still tears it down', () => {
+ const { planner, rerenderShell } = renderShell({ TRIP_TABS: RT_TABS, activeTab: 'roadtrip' } as Partial)
+ expect(screen.getByTestId('map-area')).toBeInTheDocument()
+
+ goToTab(planner, rerenderShell, 'transports')
+
+ expect(screen.queryByTestId('map-area')).not.toBeInTheDocument()
+ expect(screen.getByTestId('tab-panel')).toHaveTextContent('transports')
+ })
+
+ it('FE-MOB-SHELL-056: the switch in the drive flips its own half, not the plan view', () => {
+ renderShell({ TRIP_TABS: RT_TABS, activeTab: 'roadtrip' } as Partial)
+ expect(shellApi.mapFront).toBe(false)
+
+ fireEvent.click(rtSwitch())
+ expect(shellApi.rtView).toBe('map')
+ expect(shellApi.mapFront).toBe(true)
+ expect(shellApi.view).toBe('plan')
+
+ fireEvent.click(backToList())
+ expect(shellApi.rtView).toBe('list')
+ expect(shellApi.mapFront).toBe(false)
+ })
+
+ it('FE-MOB-SHELL-057: the drive switch draws the route and otherwise leaves the camera alone', () => {
+ const { planner } = renderShell({
+ TRIP_TABS: RT_TABS, activeTab: 'roadtrip', selectedDayId: null,
+ } as Partial)
+
+ fireEvent.click(rtSwitch())
+ expect(planner.autoShowRoute).toHaveBeenCalledTimes(1)
+ // Deliberately quieter than the plan tab's toggle: the stage is always one day,
+ // both halves show the same one, and the camera belongs to whoever looked last.
+ expect(planner.handleSelectDay).not.toHaveBeenCalled()
+ expect(planner.setExpandedDayIds).not.toHaveBeenCalled()
+
+ fireEvent.click(backToList())
+ // And no day restore on the way out, which is what the plan tab does here.
+ expect(planner.handleSelectDay).not.toHaveBeenCalled()
+ expect(planner.setExpandedDayIds).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-SHELL-058: the two halves are separate states, so neither tab drags the other into its own', () => {
+ const { planner, rerenderShell } = renderShell({ TRIP_TABS: RT_TABS } as Partial)
+
+ fireEvent.click(rtSwitch())
+ expect(shellApi.view).toBe('map')
+ expect(shellApi.rtView).toBe('list')
+ expect(shellApi.mapFront).toBe(true)
+
+ goToTab(planner, rerenderShell, 'roadtrip')
+ // The plan tab is still on its map; the drive opens on its chain regardless.
+ expect(shellApi.view).toBe('map')
+ expect(shellApi.mapFront).toBe(false)
+ expect(screen.getByRole('button', { name: 'mobileTrip.mapView' })).toBeInTheDocument()
+ })
+
+ it('FE-MOB-SHELL-059: the all-days button follows the map into the drive', () => {
+ const { planner } = renderShell({ TRIP_TABS: RT_TABS, activeTab: 'roadtrip' } as Partial)
+ expect(screen.queryByRole('button', { name: 'mobileTrip.allDays' })).not.toBeInTheDocument()
+
+ fireEvent.click(rtSwitch())
+ vi.mocked(planner.setExpandedDayIds).mockClear()
+ fireEvent.click(screen.getByRole('button', { name: 'mobileTrip.allDays' }))
+
+ // The whole drive in its day colours, off the same handler the plan map uses.
+ expect(planner.handleSelectDay).toHaveBeenLastCalledWith(null, false)
+ expect(planner.setExpandedDayIds).toHaveBeenCalledWith(null)
+ })
+
+ it('FE-MOB-SHELL-060: the stage header opens the driving settings', () => {
+ renderShell({ TRIP_TABS: RT_TABS, activeTab: 'roadtrip' } as Partial)
+ fireEvent.click(screen.getByRole('button', { name: 'roadtrip.title' }))
+ expect(shellApi.sheet).toEqual({ id: 'rtinfo', payload: undefined })
+ })
+
+ it('FE-MOB-SHELL-061: the stage header names the day on screen and what it costs', () => {
+ renderShell({
+ TRIP_TABS: RT_TABS,
+ activeTab: 'roadtrip',
+ roadtripRoutes: { days: [stage()], totalDistance: 240000 },
+ } as unknown as Partial)
+ // The stage beats the total: 123 km is today's drive, 240 km is the whole trip.
+ const header = screen.getByRole('button', { name: 'Sat 2, 123 km' })
+ // Two badges rather than one line joined with a dot.
+ expect(within(header).getByText('Sat 2')).not.toBe(within(header).getByText('123 km'))
+ expect(header.textContent).not.toContain('·')
+ })
+
+ it('FE-MOB-SHELL-062: with the day filter off it reads the whole drive', () => {
+ renderShell({
+ TRIP_TABS: RT_TABS,
+ activeTab: 'roadtrip',
+ selectedDayId: null,
+ roadtripRoutes: { days: [stage()], totalDistance: 240000 },
+ } as unknown as Partial)
+ const header = screen.getByRole('button', { name: '240 km' })
+ // The total alone: without a stage there is no day to badge.
+ const badges = header.querySelectorAll('span.rounded-full')
+ expect(badges).toHaveLength(1)
+ expect(badges[0]).toHaveTextContent('240 km')
+ })
+
+ it('FE-MOB-SHELL-063: before anything has routed it falls back to the addon name, and the plan tab never shows it', () => {
+ const { planner, rerenderShell } = renderShell({ TRIP_TABS: RT_TABS, activeTab: 'roadtrip' } as Partial)
+ // Never an empty figure: the header is the only way into the driving settings.
+ expect(screen.getByRole('button', { name: 'roadtrip.title' })).toBeInTheDocument()
+
+ goToTab(planner, rerenderShell, 'plan')
+ expect(screen.queryByRole('button', { name: 'roadtrip.title' })).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-SHELL-064: a stage whose day the rail has lost still reads as a day number', () => {
+ // A remote day:deleted can retire the day while its legs are still on screen.
+ renderShell({
+ TRIP_TABS: RT_TABS,
+ activeTab: 'roadtrip',
+ selectedDayId: 99,
+ roadtripRoutes: { days: [stage({ dayId: 99, dayNumber: 4, distance: 50000 })], totalDistance: 240000 },
+ } as unknown as Partial)
+ expect(screen.getByRole('button', { name: 'planner.dayN:4, 50 km' })).toBeInTheDocument()
+ })
+
+ it('FE-MOB-SHELL-065: a stage the round has not measured yet shows its day badge alone', () => {
+ renderShell({
+ TRIP_TABS: RT_TABS,
+ activeTab: 'roadtrip',
+ roadtripRoutes: { days: [stage({ distance: 0 })], totalDistance: 240000 },
+ } as unknown as Partial)
+ // Not "Sat 2 · 0 m", and not the whole trip's 240 km standing in for the day either.
+ // The active day chip below shares the name, so the header is the one with the sliders.
+ const header = screen.getAllByRole('button', { name: 'Sat 2' })
+ .find(button => button.querySelector('.lucide-sliders-horizontal')) as HTMLElement
+ expect(header).toBeDefined()
+ expect(within(header).queryByText('0 m')).toBeNull()
+ expect(within(header).queryByText('240 km')).toBeNull()
+ })
+
+ it('FE-MOB-SHELL-066: the header figures are badges, the day in caps and the distance in its own case', () => {
+ renderShell({
+ TRIP_TABS: RT_TABS,
+ activeTab: 'roadtrip',
+ roadtripRoutes: { days: [stage()], totalDistance: 240000 },
+ } as unknown as Partial)
+ const header = screen.getByRole('button', { name: 'Sat 2, 123 km' })
+ const badges = Array.from(header.children).filter(el => el.tagName === 'SPAN')
+ expect(badges.map(b => b.textContent)).toEqual(['Sat 2', '123 km'])
+ for (const badge of badges) expect(badge.className).toContain('rounded-full')
+ expect(badges[0].className).toContain('uppercase')
+ // m and M are different units, so the distance keeps its case.
+ expect(badges[1].className).not.toContain('uppercase')
+ // Neutral, both: the active day chip right below is already the filled pill.
+ expect(badges[0].className).not.toContain('bg-m-act')
+ })
+ })
})
describe('buildShell fixture', () => {
diff --git a/client/tests/unit/mobile/trip/useMRtAlternatives.test.ts b/client/tests/unit/mobile/trip/useMRtAlternatives.test.ts
new file mode 100644
index 000000000..533d79693
--- /dev/null
+++ b/client/tests/unit/mobile/trip/useMRtAlternatives.test.ts
@@ -0,0 +1,204 @@
+import { describe, expect, it, vi } from 'vitest'
+import { act, renderHook } from '@testing-library/react'
+import { buildPlanner, buildShell } from '../../../helpers/mobileTrip'
+import {
+ RT_ALT_BAR_HEIGHT, RT_ALT_BAR_LIFT, useMRtAlternatives,
+} from '../../../../src/mobile/screens/trip/roadtrip/useMRtAlternatives'
+import { buildAlternativeOverlays } from '../../../../src/components/Roadtrip/alternativeOverlays'
+import type { LegAlternatives, OfferedRoute } from '../../../../src/components/Roadtrip/useRouteAlternatives'
+import type { MTripShellApi, TripPlanner } from '../../../../src/mobile/screens/trip/MTripShell'
+
+// FE-MOB-RTALTH-001 to FE-MOB-RTALTH-009
+//
+// The hook holds no picker state, so every case is a planner shape and what the hook
+// reads out of it or asks of it.
+
+/** Three ways of driving one leg: the road already driven first, then two offers. */
+const ROUTES: OfferedRoute[] = [
+ { coordinates: [[35.7, 139.8], [35.4, 138.6], [34.98, 135.75]], distance: 210_000, duration: 9_600, divergence: null, current: true },
+ { coordinates: [[35.7, 139.8], [35.9, 138.2], [34.98, 135.75]], distance: 198_000, duration: 10_320, divergence: { lat: 35.9, lng: 138.2 } },
+ { coordinates: [[35.7, 139.8], [35.2, 138.9], [34.98, 135.75]], distance: 236_000, duration: 11_400, divergence: { lat: 35.2, lng: 138.9 }, avoids: 'motorway' },
+]
+
+const OVERLAYS = buildAlternativeOverlays(ROUTES, {
+ fastest: 'Fastest', current: 'Current', noMotorway: 'No motorway', noToll: 'No tolls', noFerry: 'No ferry',
+})
+
+function leg(over: Partial = {}): LegAlternatives {
+ return { dayId: 2, index: 1, routes: ROUTES, loading: false, error: false, ...over }
+}
+
+/** A planner with the picker open on leg 1 of day 2, answered with three roads. */
+function planner(over: Partial = {}, open: LegAlternatives | null = leg()): TripPlanner {
+ const base = buildPlanner()
+ return buildPlanner({
+ selectedDayId: 2,
+ routeAlternatives: { ...base.routeAlternatives, open },
+ alternativeOverlays: open ? OVERLAYS : [],
+ ...over,
+ } as Partial)
+}
+
+function setup(p: TripPlanner = planner(), shell: MTripShellApi = buildShell()) {
+ const view = renderHook(({ pl, sh }) => useMRtAlternatives(pl, sh), { initialProps: { pl: p, sh: shell } })
+ return { ...view, planner: p, shell }
+}
+
+describe('useMRtAlternatives', () => {
+ it('FE-MOB-RTALTH-001: a leg is open only when both its day and its position match', () => {
+ const { result } = setup()
+
+ expect(result.current.isOpenFor(2, 1)).toBe(true)
+ // The same position on another card, and another leg of the same card.
+ expect(result.current.isOpenFor(1, 1)).toBe(false)
+ expect(result.current.isOpenFor(2, 0)).toBe(false)
+
+ const closed = setup(planner({}, null))
+ expect(closed.result.current.isOpenFor(2, 1)).toBe(false)
+ })
+
+ it('FE-MOB-RTALTH-002: reads the phase and the picked road off the planner, and has neither while closed', () => {
+ const closed = setup(planner({}, null))
+ expect(closed.result.current.open).toBeNull()
+ expect(closed.result.current.phase).toBeNull()
+ expect(closed.result.current.picked).toBeNull()
+
+ const asking = setup(planner({ alternativeOverlays: [] }, leg({ loading: true, routes: [] })))
+ expect(asking.result.current.phase).toBe('loading')
+
+ const picked = setup(planner({ highlightedAlternative: 2 }))
+ expect(picked.result.current.phase).toBe('choose')
+ expect(picked.result.current.overlays).toBe(OVERLAYS)
+ expect(picked.result.current.picked).toBe(OVERLAYS[2])
+
+ // A pick the overlays do not hold is no pick, rather than a road nobody is shown.
+ const stray = setup(planner({ highlightedAlternative: 7 }))
+ expect(stray.result.current.picked).toBeNull()
+ })
+
+ it('FE-MOB-RTALTH-003: confirm needs a road other than the one driven, a connection and a choice to make', () => {
+ expect(setup(planner()).result.current.canConfirm).toBe(false)
+ // The road already driven writes nothing, so there is nothing to confirm.
+ expect(setup(planner({ highlightedAlternative: 0 })).result.current.canConfirm).toBe(false)
+ expect(setup(planner({ highlightedAlternative: 1 })).result.current.canConfirm).toBe(true)
+
+ const base = buildPlanner()
+ const offline = setup(planner({ highlightedAlternative: 1, roadtripVias: { ...base.roadtripVias, editable: false } }))
+ expect(offline.result.current.editable).toBe(false)
+ expect(offline.result.current.canConfirm).toBe(false)
+
+ // A pick left over from the answer before is not a choice while the router is asked again.
+ const asking = setup(planner({ highlightedAlternative: 1 }, leg({ loading: true })))
+ expect(asking.result.current.canConfirm).toBe(false)
+ })
+
+ it('FE-MOB-RTALTH-004: asking a new leg clears the old pick and the fuel search, then goes to the map', () => {
+ const p = planner({}, null)
+ const shell = buildShell({ rtView: 'list' })
+ const { result } = setup(p, shell)
+
+ act(() => { result.current.ask(2, 0) })
+
+ expect(p.setHighlightedAlternative).toHaveBeenCalledWith(null)
+ expect(p.refuel.close).toHaveBeenCalledTimes(1)
+ expect(p.askRouteAlternatives).toHaveBeenCalledWith(2, 0)
+ // The pick is cleared before the new question goes out.
+ const cleared = vi.mocked(p.setHighlightedAlternative).mock.invocationCallOrder[0]
+ expect(cleared).toBeLessThan(vi.mocked(p.askRouteAlternatives).mock.invocationCallOrder[0])
+ expect(shell.toggleRtView).toHaveBeenCalledTimes(1)
+
+ // Already on the map, the switch would take the traveller back to the chain.
+ const onMap = buildShell({ rtView: 'map' })
+ const second = setup(planner({}, null), onMap)
+ act(() => { second.result.current.ask(2, 0) })
+ expect(second.planner.askRouteAlternatives).toHaveBeenCalledWith(2, 0)
+ expect(onMap.toggleRtView).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-RTALTH-005: asking the leg already open only goes back to its answer', () => {
+ const p = planner({ highlightedAlternative: 1 })
+ const shell = buildShell({ rtView: 'list' })
+ const { result } = setup(p, shell)
+
+ act(() => { result.current.ask(2, 1) })
+
+ // The planner's ask toggles an open leg shut, and the pick on it is still wanted.
+ expect(p.askRouteAlternatives).not.toHaveBeenCalled()
+ expect(p.setHighlightedAlternative).not.toHaveBeenCalled()
+ expect(p.refuel.close).not.toHaveBeenCalled()
+ expect(shell.toggleRtView).toHaveBeenCalledTimes(1)
+ })
+
+ it('FE-MOB-RTALTH-006: a stage change closes the picker, and nothing else does', () => {
+ const p = planner()
+ const { rerender, shell } = setup(p)
+ expect(p.routeAlternatives.close).not.toHaveBeenCalled()
+
+ // Re-rendered on the same stage, as the shell does on every store write.
+ rerender({ pl: { ...p }, sh: shell })
+ expect(p.routeAlternatives.close).not.toHaveBeenCalled()
+
+ rerender({ pl: { ...p, selectedDayId: 3 }, sh: shell })
+ expect(p.routeAlternatives.close).toHaveBeenCalledTimes(1)
+
+ // The all days view has no stage at all, so no leg of one either.
+ const allDays = planner({ selectedDayId: null })
+ setup(allDays)
+ expect(allDays.routeAlternatives.close).toHaveBeenCalledTimes(1)
+
+ // With nothing open there is nothing to close.
+ const closed = planner({ selectedDayId: 3 }, null)
+ setup(closed)
+ expect(closed.routeAlternatives.close).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-RTALTH-007: confirm writes the picked road once and is pending until the write lands', async () => {
+ let land: () => void = () => {}
+ const p = planner({
+ highlightedAlternative: 2,
+ chooseRouteAlternative: vi.fn(() => new Promise(resolve => { land = resolve })),
+ })
+ const { result } = setup(p)
+
+ act(() => { result.current.confirm() })
+
+ expect(p.chooseRouteAlternative).toHaveBeenCalledWith(2)
+ expect(result.current.saving).toBe(true)
+ expect(result.current.canConfirm).toBe(false)
+ // A second tap while the first is in flight writes nothing more.
+ act(() => { result.current.confirm() })
+ expect(p.chooseRouteAlternative).toHaveBeenCalledTimes(1)
+
+ await act(async () => { land() })
+ expect(result.current.saving).toBe(false)
+ expect(result.current.canConfirm).toBe(true)
+ })
+
+ it('FE-MOB-RTALTH-008: a pick only lights a road, cancel closes, and the question needs day edit rights', () => {
+ const p = planner()
+ const { result } = setup(p)
+
+ act(() => { result.current.pick(1) })
+ expect(p.setHighlightedAlternative).toHaveBeenCalledWith(1)
+ expect(p.chooseRouteAlternative).not.toHaveBeenCalled()
+
+ act(() => { result.current.confirm() })
+ // Nothing picked in this planner, so the confirm stays a no-op.
+ expect(p.chooseRouteAlternative).not.toHaveBeenCalled()
+
+ act(() => { result.current.cancel() })
+ expect(p.routeAlternatives.close).toHaveBeenCalledTimes(1)
+
+ expect(result.current.canAsk).toBe(true)
+ expect(p.can).toHaveBeenCalledWith('day_edit', p.trip)
+ const viewer = setup(planner({ can: vi.fn(() => false) }))
+ expect(viewer.result.current.canAsk).toBe(false)
+ })
+
+ it('FE-MOB-RTALTH-009: the map lifts its floor by the bar and the gap it keeps from the dock', () => {
+ // The same 15px a bar standing over the dock keeps from it. This is the only such bar
+ // left: the stage bar that used to hold the slot the rest of the time is gone.
+ expect(RT_ALT_BAR_HEIGHT).toBe(174)
+ expect(RT_ALT_BAR_LIFT).toBe(189)
+ })
+})
diff --git a/client/tests/unit/mobile/trip/useMRtCorridor.test.ts b/client/tests/unit/mobile/trip/useMRtCorridor.test.ts
new file mode 100644
index 000000000..aecf98fac
--- /dev/null
+++ b/client/tests/unit/mobile/trip/useMRtCorridor.test.ts
@@ -0,0 +1,218 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, renderHook } from '@testing-library/react'
+import { buildPlanner, buildShell } from '../../../helpers/mobileTrip'
+import { useMRtCorridor } from '../../../../src/mobile/screens/trip/roadtrip/useMRtCorridor'
+import type { MTripShellApi, TripPlanner } from '../../../../src/mobile/screens/trip/MTripShell'
+import type { RoadtripCorridor } from '../../../../src/components/Roadtrip/useRoadtripCorridor'
+import type { Day } from '../../../../src/types'
+import type { RoadtripDay, RoadtripRoutes } from '@trek/shared/roadtrip'
+
+// FE-MOB-RTCOR-001 to FE-MOB-RTCOR-012
+
+const mocks = vi.hoisted(() => ({ offline: false }))
+vi.mock('../../../../src/hooks/useNetworkMode', () => ({
+ useNetworkMode: () => ({ offline: mocks.offline, forced: false, setForced: vi.fn() }),
+}))
+
+const DAYS = [
+ { id: 1, trip_id: 7, day_number: 1, date: '2026-05-01', title: null },
+ { id: 2, trip_id: 7, day_number: 2, date: '2026-05-02', title: null },
+] as unknown as Day[]
+
+/** Four stops with clocks on them, so "which one is next" has an answer. */
+function stage(over: Partial = {}): RoadtripDay {
+ return {
+ dayId: 2,
+ dayNumber: 2,
+ date: '2026-05-02',
+ stops: [
+ { assignmentId: 501, ownerDayId: 2, ownerIndex: 0, placeId: 101, name: 'Start', lat: 53.55, lng: 9.99, time: null, dwellMinutes: 0, legMode: null, incomingLegMode: null, stopType: null },
+ { assignmentId: 502, ownerDayId: 2, ownerIndex: 1, placeId: 102, name: 'Middle', lat: 53.5, lng: 9.8, time: null, dwellMinutes: 0, legMode: null, incomingLegMode: null, stopType: null },
+ { assignmentId: 503, ownerDayId: 2, ownerIndex: 2, placeId: 103, name: 'End', lat: 53.45, lng: 9.6, time: null, dwellMinutes: 0, legMode: null, incomingLegMode: null, stopType: null },
+ ],
+ legs: [],
+ schedule: {
+ entries: [
+ { arrival: '08:00', departure: '08:00', anchored: true, dayOffset: 0 },
+ { arrival: '10:00', departure: '10:00', anchored: false, dayOffset: 0 },
+ { arrival: '12:00', departure: null, anchored: false, dayOffset: 0 },
+ ],
+ warnings: [],
+ },
+ legVias: [], geometry: [], distance: 300_000, duration: 14_400,
+ driveWarnings: [], dayWarning: null, spills: [], dryPoints: [],
+ ...over,
+ } as unknown as RoadtripDay
+}
+
+function routes(over: Partial = {}): RoadtripRoutes {
+ return {
+ days: [stage()],
+ quietDays: [], lines: [], lineDays: [], accessLines: [], vias: [], segments: [],
+ totalDistance: 300_000, totalDuration: 14_400, totalStops: 3, loading: false,
+ ...over,
+ } as unknown as RoadtripRoutes
+}
+
+function corridor(over: Partial = {}): RoadtripCorridor {
+ const base = buildPlanner().roadtripCorridor as RoadtripCorridor
+ return {
+ ...base,
+ // Two points is what `canSearch` reads as "there is a drive here".
+ search: { ...base.search, spine: [{ lat: 53.55, lng: 9.99 }, { lat: 53.45, lng: 9.6 }] },
+ stopsAlongKm: [0, 40, 95],
+ ...over,
+ }
+}
+
+function planner(over: Partial = {}): TripPlanner {
+ return buildPlanner({
+ tripId: 7,
+ days: DAYS,
+ selectedDayId: 2,
+ roadtripRoutes: routes(),
+ roadtripCorridor: corridor(),
+ ...over,
+ } as Partial)
+}
+
+function setup(p: TripPlanner = planner(), shell: MTripShellApi = buildShell()) {
+ const { result, rerender } = renderHook(() => useMRtCorridor(p, shell))
+ return { result, rerender, planner: p, shell }
+}
+
+/** Freezes the clock on the stage's own date, whatever zone the runner is in. */
+function freezeAt(hour: number, minute: number): TripPlanner {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date(2026, 4, 2, hour, minute))
+ const date = new Date().toISOString().slice(0, 10)
+ return planner({
+ days: DAYS.map(d => (d.id === 2 ? { ...d, date } : d)) as unknown as Day[],
+ roadtripRoutes: routes({ days: [stage({ date })] }),
+ })
+}
+
+beforeEach(() => { mocks.offline = false })
+afterEach(() => { vi.useRealTimers() })
+
+describe('useMRtCorridor', () => {
+ it('FE-MOB-RTCOR-001: searches the stage the chip rail is on', () => {
+ const p = planner()
+ setup(p)
+
+ expect(p.roadtripCorridor.setDayId).toHaveBeenCalledWith('2')
+ })
+
+ it('FE-MOB-RTCOR-002: a trip with nothing routed names no day at all', () => {
+ const p = planner({ roadtripRoutes: routes({ days: [] }) })
+ setup(p)
+
+ // Not '' and not the first day of the trip: there is no drive to search, and
+ // writing a day id anyway would make the desktop picker jump on the next render.
+ expect(p.roadtripCorridor.setDayId).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-RTCOR-003: asks about the stretch ahead, measured from the stop already passed', () => {
+ // 11:00 on the stage's own date: the 12:00 stop is next, so the 10:00 one is behind
+ // and the road still to drive starts at its 40 km.
+ const p = freezeAt(11, 0)
+ const { result } = setup(p)
+
+ expect(result.current.anchored).toBe(true)
+ act(() => { result.current.run() })
+ expect(p.roadtripCorridor.search.search).toHaveBeenCalledWith({ fromKm: 40, toKm: 90 })
+ })
+
+ it('FE-MOB-RTCOR-004: on any other day it starts at the beginning of the stage', () => {
+ // No clock reading to go on. A guess dressed up as a position would put the search
+ // in the wrong half of the drive, so it asks about the first fifty kilometres.
+ const p = planner()
+ const { result } = setup(p)
+
+ expect(result.current.anchored).toBe(false)
+ act(() => { result.current.run() })
+ expect(p.roadtripCorridor.search.search).toHaveBeenCalledWith({ fromKm: 0, toKm: 50 })
+ })
+
+ it('FE-MOB-RTCOR-005: before the first stop is behind, ahead is the whole stage from zero', () => {
+ const p = freezeAt(7, 30)
+ const { result } = setup(p)
+
+ expect(result.current.anchored).toBe(false)
+ act(() => { result.current.run() })
+ expect(p.roadtripCorridor.search.search).toHaveBeenCalledWith({ fromKm: 0, toKm: 50 })
+ })
+
+ it('FE-MOB-RTCOR-006: a stage search asks about the whole day, with no window at all', () => {
+ const p = freezeAt(11, 0)
+ const { result } = setup(p, buildShell({ rtReach: 'stage' }))
+
+ act(() => { result.current.run() })
+ expect(p.roadtripCorridor.search.search).toHaveBeenCalledWith(null)
+ })
+
+ it('FE-MOB-RTCOR-007: changing the reach throws the answer away', () => {
+ const p = planner()
+ const shell = buildShell()
+ const { result } = setup(p, shell)
+
+ act(() => { result.current.setReach('stage') })
+
+ expect(shell.setRtReach).toHaveBeenCalledWith('stage')
+ // Hits from the fifty kilometres ahead are not an answer to "the whole stage".
+ expect(p.roadtripCorridor.clear).toHaveBeenCalledTimes(1)
+ })
+
+ it('FE-MOB-RTCOR-008: picking the reach it is already on changes nothing', () => {
+ const p = planner()
+ const shell = buildShell()
+ const { result } = setup(p, shell)
+
+ act(() => { result.current.setReach('ahead') })
+
+ expect(shell.setRtReach).not.toHaveBeenCalled()
+ expect(p.roadtripCorridor.clear).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-RTCOR-009: offline it cannot search, and pressing it anyway does nothing', () => {
+ mocks.offline = true
+ const p = planner()
+ const { result } = setup(p)
+
+ expect(result.current.offline).toBe(true)
+ expect(result.current.canSearch).toBe(false)
+ act(() => { result.current.run() })
+ expect(p.roadtripCorridor.search.search).not.toHaveBeenCalled()
+ })
+
+ it('FE-MOB-RTCOR-010: without a category or a routed line there is nothing to ask', () => {
+ const noCategory = setup(planner({ roadtripCorridor: corridor({ categories: [] }) }))
+ expect(noCategory.result.current.canSearch).toBe(false)
+
+ const base = buildPlanner().roadtripCorridor as RoadtripCorridor
+ const noLine = setup(planner({ roadtripCorridor: corridor({ search: { ...base.search, spine: [] } }) }))
+ expect(noLine.result.current.canSearch).toBe(false)
+ })
+
+ it('FE-MOB-RTCOR-011: what the map draws is what the sheet lists', () => {
+ const visible = [{ osm_id: 'a' }] as unknown as RoadtripCorridor['visible']
+ const { result } = setup(planner({ roadtripCorridor: corridor({ visible }) }))
+
+ // One array, not two filtered views of one list: the pins and the rows have to be
+ // the same set or a row points at a pin that is not there.
+ expect(result.current.hits).toBe(visible)
+ })
+
+ it('FE-MOB-RTCOR-012: "answered" needs a search to have run, not just an empty list', () => {
+ const base = buildPlanner().roadtripCorridor as RoadtripCorridor
+ const idle = setup(planner())
+ expect(idle.result.current.answered).toBe(false)
+
+ const ran = setup(planner({
+ roadtripCorridor: corridor({ search: { ...base.search, progress: { done: 3, total: 3 } } }),
+ }))
+ // Nothing found is an answer. Reading it as "nothing asked yet" would hide the one
+ // sentence that says so.
+ expect(ran.result.current.answered).toBe(true)
+ })
+})
diff --git a/shared/src/i18n/ar/dawarich.ts b/shared/src/i18n/ar/dawarich.ts
index 64b5be2fe..8af889d73 100644
--- a/shared/src/i18n/ar/dawarich.ts
+++ b/shared/src/i18n/ar/dawarich.ts
@@ -173,6 +173,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': 'على بُعد {km} كم',
'dawarich.bucket.rule': 'تُحتسب الأمنية محققة ضمن {meters} م وبعد {minutes} دقيقة في المكان.',
+ 'dawarich.journey.dayStays.one': 'إقامة واحدة من Dawarich',
+ 'dawarich.journey.dayStays.other': 'إقامات من Dawarich: {count}',
};
export default dawarich;
diff --git a/shared/src/i18n/ar/map.ts b/shared/src/i18n/ar/map.ts
index c2b148c7a..994a58b10 100644
--- a/shared/src/i18n/ar/map.ts
+++ b/shared/src/i18n/ar/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': 'عرض الرحلة كاملة',
'map.overview.hide': 'إخفاء الرحلة كاملة',
'map.overview.total': 'المسافة الإجمالية',
+ 'map.attribution': 'مصادر الخريطة',
};
export default map;
diff --git a/shared/src/i18n/ar/mobileTrip.ts b/shared/src/i18n/ar/mobileTrip.ts
index f4d75a64c..a7a0f93cf 100644
--- a/shared/src/i18n/ar/mobileTrip.ts
+++ b/shared/src/i18n/ar/mobileTrip.ts
@@ -47,5 +47,23 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': 'التالي',
'mobileTrip.viewDetails': 'عرض التفاصيل',
'mobileTrip.transportsEmpty': 'لا يوجد نقل بعد',
+ 'mobileTrip.rtInfoTitle': 'أرقام القيادة',
+ 'mobileTrip.rtDesktopNote':
+ 'تُضبط هذه الأرقام على سطح المكتب، حيث يمكنك أيضًا مقارنة المسارات البديلة، وجعل يوم يتبع مسارًا مستوردًا.',
+ 'mobileTrip.rtPlanOnDesktop': 'يتم التخطيط على سطح المكتب. يحسب TREK القيادة بمجرد أن يضم اليوم مكانين.',
+ 'mobileTrip.rtSearchOffline': 'يلزم اتصال بالإنترنت: يقرأ البحث المسار الذي أمامك.',
+ 'mobileTrip.rtBehind': '{time} تأخرًا عن الخطة',
+ 'mobileTrip.rtStart': 'البداية',
+ 'mobileTrip.rtStayScope': 'مدة التوقف تخص المكان نفسه، لذا تُحتسب في كل يوم تكون فيه هذه المحطة ضمن الخطة.',
+ 'mobileTrip.rtStayLess': '{count} دقيقة أقل',
+ 'mobileTrip.rtStayMore': '{count} دقيقة أكثر',
+ 'mobileTrip.rtNightDesktopOnly': 'إضافة مبيت في هذا المكان تتم في مخطط سطح المكتب. هنا يمكنك إزالته فقط.',
+ 'mobileTrip.rtReach': 'إلى أي مدى',
+ 'mobileTrip.rtReachAhead': '{distance} أمامك',
+ 'mobileTrip.rtFromNext': 'من محطتك التالية',
+ 'mobileTrip.rtFromStart': 'من بداية المرحلة',
+ 'mobileTrip.rtNoneAhead': 'لا شيء على الطريق أمامك. جرّب المرحلة كاملة.',
+ 'mobileTrip.rtNoneOnStage': 'لا شيء من هذا النوع على طول هذه المرحلة.',
+ 'mobileTrip.rtTruncated': '{count} مقاطع فيها أكثر مما يتسع في إجابة واحدة. اختر أنواعًا أقل لرؤية الباقي.',
};
export default mobileTrip;
diff --git a/shared/src/i18n/br/dawarich.ts b/shared/src/i18n/br/dawarich.ts
index 73fe3f5b8..2d3dfda88 100644
--- a/shared/src/i18n/br/dawarich.ts
+++ b/shared/src/i18n/br/dawarich.ts
@@ -175,6 +175,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': 'a {km} km',
'dawarich.bucket.rule': 'Um desejo conta como alcançado a até {meters} m e após {minutes} minutos no local.',
+ 'dawarich.journey.dayStays.one': '1 parada do Dawarich',
+ 'dawarich.journey.dayStays.other': '{count} paradas do Dawarich',
};
export default dawarich;
diff --git a/shared/src/i18n/br/map.ts b/shared/src/i18n/br/map.ts
index 6fca93b95..d14722b7b 100644
--- a/shared/src/i18n/br/map.ts
+++ b/shared/src/i18n/br/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': 'Mostrar a viagem inteira',
'map.overview.hide': 'Ocultar a viagem inteira',
'map.overview.total': 'Distância total',
+ 'map.attribution': 'Créditos do mapa',
};
export default map;
diff --git a/shared/src/i18n/br/mobileTrip.ts b/shared/src/i18n/br/mobileTrip.ts
index fdd948d38..c309aade9 100644
--- a/shared/src/i18n/br/mobileTrip.ts
+++ b/shared/src/i18n/br/mobileTrip.ts
@@ -47,5 +47,27 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': 'A seguir',
'mobileTrip.viewDetails': 'Ver detalhes',
'mobileTrip.transportsEmpty': 'Nenhum transporte ainda',
+ 'mobileTrip.rtInfoTitle': 'Dados de condução',
+ 'mobileTrip.rtDesktopNote':
+ 'Esses dados são definidos no computador, onde você também pode comparar rotas alternativas e fazer um dia seguir uma trilha importada.',
+ 'mobileTrip.rtPlanOnDesktop':
+ 'O planejamento acontece no computador. O TREK calcula o trajeto assim que um dia tem dois locais.',
+ 'mobileTrip.rtSearchOffline': 'Precisa de conexão: a busca lê a rota à frente.',
+ 'mobileTrip.rtBehind': '{time} de atraso em relação ao plano',
+ 'mobileTrip.rtStart': 'Início',
+ 'mobileTrip.rtStayScope':
+ 'A estadia pertence ao local, então ela vale em todos os dias em que esta parada está planejada.',
+ 'mobileTrip.rtStayLess': '{count} minutos a menos',
+ 'mobileTrip.rtStayMore': '{count} minutos a mais',
+ 'mobileTrip.rtNightDesktopOnly':
+ 'Reservar um pernoite neste local funciona no planejador do computador. Aqui você só pode descartá-lo.',
+ 'mobileTrip.rtReach': 'Até onde',
+ 'mobileTrip.rtReachAhead': '{distance} à frente',
+ 'mobileTrip.rtFromNext': 'A partir da sua próxima parada',
+ 'mobileTrip.rtFromStart': 'A partir do início da etapa',
+ 'mobileTrip.rtNoneAhead': 'Nada na estrada à frente. Tente a etapa inteira.',
+ 'mobileTrip.rtNoneOnStage': 'Nada desse tipo ao longo desta etapa.',
+ 'mobileTrip.rtTruncated':
+ '{count} trechos tinham mais do que cabe em uma resposta. Escolha menos tipos para ver o resto.',
};
export default mobileTrip;
diff --git a/shared/src/i18n/ca/dawarich.ts b/shared/src/i18n/ca/dawarich.ts
index bbc9aa412..bf9980e1e 100644
--- a/shared/src/i18n/ca/dawarich.ts
+++ b/shared/src/i18n/ca/dawarich.ts
@@ -174,6 +174,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': 'a {km} km',
'dawarich.bucket.rule': 'Un desig es considera assolit a menys de {meters} m i després de {minutes} minuts al lloc.',
+ 'dawarich.journey.dayStays.one': '1 estada de Dawarich',
+ 'dawarich.journey.dayStays.other': '{count} estades de Dawarich',
};
export default dawarich;
diff --git a/shared/src/i18n/ca/map.ts b/shared/src/i18n/ca/map.ts
index e0bf1b992..a5ec3b491 100644
--- a/shared/src/i18n/ca/map.ts
+++ b/shared/src/i18n/ca/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': 'Mostra tot el viatge',
'map.overview.hide': 'Amaga tot el viatge',
'map.overview.total': 'Distància total',
+ 'map.attribution': 'Crèdits del mapa',
};
export default map;
diff --git a/shared/src/i18n/ca/mobileTrip.ts b/shared/src/i18n/ca/mobileTrip.ts
index e2d94b94b..8a315755e 100644
--- a/shared/src/i18n/ca/mobileTrip.ts
+++ b/shared/src/i18n/ca/mobileTrip.ts
@@ -47,6 +47,28 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': 'A continuació',
'mobileTrip.viewDetails': 'Mostra els detalls',
'mobileTrip.transportsEmpty': 'Encara no hi ha transport',
+ 'mobileTrip.rtInfoTitle': 'Dades de conducció',
+ 'mobileTrip.rtDesktopNote':
+ 'Aquestes dades es configuren a l’escriptori, on també pots comparar rutes alternatives i fer que un dia segueixi una traça importada.',
+ 'mobileTrip.rtPlanOnDesktop':
+ 'La planificació es fa a l’escriptori. TREK calcula el trajecte quan un dia té dos llocs.',
+ 'mobileTrip.rtSearchOffline': 'Cal connexió: la cerca llegeix la ruta que tens per endavant.',
+ 'mobileTrip.rtBehind': '{time} de retard sobre el pla',
+ 'mobileTrip.rtStart': 'Inici',
+ 'mobileTrip.rtStayScope':
+ 'L’estada pertany al lloc, així que compta tots els dies en què aquesta parada està planificada.',
+ 'mobileTrip.rtStayLess': '{count} minuts menys',
+ 'mobileTrip.rtStayMore': '{count} minuts més',
+ 'mobileTrip.rtNightDesktopOnly':
+ 'Reservar una pernoctació en aquest lloc es fa al planificador d’escriptori. Aquí només la pots descartar.',
+ 'mobileTrip.rtReach': 'Fins on',
+ 'mobileTrip.rtReachAhead': '{distance} per endavant',
+ 'mobileTrip.rtFromNext': 'Des de la teva propera parada',
+ 'mobileTrip.rtFromStart': 'Des de l’inici de l’etapa',
+ 'mobileTrip.rtNoneAhead': 'No hi ha res a la carretera que tens al davant. Prova tota l’etapa.',
+ 'mobileTrip.rtNoneOnStage': 'No hi ha res d’aquest tipus al llarg d’aquesta etapa.',
+ 'mobileTrip.rtTruncated':
+ '{count} trams tenien més del que cap en una resposta. Tria menys tipus per veure la resta.',
};
export default mobileTrip;
diff --git a/shared/src/i18n/cs/dawarich.ts b/shared/src/i18n/cs/dawarich.ts
index d8361290f..766db6edb 100644
--- a/shared/src/i18n/cs/dawarich.ts
+++ b/shared/src/i18n/cs/dawarich.ts
@@ -174,6 +174,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': '{km} km daleko',
'dawarich.bucket.rule': 'Přání se počítá jako splněné do {meters} m a po {minutes} minutách na místě.',
+ 'dawarich.journey.dayStays.one': '1 zastávka z Dawarichu',
+ 'dawarich.journey.dayStays.other': 'Zastávky z Dawarichu: {count}',
};
export default dawarich;
diff --git a/shared/src/i18n/cs/map.ts b/shared/src/i18n/cs/map.ts
index c12aea4db..4d834319e 100644
--- a/shared/src/i18n/cs/map.ts
+++ b/shared/src/i18n/cs/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': 'Zobrazit celou cestu',
'map.overview.hide': 'Skrýt celou cestu',
'map.overview.total': 'Celková vzdálenost',
+ 'map.attribution': 'Zdroje mapy',
};
export default map;
diff --git a/shared/src/i18n/cs/mobileTrip.ts b/shared/src/i18n/cs/mobileTrip.ts
index 5ca305d1b..656ca2b00 100644
--- a/shared/src/i18n/cs/mobileTrip.ts
+++ b/shared/src/i18n/cs/mobileTrip.ts
@@ -47,5 +47,26 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': 'Další na řadě',
'mobileTrip.viewDetails': 'Zobrazit podrobnosti',
'mobileTrip.transportsEmpty': 'Zatím žádná doprava',
+ 'mobileTrip.rtInfoTitle': 'Údaje o jízdě',
+ 'mobileTrip.rtDesktopNote':
+ 'Tyto údaje se nastavují na počítači, kde také můžete porovnávat jiné trasy a nechat den sledovat importovanou stopu.',
+ 'mobileTrip.rtPlanOnDesktop': 'Plánování probíhá na počítači. Jakmile má den dvě místa, TREK jízdu spočítá.',
+ 'mobileTrip.rtSearchOffline': 'Vyžaduje připojení: hledání čte trasu před vámi.',
+ 'mobileTrip.rtBehind': 'o {time} za plánem',
+ 'mobileTrip.rtStart': 'Začátek',
+ 'mobileTrip.rtStayScope':
+ 'Doba zastávky patří k místu, takže platí pro každý den, na který je tato zastávka naplánovaná.',
+ 'mobileTrip.rtStayLess': 'o {count} minut méně',
+ 'mobileTrip.rtStayMore': 'o {count} minut více',
+ 'mobileTrip.rtNightDesktopOnly':
+ 'Nocleh na tomto místě se zadává v plánovači na počítači. Tady jej můžete jen zrušit.',
+ 'mobileTrip.rtReach': 'Jak daleko',
+ 'mobileTrip.rtReachAhead': '{distance} před vámi',
+ 'mobileTrip.rtFromNext': 'Od vaší příští zastávky',
+ 'mobileTrip.rtFromStart': 'Od začátku etapy',
+ 'mobileTrip.rtNoneAhead': 'Na cestě před vámi nic není. Zkuste celou etapu.',
+ 'mobileTrip.rtNoneOnStage': 'Nic takového podél této etapy není.',
+ 'mobileTrip.rtTruncated':
+ '{count} úseků mělo víc, než se vejde do jedné odpovědi. Vyberte méně druhů, ať uvidíte zbytek.',
};
export default mobileTrip;
diff --git a/shared/src/i18n/de/dawarich.ts b/shared/src/i18n/de/dawarich.ts
index 78283b868..dc96d0c2c 100644
--- a/shared/src/i18n/de/dawarich.ts
+++ b/shared/src/i18n/de/dawarich.ts
@@ -178,6 +178,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': '{km} km entfernt',
'dawarich.bucket.rule': 'Ein Wunsch gilt ab {meters} m Nähe und {minutes} Minuten vor Ort als erreicht.',
+ 'dawarich.journey.dayStays.one': '1 Aufenthalt von Dawarich',
+ 'dawarich.journey.dayStays.other': '{count} Aufenthalte von Dawarich',
};
export default dawarich;
diff --git a/shared/src/i18n/de/map.ts b/shared/src/i18n/de/map.ts
index a4b0e874b..baa750e0a 100644
--- a/shared/src/i18n/de/map.ts
+++ b/shared/src/i18n/de/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': 'Ganze Reise anzeigen',
'map.overview.hide': 'Ganze Reise ausblenden',
'map.overview.total': 'Gesamtstrecke',
+ 'map.attribution': 'Kartenquellen',
};
export default map;
diff --git a/shared/src/i18n/de/mobileTrip.ts b/shared/src/i18n/de/mobileTrip.ts
index 2eaf8a02f..1a4c282fb 100644
--- a/shared/src/i18n/de/mobileTrip.ts
+++ b/shared/src/i18n/de/mobileTrip.ts
@@ -47,5 +47,26 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': 'Als Nächstes',
'mobileTrip.viewDetails': 'Details anzeigen',
'mobileTrip.transportsEmpty': 'Noch keine Transporte',
+ 'mobileTrip.rtInfoTitle': 'Fahrdaten',
+ 'mobileTrip.rtDesktopNote':
+ 'Diese Werte werden am Desktop gesetzt. Dort kannst du auch Routenvarianten vergleichen und einen Tag einer importierten Spur folgen lassen.',
+ 'mobileTrip.rtPlanOnDesktop': 'Geplant wird am Desktop. TREK berechnet die Fahrt, sobald ein Tag zwei Orte hat.',
+ 'mobileTrip.rtSearchOffline': 'Braucht eine Verbindung: Die Suche liest die Strecke, die vor dir liegt.',
+ 'mobileTrip.rtBehind': '{time} hinter dem Plan',
+ 'mobileTrip.rtStart': 'Start',
+ 'mobileTrip.rtStayScope':
+ 'Der Aufenthalt gehört zum Ort und zählt deshalb an jedem Tag, an dem dieser Stopp geplant ist.',
+ 'mobileTrip.rtStayLess': '{count} Minuten weniger',
+ 'mobileTrip.rtStayMore': '{count} Minuten mehr',
+ 'mobileTrip.rtNightDesktopOnly':
+ 'Eine Übernachtung an diesem Ort legst du im Desktop-Planer an. Hier kannst du sie nur verwerfen.',
+ 'mobileTrip.rtReach': 'Wie weit',
+ 'mobileTrip.rtReachAhead': '{distance} voraus',
+ 'mobileTrip.rtFromNext': 'Ab deinem nächsten Stopp',
+ 'mobileTrip.rtFromStart': 'Ab dem Anfang der Etappe',
+ 'mobileTrip.rtNoneAhead': 'Auf der Strecke voraus ist nichts. Versuch die ganze Etappe.',
+ 'mobileTrip.rtNoneOnStage': 'Auf dieser Etappe gibt es davon nichts.',
+ 'mobileTrip.rtTruncated':
+ '{count} Abschnitte hatten mehr, als in eine Antwort passt. Wähl weniger Arten, um den Rest zu sehen.',
};
export default mobileTrip;
diff --git a/shared/src/i18n/en/dawarich.ts b/shared/src/i18n/en/dawarich.ts
index a04011cee..b9f16e240 100644
--- a/shared/src/i18n/en/dawarich.ts
+++ b/shared/src/i18n/en/dawarich.ts
@@ -173,6 +173,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': '{km} km away',
'dawarich.bucket.rule': 'A wish counts as reached within {meters} m and after {minutes} minutes on the spot.',
+ 'dawarich.journey.dayStays.one': '1 stay from Dawarich',
+ 'dawarich.journey.dayStays.other': '{count} stays from Dawarich',
};
export default dawarich;
diff --git a/shared/src/i18n/en/map.ts b/shared/src/i18n/en/map.ts
index b14c9b528..26f01b3ad 100644
--- a/shared/src/i18n/en/map.ts
+++ b/shared/src/i18n/en/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': 'Show whole trip',
'map.overview.hide': 'Hide whole trip',
'map.overview.total': 'Total distance',
+ 'map.attribution': 'Map credits',
};
export default map;
diff --git a/shared/src/i18n/en/mobileTrip.ts b/shared/src/i18n/en/mobileTrip.ts
index b393619f5..5841040bb 100644
--- a/shared/src/i18n/en/mobileTrip.ts
+++ b/shared/src/i18n/en/mobileTrip.ts
@@ -47,5 +47,25 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': 'Up Next',
'mobileTrip.viewDetails': 'View details',
'mobileTrip.transportsEmpty': 'No transport yet',
+ 'mobileTrip.rtInfoTitle': 'Driving figures',
+ 'mobileTrip.rtDesktopNote':
+ 'These figures are set on the desktop, where you can also compare route alternatives and make a day follow an imported track.',
+ 'mobileTrip.rtPlanOnDesktop': 'Planning happens on the desktop. TREK works out the drive once a day has two places.',
+ 'mobileTrip.rtSearchOffline': 'Needs a connection: the search reads the route ahead.',
+ 'mobileTrip.rtBehind': '{time} behind plan',
+ 'mobileTrip.rtStart': 'Start',
+ 'mobileTrip.rtStayScope': 'The stay belongs to the place, so it counts on every day this stop is planned.',
+ 'mobileTrip.rtStayLess': '{count} minutes less',
+ 'mobileTrip.rtStayMore': '{count} minutes more',
+ 'mobileTrip.rtNightDesktopOnly':
+ 'Booking a night at this place works in the desktop planner. Here you can only discard it.',
+ 'mobileTrip.rtReach': 'How far',
+ 'mobileTrip.rtReachAhead': '{distance} ahead',
+ 'mobileTrip.rtFromNext': 'From your next stop',
+ 'mobileTrip.rtFromStart': 'From the start of the stage',
+ 'mobileTrip.rtNoneAhead': 'Nothing on the road ahead. Try the whole stage.',
+ 'mobileTrip.rtNoneOnStage': 'Nothing of that kind along this stage.',
+ 'mobileTrip.rtTruncated':
+ '{count} stretches had more than fits in one answer. Pick fewer kinds to see the rest.',
};
export default mobileTrip;
diff --git a/shared/src/i18n/es/dawarich.ts b/shared/src/i18n/es/dawarich.ts
index 8a5aa2874..17555db93 100644
--- a/shared/src/i18n/es/dawarich.ts
+++ b/shared/src/i18n/es/dawarich.ts
@@ -175,6 +175,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': 'a {km} km',
'dawarich.bucket.rule': 'Un deseo cuenta como cumplido a menos de {meters} m y tras {minutes} minutos en el lugar.',
+ 'dawarich.journey.dayStays.one': '1 estancia de Dawarich',
+ 'dawarich.journey.dayStays.other': '{count} estancias de Dawarich',
};
export default dawarich;
diff --git a/shared/src/i18n/es/map.ts b/shared/src/i18n/es/map.ts
index 9478b1a0d..13dbf234d 100644
--- a/shared/src/i18n/es/map.ts
+++ b/shared/src/i18n/es/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': 'Mostrar todo el viaje',
'map.overview.hide': 'Ocultar todo el viaje',
'map.overview.total': 'Distancia total',
+ 'map.attribution': 'Créditos del mapa',
};
export default map;
diff --git a/shared/src/i18n/es/mobileTrip.ts b/shared/src/i18n/es/mobileTrip.ts
index 376586bd0..8bfabb6d7 100644
--- a/shared/src/i18n/es/mobileTrip.ts
+++ b/shared/src/i18n/es/mobileTrip.ts
@@ -47,5 +47,27 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': 'A continuación',
'mobileTrip.viewDetails': 'Ver detalles',
'mobileTrip.transportsEmpty': 'Aún no hay transporte',
+ 'mobileTrip.rtInfoTitle': 'Cifras del trayecto',
+ 'mobileTrip.rtDesktopNote':
+ 'Estas cifras se ajustan en el escritorio, donde también puedes comparar rutas alternativas y hacer que un día siga una traza importada.',
+ 'mobileTrip.rtPlanOnDesktop':
+ 'La planificación se hace en el escritorio. TREK calcula el trayecto en cuanto un día tiene dos lugares.',
+ 'mobileTrip.rtSearchOffline': 'Hace falta conexión: la búsqueda lee la ruta que queda por delante.',
+ 'mobileTrip.rtBehind': '{time} de retraso sobre lo previsto',
+ 'mobileTrip.rtStart': 'Inicio',
+ 'mobileTrip.rtStayScope':
+ 'La duración de la parada pertenece al lugar, así que cuenta en cada día en el que esta parada está prevista.',
+ 'mobileTrip.rtStayLess': '{count} minutos menos',
+ 'mobileTrip.rtStayMore': '{count} minutos más',
+ 'mobileTrip.rtNightDesktopOnly':
+ 'Reservar una pernoctación en este lugar se hace en el planificador de escritorio. Aquí solo puedes descartarla.',
+ 'mobileTrip.rtReach': 'Hasta dónde',
+ 'mobileTrip.rtReachAhead': '{distance} por delante',
+ 'mobileTrip.rtFromNext': 'Desde tu próxima parada',
+ 'mobileTrip.rtFromStart': 'Desde el inicio de la etapa',
+ 'mobileTrip.rtNoneAhead': 'No hay nada en la carretera que tienes por delante. Prueba con toda la etapa.',
+ 'mobileTrip.rtNoneOnStage': 'No hay nada de eso a lo largo de esta etapa.',
+ 'mobileTrip.rtTruncated':
+ '{count} tramos tenían más de lo que cabe en una respuesta. Elige menos tipos para ver el resto.',
};
export default mobileTrip;
diff --git a/shared/src/i18n/fr/dawarich.ts b/shared/src/i18n/fr/dawarich.ts
index 0c4612a55..fef3d0e81 100644
--- a/shared/src/i18n/fr/dawarich.ts
+++ b/shared/src/i18n/fr/dawarich.ts
@@ -177,6 +177,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': 'à {km} km',
'dawarich.bucket.rule': 'Une envie est atteinte à moins de {meters} m et après {minutes} minutes sur place.',
+ 'dawarich.journey.dayStays.one': '1 arrêt depuis Dawarich',
+ 'dawarich.journey.dayStays.other': '{count} arrêts depuis Dawarich',
};
export default dawarich;
diff --git a/shared/src/i18n/fr/map.ts b/shared/src/i18n/fr/map.ts
index 68854f27d..5b0093622 100644
--- a/shared/src/i18n/fr/map.ts
+++ b/shared/src/i18n/fr/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': 'Afficher tout le voyage',
'map.overview.hide': 'Masquer tout le voyage',
'map.overview.total': 'Distance totale',
+ 'map.attribution': 'Crédits de la carte',
};
export default map;
diff --git a/shared/src/i18n/fr/mobileTrip.ts b/shared/src/i18n/fr/mobileTrip.ts
index 369bfb819..01089aa6c 100644
--- a/shared/src/i18n/fr/mobileTrip.ts
+++ b/shared/src/i18n/fr/mobileTrip.ts
@@ -47,5 +47,27 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': 'À suivre',
'mobileTrip.viewDetails': 'Voir les détails',
'mobileTrip.transportsEmpty': 'Aucun transport',
+ 'mobileTrip.rtInfoTitle': 'Chiffres du trajet',
+ 'mobileTrip.rtDesktopNote':
+ 'Ces chiffres se règlent sur ordinateur, où vous pouvez aussi comparer d’autres itinéraires et faire suivre à un jour une trace importée.',
+ 'mobileTrip.rtPlanOnDesktop':
+ 'La planification se fait sur ordinateur. TREK calcule le trajet dès qu’un jour compte deux lieux.',
+ 'mobileTrip.rtSearchOffline': 'Connexion nécessaire : la recherche lit l’itinéraire à venir.',
+ 'mobileTrip.rtBehind': '{time} de retard sur le programme',
+ 'mobileTrip.rtStart': 'Début',
+ 'mobileTrip.rtStayScope':
+ 'La durée sur place appartient au lieu : elle compte donc pour chaque jour où cet arrêt est prévu.',
+ 'mobileTrip.rtStayLess': '{count} minutes de moins',
+ 'mobileTrip.rtStayMore': '{count} minutes de plus',
+ 'mobileTrip.rtNightDesktopOnly':
+ 'Réserver une nuitée à ce lieu se fait dans le planificateur sur ordinateur. Ici, vous pouvez seulement la supprimer.',
+ 'mobileTrip.rtReach': 'Jusqu’où',
+ 'mobileTrip.rtReachAhead': '{distance} devant',
+ 'mobileTrip.rtFromNext': 'À partir de votre prochain arrêt',
+ 'mobileTrip.rtFromStart': 'Depuis le début de l’étape',
+ 'mobileTrip.rtNoneAhead': 'Rien sur la route devant vous. Essayez toute l’étape.',
+ 'mobileTrip.rtNoneOnStage': 'Rien de ce genre le long de cette étape.',
+ 'mobileTrip.rtTruncated':
+ '{count} tronçons avaient plus que ce qui tient dans une réponse. Choisissez moins de types pour voir le reste.',
};
export default mobileTrip;
diff --git a/shared/src/i18n/gr/dawarich.ts b/shared/src/i18n/gr/dawarich.ts
index a0f9d0767..5773befc5 100644
--- a/shared/src/i18n/gr/dawarich.ts
+++ b/shared/src/i18n/gr/dawarich.ts
@@ -178,6 +178,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': '{km} χλμ. μακριά',
'dawarich.bucket.rule': 'Μια επιθυμία μετράει ως εκπληρωμένη σε απόσταση έως {meters} μ. και μετά από {minutes} λεπτά στο σημείο.',
+ 'dawarich.journey.dayStays.one': '1 στάση από το Dawarich',
+ 'dawarich.journey.dayStays.other': '{count} στάσεις από το Dawarich',
};
export default dawarich;
diff --git a/shared/src/i18n/gr/map.ts b/shared/src/i18n/gr/map.ts
index 37ee38c72..463bbc831 100644
--- a/shared/src/i18n/gr/map.ts
+++ b/shared/src/i18n/gr/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': 'Εμφάνιση όλου του ταξιδιού',
'map.overview.hide': 'Απόκρυψη όλου του ταξιδιού',
'map.overview.total': 'Συνολική απόσταση',
+ 'map.attribution': 'Πηγές χάρτη',
};
export default map;
diff --git a/shared/src/i18n/gr/mobileTrip.ts b/shared/src/i18n/gr/mobileTrip.ts
index c9a531006..ada7c3a7b 100644
--- a/shared/src/i18n/gr/mobileTrip.ts
+++ b/shared/src/i18n/gr/mobileTrip.ts
@@ -47,5 +47,27 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': 'Επόμενο',
'mobileTrip.viewDetails': 'Προβολή λεπτομερειών',
'mobileTrip.transportsEmpty': 'Δεν υπάρχει μεταφορά ακόμη',
+ 'mobileTrip.rtInfoTitle': 'Στοιχεία οδήγησης',
+ 'mobileTrip.rtDesktopNote':
+ 'Αυτά τα στοιχεία ορίζονται στον υπολογιστή, όπου μπορείτε επίσης να συγκρίνετε άλλες διαδρομές και να κάνετε μια ημέρα να ακολουθεί ένα εισαγόμενο ίχνος.',
+ 'mobileTrip.rtPlanOnDesktop':
+ 'Ο σχεδιασμός γίνεται στον υπολογιστή. Το TREK υπολογίζει τη διαδρομή μόλις μια ημέρα έχει δύο μέρη.',
+ 'mobileTrip.rtSearchOffline': 'Χρειάζεται σύνδεση: η αναζήτηση διαβάζει τη διαδρομή που ακολουθεί.',
+ 'mobileTrip.rtBehind': '{time} πίσω από το πρόγραμμα',
+ 'mobileTrip.rtStart': 'Έναρξη',
+ 'mobileTrip.rtStayScope':
+ 'Η διάρκεια της στάσης ανήκει στο μέρος, οπότε μετράει σε κάθε ημέρα που είναι προγραμματισμένη αυτή η στάση.',
+ 'mobileTrip.rtStayLess': '{count} λεπτά λιγότερα',
+ 'mobileTrip.rtStayMore': '{count} λεπτά περισσότερα',
+ 'mobileTrip.rtNightDesktopOnly':
+ 'Η κράτηση διανυκτέρευσης σε αυτό το μέρος γίνεται στον σχεδιαστή του υπολογιστή. Εδώ μπορείτε μόνο να την αφαιρέσετε.',
+ 'mobileTrip.rtReach': 'Πόσο μακριά',
+ 'mobileTrip.rtReachAhead': '{distance} μπροστά',
+ 'mobileTrip.rtFromNext': 'Από την επόμενη στάση σας',
+ 'mobileTrip.rtFromStart': 'Από την αρχή του σκέλους',
+ 'mobileTrip.rtNoneAhead': 'Τίποτα στον δρόμο μπροστά σας. Δοκιμάστε όλο το σκέλος.',
+ 'mobileTrip.rtNoneOnStage': 'Τίποτα τέτοιο κατά μήκος αυτού του σκέλους.',
+ 'mobileTrip.rtTruncated':
+ '{count} τμήματα είχαν περισσότερα από όσα χωρούν σε μία απάντηση. Διαλέξτε λιγότερα είδη για να δείτε τα υπόλοιπα.',
};
export default mobileTrip;
diff --git a/shared/src/i18n/hu/dawarich.ts b/shared/src/i18n/hu/dawarich.ts
index a4d9c0269..1a41b1bff 100644
--- a/shared/src/i18n/hu/dawarich.ts
+++ b/shared/src/i18n/hu/dawarich.ts
@@ -176,6 +176,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': '{km} km-re',
'dawarich.bucket.rule': 'Egy kívánság {meters} méteren belül és {minutes} perc helyszíni idő után számít teljesítettnek.',
+ 'dawarich.journey.dayStays.one': '1 tartózkodás a Dawarichból',
+ 'dawarich.journey.dayStays.other': '{count} tartózkodás a Dawarichból',
};
export default dawarich;
diff --git a/shared/src/i18n/hu/map.ts b/shared/src/i18n/hu/map.ts
index 4ed177293..a44d5185b 100644
--- a/shared/src/i18n/hu/map.ts
+++ b/shared/src/i18n/hu/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': 'Teljes utazás megjelenítése',
'map.overview.hide': 'Teljes utazás elrejtése',
'map.overview.total': 'Teljes távolság',
+ 'map.attribution': 'Térkép forrásai',
};
export default map;
diff --git a/shared/src/i18n/hu/mobileTrip.ts b/shared/src/i18n/hu/mobileTrip.ts
index 97ad3e7b4..dd226aa7b 100644
--- a/shared/src/i18n/hu/mobileTrip.ts
+++ b/shared/src/i18n/hu/mobileTrip.ts
@@ -47,5 +47,27 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': 'Következő',
'mobileTrip.viewDetails': 'Részletek megtekintése',
'mobileTrip.transportsEmpty': 'Még nincs közlekedés',
+ 'mobileTrip.rtInfoTitle': 'Vezetési adatok',
+ 'mobileTrip.rtDesktopNote':
+ 'Ezeket az adatokat asztali gépen adod meg, ott hasonlíthatod össze az útvonalváltozatokat, és állíthatod be, hogy egy nap importált nyomvonalat kövessen.',
+ 'mobileTrip.rtPlanOnDesktop':
+ 'A tervezés asztali gépen történik. Amint egy napon két hely szerepel, a TREK kiszámolja az útvonalat.',
+ 'mobileTrip.rtSearchOffline': 'Internetkapcsolat kell hozzá: a keresés az előtted lévő útvonalat olvassa be.',
+ 'mobileTrip.rtBehind': '{time} késés a tervhez képest',
+ 'mobileTrip.rtStart': 'Kezdés',
+ 'mobileTrip.rtStayScope':
+ 'Az itt töltött idő a helyhez tartozik, ezért minden olyan napon számít, amelyre ez a megálló be van tervezve.',
+ 'mobileTrip.rtStayLess': '{count} perccel kevesebb',
+ 'mobileTrip.rtStayMore': '{count} perccel több',
+ 'mobileTrip.rtNightDesktopOnly':
+ 'Az éjszakázást ezen a helyen az asztali tervezőben lehet megadni. Itt csak elvetni tudod.',
+ 'mobileTrip.rtReach': 'Meddig',
+ 'mobileTrip.rtReachAhead': '{distance} előre',
+ 'mobileTrip.rtFromNext': 'A következő megállódtól',
+ 'mobileTrip.rtFromStart': 'A szakasz elejétől',
+ 'mobileTrip.rtNoneAhead': 'Az előtted lévő úton nincs semmi. Próbáld az egész szakaszt.',
+ 'mobileTrip.rtNoneOnStage': 'Ezen a szakaszon nincs ilyesmi.',
+ 'mobileTrip.rtTruncated':
+ '{count} szakaszon több volt, mint ami egy válaszba fér. Válassz kevesebb fajtát, hogy lásd a többit.',
};
export default mobileTrip;
diff --git a/shared/src/i18n/id/dawarich.ts b/shared/src/i18n/id/dawarich.ts
index 3c3fbd380..33e4c4aad 100644
--- a/shared/src/i18n/id/dawarich.ts
+++ b/shared/src/i18n/id/dawarich.ts
@@ -175,6 +175,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': '{km} km dari sana',
'dawarich.bucket.rule': 'Sebuah keinginan dianggap tercapai dalam radius {meters} m dan setelah {minutes} menit di lokasi.',
+ 'dawarich.journey.dayStays.one': '1 persinggahan dari Dawarich',
+ 'dawarich.journey.dayStays.other': '{count} persinggahan dari Dawarich',
};
export default dawarich;
diff --git a/shared/src/i18n/id/map.ts b/shared/src/i18n/id/map.ts
index 0b41df148..885b8decb 100644
--- a/shared/src/i18n/id/map.ts
+++ b/shared/src/i18n/id/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': 'Tampilkan seluruh perjalanan',
'map.overview.hide': 'Sembunyikan seluruh perjalanan',
'map.overview.total': 'Jarak total',
+ 'map.attribution': 'Kredit peta',
};
export default map;
diff --git a/shared/src/i18n/id/mobileTrip.ts b/shared/src/i18n/id/mobileTrip.ts
index 8b8501528..cc4fbd692 100644
--- a/shared/src/i18n/id/mobileTrip.ts
+++ b/shared/src/i18n/id/mobileTrip.ts
@@ -47,5 +47,27 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': 'Berikutnya',
'mobileTrip.viewDetails': 'Lihat detail',
'mobileTrip.transportsEmpty': 'Belum ada transportasi',
+ 'mobileTrip.rtInfoTitle': 'Data berkendara',
+ 'mobileTrip.rtDesktopNote':
+ 'Data ini diatur di desktop, di sana kamu juga bisa membandingkan rute alternatif dan membuat satu hari mengikuti jalur yang diimpor.',
+ 'mobileTrip.rtPlanOnDesktop':
+ 'Perencanaan dilakukan di desktop. TREK menghitung perjalanannya begitu satu hari punya dua tempat.',
+ 'mobileTrip.rtSearchOffline': 'Perlu koneksi: pencarian membaca rute di depan.',
+ 'mobileTrip.rtBehind': 'terlambat {time} dari rencana',
+ 'mobileTrip.rtStart': 'Mulai',
+ 'mobileTrip.rtStayScope':
+ 'Lama singgah melekat pada tempatnya, jadi ia terhitung di setiap hari perhentian ini direncanakan.',
+ 'mobileTrip.rtStayLess': '{count} menit lebih singkat',
+ 'mobileTrip.rtStayMore': '{count} menit lebih lama',
+ 'mobileTrip.rtNightDesktopOnly':
+ 'Memesan menginap di tempat ini dilakukan di perencana desktop. Di sini kamu hanya bisa menghapusnya.',
+ 'mobileTrip.rtReach': 'Sejauh apa',
+ 'mobileTrip.rtReachAhead': '{distance} ke depan',
+ 'mobileTrip.rtFromNext': 'Dari perhentian berikutnya',
+ 'mobileTrip.rtFromStart': 'Dari awal etape',
+ 'mobileTrip.rtNoneAhead': 'Tidak ada apa-apa di jalan di depan. Coba seluruh etape.',
+ 'mobileTrip.rtNoneOnStage': 'Tidak ada yang seperti itu di sepanjang etape ini.',
+ 'mobileTrip.rtTruncated':
+ '{count} ruas punya lebih banyak daripada yang muat dalam satu jawaban. Pilih lebih sedikit jenis untuk melihat sisanya.',
};
export default mobileTrip;
diff --git a/shared/src/i18n/it/dawarich.ts b/shared/src/i18n/it/dawarich.ts
index 7194634df..b54bf27f1 100644
--- a/shared/src/i18n/it/dawarich.ts
+++ b/shared/src/i18n/it/dawarich.ts
@@ -177,6 +177,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': 'a {km} km',
'dawarich.bucket.rule': 'Un desiderio è raggiunto entro {meters} m e dopo {minutes} minuti sul posto.',
+ 'dawarich.journey.dayStays.one': '1 sosta da Dawarich',
+ 'dawarich.journey.dayStays.other': '{count} soste da Dawarich',
};
export default dawarich;
diff --git a/shared/src/i18n/it/map.ts b/shared/src/i18n/it/map.ts
index 0ada52a73..eed483926 100644
--- a/shared/src/i18n/it/map.ts
+++ b/shared/src/i18n/it/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': 'Mostra tutto il viaggio',
'map.overview.hide': 'Nascondi tutto il viaggio',
'map.overview.total': 'Distanza totale',
+ 'map.attribution': 'Crediti della mappa',
};
export default map;
diff --git a/shared/src/i18n/it/mobileTrip.ts b/shared/src/i18n/it/mobileTrip.ts
index 797070110..58dbbb46d 100644
--- a/shared/src/i18n/it/mobileTrip.ts
+++ b/shared/src/i18n/it/mobileTrip.ts
@@ -47,5 +47,27 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': 'Prossimo',
'mobileTrip.viewDetails': 'Vedi dettagli',
'mobileTrip.transportsEmpty': 'Ancora nessun trasporto',
+ 'mobileTrip.rtInfoTitle': 'Dati del tragitto',
+ 'mobileTrip.rtDesktopNote':
+ 'Questi dati si impostano da computer, dove puoi anche confrontare percorsi alternativi e far seguire a un giorno una traccia importata.',
+ 'mobileTrip.rtPlanOnDesktop':
+ 'La pianificazione si fa da computer. TREK calcola il tragitto appena un giorno ha due luoghi.',
+ 'mobileTrip.rtSearchOffline': 'Serve una connessione: la ricerca legge il percorso che hai davanti.',
+ 'mobileTrip.rtBehind': '{time} di ritardo sul programma',
+ 'mobileTrip.rtStart': 'Inizio',
+ 'mobileTrip.rtStayScope':
+ 'La durata della sosta appartiene al luogo, quindi vale in ogni giorno in cui questa tappa è prevista.',
+ 'mobileTrip.rtStayLess': '{count} minuti in meno',
+ 'mobileTrip.rtStayMore': '{count} minuti in più',
+ 'mobileTrip.rtNightDesktopOnly':
+ 'Prenotare un pernottamento in questo luogo si fa nel pianificatore da computer. Qui puoi solo scartarlo.',
+ 'mobileTrip.rtReach': 'Fin dove',
+ 'mobileTrip.rtReachAhead': '{distance} davanti',
+ 'mobileTrip.rtFromNext': 'Dalla tua prossima sosta',
+ 'mobileTrip.rtFromStart': 'Dall’inizio della tappa',
+ 'mobileTrip.rtNoneAhead': 'Niente sulla strada davanti a te. Prova con tutta la tappa.',
+ 'mobileTrip.rtNoneOnStage': 'Niente del genere lungo questa tappa.',
+ 'mobileTrip.rtTruncated':
+ '{count} tratti avevano più di quanto stia in una risposta. Scegli meno tipi per vedere il resto.',
};
export default mobileTrip;
diff --git a/shared/src/i18n/ja/dawarich.ts b/shared/src/i18n/ja/dawarich.ts
index c14076f82..093ca4c16 100644
--- a/shared/src/i18n/ja/dawarich.ts
+++ b/shared/src/i18n/ja/dawarich.ts
@@ -178,6 +178,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': '{km} km 先',
'dawarich.bucket.rule': '{meters} m 以内に {minutes} 分以上滞在すると、願いがかなったとみなします。',
+ 'dawarich.journey.dayStays.one': 'Dawarich の滞在 1 件',
+ 'dawarich.journey.dayStays.other': 'Dawarich の滞在 {count} 件',
};
export default dawarich;
diff --git a/shared/src/i18n/ja/map.ts b/shared/src/i18n/ja/map.ts
index a5d7d3ca9..a4ee235d6 100644
--- a/shared/src/i18n/ja/map.ts
+++ b/shared/src/i18n/ja/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': '旅程全体を表示',
'map.overview.hide': '旅程全体を非表示',
'map.overview.total': '合計距離',
+ 'map.attribution': '地図のクレジット',
};
export default map;
diff --git a/shared/src/i18n/ja/mobileTrip.ts b/shared/src/i18n/ja/mobileTrip.ts
index dc6932a53..efae26766 100644
--- a/shared/src/i18n/ja/mobileTrip.ts
+++ b/shared/src/i18n/ja/mobileTrip.ts
@@ -47,5 +47,23 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': '次の予定',
'mobileTrip.viewDetails': '詳細を表示',
'mobileTrip.transportsEmpty': '移動手段はまだありません',
+ 'mobileTrip.rtInfoTitle': '走行データ',
+ 'mobileTrip.rtDesktopNote': 'これらの数値はデスクトップで設定します。デスクトップでは、別のルートを比べたり、読み込んだトラックにその日を沿わせたりもできます。',
+ 'mobileTrip.rtPlanOnDesktop': '計画はデスクトップで行います。1日に場所が2か所そろうと、TREKが走行を計算します。',
+ 'mobileTrip.rtSearchOffline': '接続が必要です:この検索は先のルートを読み取ります。',
+ 'mobileTrip.rtBehind': '予定より {time} 遅れ',
+ 'mobileTrip.rtStart': '開始',
+ 'mobileTrip.rtStayScope': '滞在時間は場所に紐づくため、この立ち寄り先を予定しているすべての日に適用されます。',
+ 'mobileTrip.rtStayLess': '{count} 分減らす',
+ 'mobileTrip.rtStayMore': '{count} 分増やす',
+ 'mobileTrip.rtNightDesktopOnly':
+ 'この場所に宿泊を設定できるのはデスクトップのプランナーです。ここでは取り消すことしかできません。',
+ 'mobileTrip.rtReach': 'どこまで',
+ 'mobileTrip.rtReachAhead': 'この先 {distance}',
+ 'mobileTrip.rtFromNext': '次の立ち寄り先から',
+ 'mobileTrip.rtFromStart': '区間の始まりから',
+ 'mobileTrip.rtNoneAhead': 'この先の道沿いには何もありません。区間全体で試してください。',
+ 'mobileTrip.rtNoneOnStage': 'この区間沿いにはそうした場所はありません。',
+ 'mobileTrip.rtTruncated': '{count} 区間は1回の答えに収まりきりませんでした。種類を減らすと残りも見られます。',
};
export default mobileTrip;
diff --git a/shared/src/i18n/ko/dawarich.ts b/shared/src/i18n/ko/dawarich.ts
index 5a7de299d..eff2104dd 100644
--- a/shared/src/i18n/ko/dawarich.ts
+++ b/shared/src/i18n/ko/dawarich.ts
@@ -173,6 +173,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': '{km} km 거리',
'dawarich.bucket.rule': '{meters} m 이내에서 {minutes}분 이상 머무르면 소원을 이룬 것으로 봅니다.',
+ 'dawarich.journey.dayStays.one': 'Dawarich 체류 1곳',
+ 'dawarich.journey.dayStays.other': 'Dawarich 체류 {count}곳',
};
export default dawarich;
diff --git a/shared/src/i18n/ko/map.ts b/shared/src/i18n/ko/map.ts
index c20e69a9e..585b5d433 100644
--- a/shared/src/i18n/ko/map.ts
+++ b/shared/src/i18n/ko/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': '전체 여행 보기',
'map.overview.hide': '전체 여행 숨기기',
'map.overview.total': '총 거리',
+ 'map.attribution': '지도 출처',
};
export default map;
diff --git a/shared/src/i18n/ko/mobileTrip.ts b/shared/src/i18n/ko/mobileTrip.ts
index b863b18ad..3b1a0796a 100644
--- a/shared/src/i18n/ko/mobileTrip.ts
+++ b/shared/src/i18n/ko/mobileTrip.ts
@@ -47,5 +47,23 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': '다음 일정',
'mobileTrip.viewDetails': '세부정보 보기',
'mobileTrip.transportsEmpty': '아직 교통편이 없습니다',
+ 'mobileTrip.rtInfoTitle': '주행 수치',
+ 'mobileTrip.rtDesktopNote': '이 수치는 데스크톱에서 설정합니다. 데스크톱에서는 다른 경로를 비교하고, 가져온 트랙을 따라가도록 하루를 맞출 수도 있습니다.',
+ 'mobileTrip.rtPlanOnDesktop': '계획은 데스크톱에서 세웁니다. 하루에 장소가 두 곳 생기면 TREK이 주행을 계산합니다.',
+ 'mobileTrip.rtSearchOffline': '연결이 필요합니다: 이 검색은 앞으로 갈 경로를 읽습니다.',
+ 'mobileTrip.rtBehind': '계획보다 {time} 늦음',
+ 'mobileTrip.rtStart': '시작',
+ 'mobileTrip.rtStayScope': '체류 시간은 장소에 속하므로, 이 경유지가 들어간 모든 날짜에 적용됩니다.',
+ 'mobileTrip.rtStayLess': '{count}분 줄이기',
+ 'mobileTrip.rtStayMore': '{count}분 늘리기',
+ 'mobileTrip.rtNightDesktopOnly':
+ '이 장소에 숙박을 잡는 것은 데스크톱 플래너에서만 됩니다. 여기에서는 취소만 할 수 있습니다.',
+ 'mobileTrip.rtReach': '어디까지',
+ 'mobileTrip.rtReachAhead': '앞으로 {distance}',
+ 'mobileTrip.rtFromNext': '다음 경유지부터',
+ 'mobileTrip.rtFromStart': '구간 시작부터',
+ 'mobileTrip.rtNoneAhead': '앞쪽 도로에는 아무것도 없습니다. 구간 전체로 찾아보세요.',
+ 'mobileTrip.rtNoneOnStage': '이 구간에는 그런 곳이 없습니다.',
+ 'mobileTrip.rtTruncated': '{count}개 구간은 한 번의 답에 담기지 않았습니다. 종류를 줄이면 나머지도 볼 수 있습니다.',
};
export default mobileTrip;
diff --git a/shared/src/i18n/nl/dawarich.ts b/shared/src/i18n/nl/dawarich.ts
index ae8595e4a..9790bfbfc 100644
--- a/shared/src/i18n/nl/dawarich.ts
+++ b/shared/src/i18n/nl/dawarich.ts
@@ -175,6 +175,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': '{km} km verderop',
'dawarich.bucket.rule': 'Een wens telt als bereikt binnen {meters} m en na {minutes} minuten ter plaatse.',
+ 'dawarich.journey.dayStays.one': '1 stop van Dawarich',
+ 'dawarich.journey.dayStays.other': '{count} stops van Dawarich',
};
export default dawarich;
diff --git a/shared/src/i18n/nl/map.ts b/shared/src/i18n/nl/map.ts
index 5083b1925..021eb524d 100644
--- a/shared/src/i18n/nl/map.ts
+++ b/shared/src/i18n/nl/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': 'Hele reis tonen',
'map.overview.hide': 'Hele reis verbergen',
'map.overview.total': 'Totale afstand',
+ 'map.attribution': 'Kaartvermeldingen',
};
export default map;
diff --git a/shared/src/i18n/nl/mobileTrip.ts b/shared/src/i18n/nl/mobileTrip.ts
index 56a225b66..8ef950223 100644
--- a/shared/src/i18n/nl/mobileTrip.ts
+++ b/shared/src/i18n/nl/mobileTrip.ts
@@ -47,5 +47,25 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': 'Volgende',
'mobileTrip.viewDetails': 'Details bekijken',
'mobileTrip.transportsEmpty': 'Nog geen transport',
+ 'mobileTrip.rtInfoTitle': 'Rijgegevens',
+ 'mobileTrip.rtDesktopNote':
+ 'Deze waarden stel je in op de desktop. Daar kun je ook routevarianten vergelijken en een dag een geïmporteerde track laten volgen.',
+ 'mobileTrip.rtPlanOnDesktop': 'Plannen doe je op de desktop. TREK berekent de rit zodra een dag twee plaatsen heeft.',
+ 'mobileTrip.rtSearchOffline': 'Vereist een verbinding: de zoekopdracht leest de route die voor je ligt.',
+ 'mobileTrip.rtBehind': '{time} achter op schema',
+ 'mobileTrip.rtStart': 'Start',
+ 'mobileTrip.rtStayScope': 'Het verblijf hoort bij de plaats en telt dus op elke dag waarop deze stop gepland staat.',
+ 'mobileTrip.rtStayLess': '{count} minuten minder',
+ 'mobileTrip.rtStayMore': '{count} minuten meer',
+ 'mobileTrip.rtNightDesktopOnly':
+ 'Een overnachting op deze plaats voeg je toe in de desktopplanner. Hier kun je die alleen verwijderen.',
+ 'mobileTrip.rtReach': 'Hoe ver',
+ 'mobileTrip.rtReachAhead': '{distance} vooruit',
+ 'mobileTrip.rtFromNext': 'Vanaf je volgende stop',
+ 'mobileTrip.rtFromStart': 'Vanaf het begin van de etappe',
+ 'mobileTrip.rtNoneAhead': 'Niets op de weg die voor je ligt. Probeer de hele etappe.',
+ 'mobileTrip.rtNoneOnStage': 'Niets van dat soort langs deze etappe.',
+ 'mobileTrip.rtTruncated':
+ '{count} stukken hadden meer dan in één antwoord past. Kies minder soorten om de rest te zien.',
};
export default mobileTrip;
diff --git a/shared/src/i18n/pl/dawarich.ts b/shared/src/i18n/pl/dawarich.ts
index 3b1dfffd0..078a9c1be 100644
--- a/shared/src/i18n/pl/dawarich.ts
+++ b/shared/src/i18n/pl/dawarich.ts
@@ -173,6 +173,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': '{km} km stąd',
'dawarich.bucket.rule': 'Marzenie uznaje się za spełnione w promieniu {meters} m i po {minutes} minutach na miejscu.',
+ 'dawarich.journey.dayStays.one': '1 postój z Dawarich',
+ 'dawarich.journey.dayStays.other': 'Postoje z Dawarich: {count}',
};
export default dawarich;
diff --git a/shared/src/i18n/pl/map.ts b/shared/src/i18n/pl/map.ts
index 59c40db28..4f1619a46 100644
--- a/shared/src/i18n/pl/map.ts
+++ b/shared/src/i18n/pl/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': 'Pokaż całą podróż',
'map.overview.hide': 'Ukryj całą podróż',
'map.overview.total': 'Łączny dystans',
+ 'map.attribution': 'Źródła mapy',
};
export default map;
diff --git a/shared/src/i18n/pl/mobileTrip.ts b/shared/src/i18n/pl/mobileTrip.ts
index bbe860f9e..f6783280d 100644
--- a/shared/src/i18n/pl/mobileTrip.ts
+++ b/shared/src/i18n/pl/mobileTrip.ts
@@ -47,5 +47,26 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': 'Następne',
'mobileTrip.viewDetails': 'Zobacz szczegóły',
'mobileTrip.transportsEmpty': 'Brak transportu',
+ 'mobileTrip.rtInfoTitle': 'Dane jazdy',
+ 'mobileTrip.rtDesktopNote':
+ 'Te dane ustawia się na komputerze, gdzie możesz też porównywać warianty trasy i sprawić, by dzień podążał za zaimportowanym śladem.',
+ 'mobileTrip.rtPlanOnDesktop': 'Planowanie odbywa się na komputerze. TREK wylicza przejazd, gdy dzień ma dwa miejsca.',
+ 'mobileTrip.rtSearchOffline': 'Wymaga połączenia: wyszukiwanie czyta trasę przed tobą.',
+ 'mobileTrip.rtBehind': '{time} opóźnienia względem planu',
+ 'mobileTrip.rtStart': 'Początek',
+ 'mobileTrip.rtStayScope':
+ 'Pobyt jest przypisany do miejsca, więc liczy się w każdym dniu, w którym zaplanowano ten przystanek.',
+ 'mobileTrip.rtStayLess': '{count} minut mniej',
+ 'mobileTrip.rtStayMore': '{count} minut więcej',
+ 'mobileTrip.rtNightDesktopOnly':
+ 'Nocleg w tym miejscu rezerwuje się w planerze na komputerze. Tutaj możesz go tylko odrzucić.',
+ 'mobileTrip.rtReach': 'Jak daleko',
+ 'mobileTrip.rtReachAhead': '{distance} przed tobą',
+ 'mobileTrip.rtFromNext': 'Od następnego przystanku',
+ 'mobileTrip.rtFromStart': 'Od początku etapu',
+ 'mobileTrip.rtNoneAhead': 'Na drodze przed tobą nic nie ma. Spróbuj całego etapu.',
+ 'mobileTrip.rtNoneOnStage': 'Na tym etapie nie ma nic takiego.',
+ 'mobileTrip.rtTruncated':
+ '{count} odcinków miało więcej, niż mieści się w jednej odpowiedzi. Wybierz mniej rodzajów, by zobaczyć resztę.',
};
export default mobileTrip;
diff --git a/shared/src/i18n/ru/dawarich.ts b/shared/src/i18n/ru/dawarich.ts
index 7668aed45..e28722fb0 100644
--- a/shared/src/i18n/ru/dawarich.ts
+++ b/shared/src/i18n/ru/dawarich.ts
@@ -173,6 +173,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': 'в {km} км',
'dawarich.bucket.rule': 'Желание считается исполненным в пределах {meters} м и после {minutes} минут на месте.',
+ 'dawarich.journey.dayStays.one': '1 остановка из Dawarich',
+ 'dawarich.journey.dayStays.other': 'Остановки из Dawarich: {count}',
};
export default dawarich;
diff --git a/shared/src/i18n/ru/map.ts b/shared/src/i18n/ru/map.ts
index a40c752a1..732143b2d 100644
--- a/shared/src/i18n/ru/map.ts
+++ b/shared/src/i18n/ru/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': 'Показать всю поездку',
'map.overview.hide': 'Скрыть всю поездку',
'map.overview.total': 'Общее расстояние',
+ 'map.attribution': 'Источники карты',
};
export default map;
diff --git a/shared/src/i18n/ru/mobileTrip.ts b/shared/src/i18n/ru/mobileTrip.ts
index 03981b805..1366be4cb 100644
--- a/shared/src/i18n/ru/mobileTrip.ts
+++ b/shared/src/i18n/ru/mobileTrip.ts
@@ -47,5 +47,27 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': 'Далее',
'mobileTrip.viewDetails': 'Просмотреть детали',
'mobileTrip.transportsEmpty': 'Пока нет транспорта',
+ 'mobileTrip.rtInfoTitle': 'Данные о вождении',
+ 'mobileTrip.rtDesktopNote':
+ 'Эти данные задаются на компьютере: там же можно сравнивать другие маршруты и провести день по импортированному треку.',
+ 'mobileTrip.rtPlanOnDesktop':
+ 'Планирование происходит на компьютере. TREK рассчитает маршрут, как только в дне окажется два места.',
+ 'mobileTrip.rtSearchOffline': 'Нужна сеть: поиск считывает маршрут впереди.',
+ 'mobileTrip.rtBehind': 'на {time} позже плана',
+ 'mobileTrip.rtStart': 'Начало',
+ 'mobileTrip.rtStayScope':
+ 'Стоянка привязана к месту, поэтому она учитывается в каждый день, на который запланирована эта остановка.',
+ 'mobileTrip.rtStayLess': 'на {count} минут меньше',
+ 'mobileTrip.rtStayMore': 'на {count} минут больше',
+ 'mobileTrip.rtNightDesktopOnly':
+ 'Забронировать ночёвку в этом месте можно в планировщике на компьютере. Здесь её можно только убрать.',
+ 'mobileTrip.rtReach': 'Насколько далеко',
+ 'mobileTrip.rtReachAhead': '{distance} впереди',
+ 'mobileTrip.rtFromNext': 'От следующей остановки',
+ 'mobileTrip.rtFromStart': 'От начала этапа',
+ 'mobileTrip.rtNoneAhead': 'На дороге впереди ничего нет. Попробуйте весь этап.',
+ 'mobileTrip.rtNoneOnStage': 'На этом этапе ничего такого нет.',
+ 'mobileTrip.rtTruncated':
+ 'На {count} участках нашлось больше, чем помещается в один ответ. Выберите меньше видов, чтобы увидеть остальное.',
};
export default mobileTrip;
diff --git a/shared/src/i18n/sv/dawarich.ts b/shared/src/i18n/sv/dawarich.ts
index 3b223d381..f15bbe445 100644
--- a/shared/src/i18n/sv/dawarich.ts
+++ b/shared/src/i18n/sv/dawarich.ts
@@ -173,6 +173,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': '{km} km bort',
'dawarich.bucket.rule': 'En önskning räknas som uppfylld inom {meters} m och efter {minutes} minuter på plats.',
+ 'dawarich.journey.dayStays.one': '1 stopp från Dawarich',
+ 'dawarich.journey.dayStays.other': '{count} stopp från Dawarich',
};
export default dawarich;
diff --git a/shared/src/i18n/sv/map.ts b/shared/src/i18n/sv/map.ts
index 37130e560..6392be254 100644
--- a/shared/src/i18n/sv/map.ts
+++ b/shared/src/i18n/sv/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': 'Visa hela resan',
'map.overview.hide': 'Dölj hela resan',
'map.overview.total': 'Total sträcka',
+ 'map.attribution': 'Kartkällor',
};
export default map;
diff --git a/shared/src/i18n/sv/mobileTrip.ts b/shared/src/i18n/sv/mobileTrip.ts
index 0914b8545..8fa10fa1a 100644
--- a/shared/src/i18n/sv/mobileTrip.ts
+++ b/shared/src/i18n/sv/mobileTrip.ts
@@ -47,5 +47,25 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': 'Härnäst',
'mobileTrip.viewDetails': 'Visa detaljer',
'mobileTrip.transportsEmpty': 'Ingen transport än',
+ 'mobileTrip.rtInfoTitle': 'Kördata',
+ 'mobileTrip.rtDesktopNote':
+ 'De här värdena ställer du in på datorn. Där kan du också jämföra alternativa vägar och låta en dag följa ett importerat spår.',
+ 'mobileTrip.rtPlanOnDesktop': 'Planeringen sker på datorn. TREK räknar ut körningen så snart en dag har två platser.',
+ 'mobileTrip.rtSearchOffline': 'Kräver anslutning: sökningen läser rutten som ligger framför dig.',
+ 'mobileTrip.rtBehind': '{time} efter planen',
+ 'mobileTrip.rtStart': 'Start',
+ 'mobileTrip.rtStayScope': 'Vistelsen hör till platsen och räknas därför varje dag som det här stoppet är inplanerat.',
+ 'mobileTrip.rtStayLess': '{count} minuter mindre',
+ 'mobileTrip.rtStayMore': '{count} minuter mer',
+ 'mobileTrip.rtNightDesktopOnly':
+ 'En övernattning på den här platsen lägger du till i planeraren på datorn. Här kan du bara ta bort den.',
+ 'mobileTrip.rtReach': 'Hur långt',
+ 'mobileTrip.rtReachAhead': '{distance} framåt',
+ 'mobileTrip.rtFromNext': 'Från ditt nästa stopp',
+ 'mobileTrip.rtFromStart': 'Från etappens början',
+ 'mobileTrip.rtNoneAhead': 'Inget på vägen framför dig. Prova hela etappen.',
+ 'mobileTrip.rtNoneOnStage': 'Inget sådant längs den här etappen.',
+ 'mobileTrip.rtTruncated':
+ '{count} sträckor hade mer än vad som får plats i ett svar. Välj färre sorter för att se resten.',
};
export default mobileTrip;
diff --git a/shared/src/i18n/tr/dawarich.ts b/shared/src/i18n/tr/dawarich.ts
index 90572524a..78e59e83e 100644
--- a/shared/src/i18n/tr/dawarich.ts
+++ b/shared/src/i18n/tr/dawarich.ts
@@ -176,6 +176,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': '{km} km uzakta',
'dawarich.bucket.rule': 'Bir dilek {meters} m yakınlıkta ve yerinde {minutes} dakika sonra ulaşılmış sayılır.',
+ 'dawarich.journey.dayStays.one': "Dawarich'ten 1 durak",
+ 'dawarich.journey.dayStays.other': "Dawarich'ten {count} durak",
};
export default dawarich;
diff --git a/shared/src/i18n/tr/map.ts b/shared/src/i18n/tr/map.ts
index d317d6f94..74b7c22d2 100644
--- a/shared/src/i18n/tr/map.ts
+++ b/shared/src/i18n/tr/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': 'Tüm geziyi göster',
'map.overview.hide': 'Tüm geziyi gizle',
'map.overview.total': 'Toplam mesafe',
+ 'map.attribution': 'Harita kaynakları',
};
export default map;
diff --git a/shared/src/i18n/tr/mobileTrip.ts b/shared/src/i18n/tr/mobileTrip.ts
index 22e3d99a4..43bae9e76 100644
--- a/shared/src/i18n/tr/mobileTrip.ts
+++ b/shared/src/i18n/tr/mobileTrip.ts
@@ -47,5 +47,25 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': 'Sırada',
'mobileTrip.viewDetails': 'Ayrıntıları görüntüle',
'mobileTrip.transportsEmpty': 'Henüz ulaşım yok',
+ 'mobileTrip.rtInfoTitle': 'Sürüş değerleri',
+ 'mobileTrip.rtDesktopNote':
+ 'Bu değerler masaüstünde ayarlanır; orada başka yolları karşılaştırabilir ve bir günü içe aktarılmış bir izi takip ettirebilirsiniz.',
+ 'mobileTrip.rtPlanOnDesktop': 'Planlama masaüstünde yapılır. Bir günde iki yer olduğunda TREK sürüşü hesaplar.',
+ 'mobileTrip.rtSearchOffline': 'Bağlantı gerekir: arama, ileride kalan rotayı okur.',
+ 'mobileTrip.rtBehind': 'plandan {time} geride',
+ 'mobileTrip.rtStart': 'Başlangıç',
+ 'mobileTrip.rtStayScope': 'Bu süre yere aittir, bu yüzden bu durağın planlandığı her gün için geçerlidir.',
+ 'mobileTrip.rtStayLess': '{count} dakika daha az',
+ 'mobileTrip.rtStayMore': '{count} dakika daha fazla',
+ 'mobileTrip.rtNightDesktopOnly':
+ 'Bu yerde konaklama masaüstü planlayıcıda ayarlanır. Burada yalnızca kaldırabilirsiniz.',
+ 'mobileTrip.rtReach': 'Ne kadar uzağa',
+ 'mobileTrip.rtReachAhead': '{distance} ileride',
+ 'mobileTrip.rtFromNext': 'Bir sonraki durağınızdan itibaren',
+ 'mobileTrip.rtFromStart': 'Etabın başından itibaren',
+ 'mobileTrip.rtNoneAhead': 'İleride yol üzerinde bir şey yok. Tüm etabı deneyin.',
+ 'mobileTrip.rtNoneOnStage': 'Bu etap boyunca bu türden bir şey yok.',
+ 'mobileTrip.rtTruncated':
+ '{count} kesimde tek bir yanıta sığandan fazlası vardı. Geri kalanı görmek için daha az tür seçin.',
};
export default mobileTrip;
diff --git a/shared/src/i18n/uk/dawarich.ts b/shared/src/i18n/uk/dawarich.ts
index e782b68af..833654444 100644
--- a/shared/src/i18n/uk/dawarich.ts
+++ b/shared/src/i18n/uk/dawarich.ts
@@ -173,6 +173,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': 'за {km} км',
'dawarich.bucket.rule': 'Бажання вважається здійсненим у межах {meters} м і після {minutes} хвилин на місці.',
+ 'dawarich.journey.dayStays.one': '1 зупинка з Dawarich',
+ 'dawarich.journey.dayStays.other': 'Зупинки з Dawarich: {count}',
};
export default dawarich;
diff --git a/shared/src/i18n/uk/map.ts b/shared/src/i18n/uk/map.ts
index 6dc038eb1..fed8d2728 100644
--- a/shared/src/i18n/uk/map.ts
+++ b/shared/src/i18n/uk/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': 'Показати всю подорож',
'map.overview.hide': 'Сховати всю подорож',
'map.overview.total': 'Загальна відстань',
+ 'map.attribution': 'Джерела карти',
};
export default map;
diff --git a/shared/src/i18n/uk/mobileTrip.ts b/shared/src/i18n/uk/mobileTrip.ts
index de3a3491f..4dfff785a 100644
--- a/shared/src/i18n/uk/mobileTrip.ts
+++ b/shared/src/i18n/uk/mobileTrip.ts
@@ -47,5 +47,27 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': 'Далі',
'mobileTrip.viewDetails': 'Переглянути деталі',
'mobileTrip.transportsEmpty': 'Поки немає транспорту',
+ 'mobileTrip.rtInfoTitle': 'Дані про водіння',
+ 'mobileTrip.rtDesktopNote':
+ 'Ці дані задаються на комп’ютері: там само можна порівнювати інші маршрути та провести день за імпортованим треком.',
+ 'mobileTrip.rtPlanOnDesktop':
+ 'Планування відбувається на комп’ютері. TREK розрахує маршрут, щойно в дні буде два місця.',
+ 'mobileTrip.rtSearchOffline': 'Потрібне з’єднання: пошук зчитує маршрут попереду.',
+ 'mobileTrip.rtBehind': 'на {time} пізніше плану',
+ 'mobileTrip.rtStart': 'Початок',
+ 'mobileTrip.rtStayScope':
+ 'Стоянка належить місцю, тому вона враховується в кожен день, на який заплановано цю зупинку.',
+ 'mobileTrip.rtStayLess': 'на {count} хвилин менше',
+ 'mobileTrip.rtStayMore': 'на {count} хвилин більше',
+ 'mobileTrip.rtNightDesktopOnly':
+ 'Забронювати ночівлю в цьому місці можна в планувальнику на комп’ютері. Тут її можна лише прибрати.',
+ 'mobileTrip.rtReach': 'Наскільки далеко',
+ 'mobileTrip.rtReachAhead': '{distance} попереду',
+ 'mobileTrip.rtFromNext': 'Від наступної зупинки',
+ 'mobileTrip.rtFromStart': 'Від початку етапу',
+ 'mobileTrip.rtNoneAhead': 'На дорозі попереду нічого немає. Спробуйте весь етап.',
+ 'mobileTrip.rtNoneOnStage': 'На цьому етапі нічого такого немає.',
+ 'mobileTrip.rtTruncated':
+ 'На {count} ділянках знайшлося більше, ніж уміщується в одну відповідь. Виберіть менше видів, щоб побачити решту.',
};
export default mobileTrip;
diff --git a/shared/src/i18n/vi/dawarich.ts b/shared/src/i18n/vi/dawarich.ts
index 7e71521c6..c0319cf27 100644
--- a/shared/src/i18n/vi/dawarich.ts
+++ b/shared/src/i18n/vi/dawarich.ts
@@ -173,6 +173,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': 'cách {km} km',
'dawarich.bucket.rule': 'Một điều ước được tính là đã đến khi trong vòng {meters} m và sau {minutes} phút tại chỗ.',
+ 'dawarich.journey.dayStays.one': '1 điểm dừng từ Dawarich',
+ 'dawarich.journey.dayStays.other': '{count} điểm dừng từ Dawarich',
};
export default dawarich;
diff --git a/shared/src/i18n/vi/map.ts b/shared/src/i18n/vi/map.ts
index 081fe6c22..6c7bf8dea 100644
--- a/shared/src/i18n/vi/map.ts
+++ b/shared/src/i18n/vi/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': 'Hiện toàn bộ chuyến đi',
'map.overview.hide': 'Ẩn toàn bộ chuyến đi',
'map.overview.total': 'Tổng quãng đường',
+ 'map.attribution': 'Nguồn bản đồ',
};
export default map;
diff --git a/shared/src/i18n/vi/mobileTrip.ts b/shared/src/i18n/vi/mobileTrip.ts
index 12588df6b..f1ceccd01 100644
--- a/shared/src/i18n/vi/mobileTrip.ts
+++ b/shared/src/i18n/vi/mobileTrip.ts
@@ -47,5 +47,27 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': 'Tiếp theo',
'mobileTrip.viewDetails': 'Xem chi tiết',
'mobileTrip.transportsEmpty': 'Chưa có phương tiện di chuyển',
+ 'mobileTrip.rtInfoTitle': 'Số liệu lái xe',
+ 'mobileTrip.rtDesktopNote':
+ 'Các số liệu này được đặt trên máy tính, nơi bạn cũng có thể so sánh các lộ trình khác và cho một ngày đi theo tuyến đã nhập.',
+ 'mobileTrip.rtPlanOnDesktop':
+ 'Việc lên kế hoạch diễn ra trên máy tính. TREK tính chặng lái xe ngay khi một ngày có hai địa điểm.',
+ 'mobileTrip.rtSearchOffline': 'Cần có kết nối: việc tìm kiếm đọc lộ trình phía trước.',
+ 'mobileTrip.rtBehind': 'chậm {time} so với kế hoạch',
+ 'mobileTrip.rtStart': 'Bắt đầu',
+ 'mobileTrip.rtStayScope':
+ 'Thời gian dừng thuộc về địa điểm, nên nó được tính vào mọi ngày có điểm dừng này trong kế hoạch.',
+ 'mobileTrip.rtStayLess': 'ít hơn {count} phút',
+ 'mobileTrip.rtStayMore': 'nhiều hơn {count} phút',
+ 'mobileTrip.rtNightDesktopOnly':
+ 'Việc đặt nghỉ đêm tại địa điểm này được thực hiện trong trình lập kế hoạch trên máy tính. Ở đây bạn chỉ có thể bỏ nó đi.',
+ 'mobileTrip.rtReach': 'Xa đến đâu',
+ 'mobileTrip.rtReachAhead': '{distance} phía trước',
+ 'mobileTrip.rtFromNext': 'Từ điểm dừng kế tiếp',
+ 'mobileTrip.rtFromStart': 'Từ đầu chặng',
+ 'mobileTrip.rtNoneAhead': 'Không có gì trên đường phía trước. Thử cả chặng xem sao.',
+ 'mobileTrip.rtNoneOnStage': 'Không có gì thuộc loại đó dọc chặng này.',
+ 'mobileTrip.rtTruncated':
+ '{count} đoạn có nhiều hơn mức vừa trong một câu trả lời. Chọn ít loại hơn để xem phần còn lại.',
};
export default mobileTrip;
diff --git a/shared/src/i18n/zh-TW/dawarich.ts b/shared/src/i18n/zh-TW/dawarich.ts
index 15193ca61..0cf112de1 100644
--- a/shared/src/i18n/zh-TW/dawarich.ts
+++ b/shared/src/i18n/zh-TW/dawarich.ts
@@ -173,6 +173,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': '{km} 公里外',
'dawarich.bucket.rule': '在 {meters} 公尺內停留 {minutes} 分鐘以上,才算實現心願。',
+ 'dawarich.journey.dayStays.one': '來自 Dawarich 的 1 個停留',
+ 'dawarich.journey.dayStays.other': '來自 Dawarich 的 {count} 個停留',
};
export default dawarich;
diff --git a/shared/src/i18n/zh-TW/map.ts b/shared/src/i18n/zh-TW/map.ts
index d5446d5f6..e92a8ea71 100644
--- a/shared/src/i18n/zh-TW/map.ts
+++ b/shared/src/i18n/zh-TW/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': '顯示整趟行程',
'map.overview.hide': '隱藏整趟行程',
'map.overview.total': '總距離',
+ 'map.attribution': '地圖來源',
};
export default map;
diff --git a/shared/src/i18n/zh-TW/mobileTrip.ts b/shared/src/i18n/zh-TW/mobileTrip.ts
index 5b02fdef6..30fb42516 100644
--- a/shared/src/i18n/zh-TW/mobileTrip.ts
+++ b/shared/src/i18n/zh-TW/mobileTrip.ts
@@ -47,5 +47,22 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': '接下來',
'mobileTrip.viewDetails': '查看詳情',
'mobileTrip.transportsEmpty': '暫無交通安排',
+ 'mobileTrip.rtInfoTitle': '駕駛數據',
+ 'mobileTrip.rtDesktopNote': '這些數據在電腦上設定,在那裡也可以比較其他路線,以及讓某一天沿匯入的軌跡行駛。',
+ 'mobileTrip.rtPlanOnDesktop': '規劃在電腦上進行。當一天有兩個地點時,TREK 就會算出車程。',
+ 'mobileTrip.rtSearchOffline': '需要連線:搜尋會讀取前方的路線。',
+ 'mobileTrip.rtBehind': '比計畫晚 {time}',
+ 'mobileTrip.rtStart': '開始',
+ 'mobileTrip.rtStayScope': '停留時間屬於該地點,因此這個停靠點排在哪一天,就會計入那一天。',
+ 'mobileTrip.rtStayLess': '少 {count} 分鐘',
+ 'mobileTrip.rtStayMore': '多 {count} 分鐘',
+ 'mobileTrip.rtNightDesktopOnly': '在這個地點安排過夜住宿要在電腦版的行程規劃中進行。這裡只能把它移除。',
+ 'mobileTrip.rtReach': '找多遠',
+ 'mobileTrip.rtReachAhead': '前方 {distance}',
+ 'mobileTrip.rtFromNext': '從下一個停靠點起',
+ 'mobileTrip.rtFromStart': '從本段起點起',
+ 'mobileTrip.rtNoneAhead': '前方路上沒有找到。試試整段。',
+ 'mobileTrip.rtNoneOnStage': '本段沿途沒有這類地點。',
+ 'mobileTrip.rtTruncated': '{count} 段路的結果超出一次回答能容納的量。少選幾類就能看到其餘的。',
};
export default mobileTrip;
diff --git a/shared/src/i18n/zh/dawarich.ts b/shared/src/i18n/zh/dawarich.ts
index 0ad930c11..0def059f4 100644
--- a/shared/src/i18n/zh/dawarich.ts
+++ b/shared/src/i18n/zh/dawarich.ts
@@ -173,6 +173,8 @@ const dawarich: TranslationStrings = {
'dawarich.bucket.kilometersAway': '{km} 公里外',
'dawarich.bucket.rule': '在 {meters} 米以内停留 {minutes} 分钟以上,才算实现心愿。',
+ 'dawarich.journey.dayStays.one': '来自 Dawarich 的 1 个停留',
+ 'dawarich.journey.dayStays.other': '来自 Dawarich 的 {count} 个停留',
};
export default dawarich;
diff --git a/shared/src/i18n/zh/map.ts b/shared/src/i18n/zh/map.ts
index 32dbf24e4..f20075b67 100644
--- a/shared/src/i18n/zh/map.ts
+++ b/shared/src/i18n/zh/map.ts
@@ -25,5 +25,6 @@ const map: TranslationStrings = {
'map.overview.show': '显示整个行程',
'map.overview.hide': '隐藏整个行程',
'map.overview.total': '总距离',
+ 'map.attribution': '地图来源',
};
export default map;
diff --git a/shared/src/i18n/zh/mobileTrip.ts b/shared/src/i18n/zh/mobileTrip.ts
index b22513a79..38425cb3c 100644
--- a/shared/src/i18n/zh/mobileTrip.ts
+++ b/shared/src/i18n/zh/mobileTrip.ts
@@ -47,5 +47,22 @@ const mobileTrip: TranslationStrings = {
'mobileTrip.upNext': '接下来',
'mobileTrip.viewDetails': '查看详情',
'mobileTrip.transportsEmpty': '暂无交通安排',
+ 'mobileTrip.rtInfoTitle': '驾驶数据',
+ 'mobileTrip.rtDesktopNote': '这些数据在桌面端设置。在桌面端还可以比较其他路线走法,并让某一天沿导入的轨迹行驶。',
+ 'mobileTrip.rtPlanOnDesktop': '规划在桌面端进行。一天里有了两个地点,TREK 就会算出这段车程。',
+ 'mobileTrip.rtSearchOffline': '需要联网:搜索会读取前方的路线。',
+ 'mobileTrip.rtBehind': '比计划晚 {time}',
+ 'mobileTrip.rtStart': '开始',
+ 'mobileTrip.rtStayScope': '停留时间属于这个地点,因此在安排了该停靠点的每一天都会生效。',
+ 'mobileTrip.rtStayLess': '减少 {count} 分钟',
+ 'mobileTrip.rtStayMore': '增加 {count} 分钟',
+ 'mobileTrip.rtNightDesktopOnly': '在这个地点安排过夜需要在桌面端的规划器中进行,这里只能放弃。',
+ 'mobileTrip.rtReach': '找多远',
+ 'mobileTrip.rtReachAhead': '前方 {distance}',
+ 'mobileTrip.rtFromNext': '从下一个停靠点起',
+ 'mobileTrip.rtFromStart': '从本段起点起',
+ 'mobileTrip.rtNoneAhead': '前方路上没有找到。试试整段。',
+ 'mobileTrip.rtNoneOnStage': '本段沿途没有这类地点。',
+ 'mobileTrip.rtTruncated': '{count} 段路的结果超出一次回答能装下的量。少选几类就能看到其余的。',
};
export default mobileTrip;
diff --git a/shared/src/roadtrip/assemble.spec.ts b/shared/src/roadtrip/assemble.spec.ts
index c2a8a90a0..decd3447c 100644
--- a/shared/src/roadtrip/assemble.spec.ts
+++ b/shared/src/roadtrip/assemble.spec.ts
@@ -145,6 +145,39 @@ describe('assembleRoadtrip connected days', () => {
});
}
+ /** The same two days, driven under an 08:00 to 20:00 window, which builds the nights. */
+ function assembleWindowedTwoDays() {
+ const first = [stop({ ownerIndex: 0 }), stop({ ownerIndex: 1 }), stop({ ownerIndex: 2 })];
+ const second = [
+ stop({ ownerDayId: 2, ownerIndex: 0, assignmentId: 300, placeId: 400, lat: 60 }),
+ stop({ ownerDayId: 2, ownerIndex: 1, assignmentId: 301, placeId: 401, lat: 61 }),
+ ];
+ const allLegs: Record = {};
+ for (const run of [first, second, [first[2]!, second[0]!]]) {
+ run.slice(0, -1).forEach((from, i) => {
+ allLegs[legKey(from, run[i + 1]!)] = lineFrom(from, run[i + 1]!);
+ });
+ }
+ return assembleRoadtrip({
+ plan: [
+ { dayId: 1, dayNumber: 1, date: '2026-06-01', title: null, stops: first },
+ { dayId: 2, dayNumber: 2, date: '2026-06-02', title: null, stops: second },
+ ],
+ quietDays: [],
+ window: { start: 8 * 60, end: 20 * 60, endMode: 'time' } as never,
+ distanceUnit: 'metric',
+ allLegs,
+ snapByDay: {},
+ missedByDay: {},
+ loading: false,
+ limits: { rangeKm: null, legMinutes: null, dayMinutes: null },
+ vehicleKind: null,
+ connectDays: false,
+ boundaries: [],
+ labels: { start: 'start', end: 'end' },
+ });
+ }
+
it('ROADTRIP-ASSEMBLE-004: the drive drawn at the head of a connected day names the stop it left from', () => {
const routes = assembleTwoDays(true);
const [first, second] = routes.days;
@@ -162,4 +195,40 @@ describe('assembleRoadtrip connected days', () => {
expect(routes.days[1]!.arrivingFrom).toBeUndefined();
expect(routes.days[1]!.geometry[0]).toEqual([60, 10]);
});
+
+ it('ROADTRIP-ASSEMBLE-006: that drive is marked as the connection it is, in the colour of the day it leaves', () => {
+ const routes = assembleTwoDays(true);
+
+ // Day 1 drives two of its own legs and then on into day 2; day 2 drives one.
+ expect(routes.lineDays).toEqual([1, 1, 1, 2]);
+ expect(routes.lines).toHaveLength(routes.lineJoins.length);
+ // The third line is drawn as day 1 but runs into day 2, and only it is a join. A
+ // surface showing one day needs that apart from the day number, which says day 1 for
+ // both the day's own legs and for the drive leading off it.
+ expect(routes.lineJoins).toEqual([false, false, true, false]);
+ });
+
+ it('ROADTRIP-ASSEMBLE-007: with the days unconnected there is no join to mark', () => {
+ const routes = assembleTwoDays(false);
+
+ expect(routes.lineDays).toEqual([1, 1, 2]);
+ expect(routes.lineJoins).toEqual([false, false, false]);
+ });
+
+ it('ROADTRIP-ASSEMBLE-008: with a day window the connection runs through the night stop, and is marked there', () => {
+ // A window builds the days itself: day 2 opens on an automatic night standing where
+ // day 1 stopped, and its first leg is the drive on from there. That leg is the SAME
+ // connection `connectDays` draws without a window, but it arrives as one of day 2's
+ // own legs, under day 2's number, and `inboundAt` is switched off entirely. Unmarked,
+ // a surface showing one day had no way to tell it from a drive within the day, and the
+ // phone drew the whole way back to yesterday's last stop on today's map.
+ const routes = assembleWindowedTwoDays();
+ const second = routes.days.find((d) => d.dayNumber === 2)!;
+
+ expect(second.stops[0]!.automaticNight?.phase).toBe('start');
+ // Day 1 drives its own two legs; day 2 opens with the drive on from the night and then
+ // drives its own. Only that first one of day 2's is the connection.
+ expect(routes.lineDays).toEqual([1, 1, 2, 2]);
+ expect(routes.lineJoins).toEqual([false, false, true, false]);
+ });
});
diff --git a/shared/src/roadtrip/assemble.ts b/shared/src/roadtrip/assemble.ts
index f2003d9ac..fc2754507 100644
--- a/shared/src/roadtrip/assemble.ts
+++ b/shared/src/roadtrip/assemble.ts
@@ -99,6 +99,9 @@ export function assembleRoadtrip({
const lines: [number, number][][] = [];
const lineDays: number[] = [];
+ // Parallel to `lines`: true where the line is the drive into the NEXT day, drawn in the
+ // leaving day's colour. See `lineJoins` on RoadtripRoutes.
+ const lineJoins: boolean[] = [];
const segments: RouteSegment[] = [];
const accessLines: RoadtripRoutes['accessLines'] = [];
@@ -134,6 +137,10 @@ export function assembleRoadtrip({
if (inbound.line.length > 1) {
lines.push(inbound.line);
lineDays.push(inbound.drawnAs);
+ // A spill carries its own `fromDayNumber` and a joined day the number of the day
+ // it left: either way, a line drawn as a day other than the one it runs in is
+ // the connection into this one.
+ lineJoins.push(inbound.drawnAs !== chain.dayNumber);
}
if (inbound.seg) segments.push(inbound.seg);
}
@@ -142,6 +149,12 @@ export function assembleRoadtrip({
if (leg.line.length > 1) {
lines.push(leg.line);
lineDays.push(chain.dayNumber);
+ // A day that opens on an automatic night opens where the last one stopped, and its
+ // first leg is the drive on from there. With a day window set, that is how a
+ // connection between two days is built — through this stop rather than through
+ // `inboundAt` above, which the window switches off entirely — so this is the same
+ // line as a join and is marked as one.
+ lineJoins.push(chain.stops[i]?.automaticNight?.phase === 'start');
}
segments.push(leg.seg);
}
@@ -288,6 +301,7 @@ export function assembleRoadtrip({
days: drives,
lines,
lineDays,
+ lineJoins,
segments,
accessLines,
vias: out.flatMap((d) => d.legVias.flat()),
diff --git a/shared/src/roadtrip/planning-types.ts b/shared/src/roadtrip/planning-types.ts
index 20ead9100..959923921 100644
--- a/shared/src/roadtrip/planning-types.ts
+++ b/shared/src/roadtrip/planning-types.ts
@@ -175,6 +175,18 @@ export interface RoadtripRoutes {
lineDays: number[];
+ /**
+ * Which of `lines` is the drive INTO the following day rather than a drive within the
+ * day it is drawn as, parallel to `lines` and `lineDays`.
+ *
+ * With "connect the days" on, the leg from one day's last stop to the next day's first
+ * is drawn in the colour of the day it leaves, so on a map showing the whole drive it
+ * reads as that day continuing. A surface showing ONE day has to tell the two apart:
+ * the connection leads off the day on screen and belongs to the next one, and drawn
+ * there it is a line to a place that day never visits.
+ */
+ lineJoins: boolean[];
+
accessLines: AccessSpur[];
vias: RouteVia[];