feat(roadtrip): share trip preferences and improve service stops

This commit is contained in:
Maurice
2026-09-12 00:24:45 +02:00
parent dd6ad31ab9
commit b773faff70
72 changed files with 1136 additions and 375 deletions
+1 -1
View File
@@ -18,7 +18,7 @@ export default function ClusteredPois({ pois, enabled, onPoiClick, children }: {
map.on('zoomend', update)
return () => { map.off('zoomend', update) }
}, [map])
const groups = useMemo(() => enabled ? clusterPois(pois, poi => map.latLngToContainerPoint([poi.lat, poi.lng])) : [], [pois, enabled, map, zoom])
const groups = useMemo(() => enabled ? clusterPois(pois, poi => map.latLngToContainerPoint([poi.lat, poi.lng]), zoom) : [], [pois, enabled, map, zoom])
const markers = new Map(pois.map((poi, index) => [poi.osm_id, children[index]]))
if (!enabled) return <>{children}</>
return <>{groups.map(group => {
@@ -1391,6 +1391,7 @@ describe('MapViewGL', () => {
it('clusters roadtrip stations and zooms before offering overlapping stations individually', async () => {
loadOnAttach()
vi.mocked(glMap.getZoom).mockReturnValue(8)
const poi: Poi = {
osm_id: 'n1', name: 'Station A', lat: 48.854, lng: 2.332, category: 'charging_station',
poi_type: 'charging_station', address: null, website: null, phone: null,
@@ -1411,6 +1412,7 @@ describe('MapViewGL', () => {
const list = calls[calls.length - 1][0]
act(() => { list.querySelectorAll('button')[1].click() })
expect(onPoiClick).toHaveBeenCalledWith(other)
vi.mocked(glMap.getZoom).mockReturnValue(10)
})
it('FE-COMP-MAPVIEWGL-043: plugin markers render as tone dots with a text-only popup', async () => {
+1 -1
View File
@@ -1840,7 +1840,7 @@ export function MapViewGL({
poiMarkersRef.current = []
poiCleanupRef.current.forEach(off => off())
poiCleanupRef.current = []
const groups = clusterLoosely ? clusterPois(pois, poi => map.project([poi.lng, poi.lat])) : pois.map(poi => ({ pois: [poi], lat: poi.lat, lng: poi.lng }))
const groups = clusterLoosely ? clusterPois(pois, poi => map.project([poi.lng, poi.lat]), map.getZoom()) : pois.map(poi => ({ pois: [poi], lat: poi.lat, lng: poi.lng }))
for (const group of groups) {
if (group.pois.length > 1) {
const el = document.createElement('button')
@@ -10,6 +10,12 @@ const station = (id: string, lng: number): Poi => ({
const project = (poi: Poi) => ({ x: poi.lng, y: poi.lat })
describe('station clusters', () => {
it('only clusters in the distant overview, even for coincident stations', () => {
const pois = [station('a', 1), station('b', 1)]
expect(clusterPois(pois, project, 8)).toHaveLength(1)
expect(clusterPois(pois, project, 9)).toHaveLength(2)
expect(clusterPois(pois, project, 14)).toHaveLength(2)
})
it('groups across grid edges, counts unique stations and preserves the originals', () => {
const a = station('a', 47), b = station('b', 49), c = station('c', 150)
const groups = clusterPois([c, b, a, a], project)
@@ -41,3 +47,9 @@ describe('station clusters', () => {
expect(select).toHaveBeenCalledWith(poi)
})
})
it('combines nearby small groups into one overview cluster', () => {
const pois = [station('a', 0), station('b', 3), station('c', 20), station('d', 23), station('e', 40), station('f', 43)]
expect(clusterPois(pois, project, 8).map(group => group.pois.length)).toEqual([6])
expect(clusterPois(pois, project, 9)).toHaveLength(6)
})
+3 -1
View File
@@ -1,13 +1,15 @@
import type { Poi } from './poiCategories'
export const POI_CLUSTER_RADIUS = 48
export const POI_CLUSTER_MAX_ZOOM = 8
export const POI_CLUSTER_DETAIL_ZOOM = 18
export interface PoiCluster { pois: Poi[]; lat: number; lng: number }
export function clusterPois(pois: Poi[], project: (poi: Poi) => { x: number; y: number }): PoiCluster[] {
export function clusterPois(pois: Poi[], project: (poi: Poi) => { x: number; y: number }, zoom = 0): PoiCluster[] {
const groups: (PoiCluster & { x: number; y: number })[] = []
const cells = new Map<string, number[]>()
const unique = new Map(pois.map(poi => [poi.osm_id, poi]))
if (zoom > POI_CLUSTER_MAX_ZOOM) return [...unique.values()].map(poi => ({ pois: [poi], lat: poi.lat, lng: poi.lng }))
for (const poi of [...unique.values()].sort((a, b) => a.osm_id.localeCompare(b.osm_id))) {
const point = project(poi)
const cx = Math.floor(point.x / POI_CLUSTER_RADIUS), cy = Math.floor(point.y / POI_CLUSTER_RADIUS)
@@ -1,3 +1,5 @@
import { useRoadtripSettings } from '../../hooks/useRoadtripSettings'
import { isServiceStopType } from '../Roadtrip/roadtripModel'
/* eslint-disable @typescript-eslint/no-unnecessary-type-assertion */
interface DragDataPayload { placeId?: string; assignmentId?: string; noteId?: string; reservationId?: string; fromDayId?: string; phase?: 'single' | 'start' | 'middle' | 'end'; /** A corridor hit on its way onto the drive (#1797) — not a place yet. */ poiOsmId?: string }
declare global { interface Window { __dragData: DragDataPayload | null } }
@@ -180,6 +182,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
const { t, language, locale } = useTranslation()
const ctxMenu = useContextMenu()
const timeFormat = useSettingsStore(s => s.settings.time_format) || '24h'
const mirrorServiceStops = useRoadtripSettings(s => s.roadtrip_service_stops_in_days !== false)
const tripActions = useRef(useTripStore.getState()).current
const can = useCanDo()
const canEditDays = can('day_edit', trip)
@@ -409,7 +412,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
}
const getDayAssignments = (dayId) =>
(assignments[String(dayId)] || []).slice().sort((a, b) => a.order_index - b.order_index)
(assignments[String(dayId)] || []).filter(a => mirrorServiceStops || !isServiceStopType(a.place?.stop_type)).slice().sort((a, b) => a.order_index - b.order_index)
// Compute initial day_plan_position for a transport based on time
const computeTransportPosition = (r, da) => {
@@ -485,7 +488,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
return map
// getMergedItems is redefined each render but captures assignments/dayNotes/reservations/days via closure
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [days, assignments, dayNotes, reservations, transportPosVersion])
}, [days, assignments, dayNotes, reservations, transportPosVersion, mirrorServiceStops])
// Days whose inline route legs should be computed & shown. Desktop: the selected
// day while the Route toggle is on. Mobile: each expanded day the user tapped
@@ -710,7 +713,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
// Unified reorder: assigns positions to ALL item types based on new visual order
const applyMergedOrder = async (dayId: number, newOrder: { type: string; data: any }[]) => {
// Capture previous place order for undo
const prevAssignmentIds = getDayAssignments(dayId).map(a => a.id)
const prevAssignmentIds = (assignments[String(dayId)] || []).slice().sort((a, b) => a.order_index - b.order_index).map(a => a.id)
// …and, per booking, the fields this call is about to overwrite, so a failed write
// can put the visible order back instead of leaving a phantom one behind the error
// toast. Restoring the whole array instead would also drop what a collaborator's
@@ -957,7 +960,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
const da = getDayAssignments(dayId)
if (da.length < 3) return
const prevIds = da.map(a => a.id)
const prevIds = (assignments[String(dayId)] || []).slice().sort((a, b) => a.order_index - b.order_index).map(a => a.id)
// Separate fixed (stay at their index) and movable assignments. A place is
// fixed if it's locked OR has a set time — timed places are anchored by their
@@ -276,3 +276,16 @@ describe('RoadtripLimitsCard', () => {
})
})
})
vi.mock('../../hooks/useRoadtripSettings', () => ({
useRoadtripSettings: (select: (preferences: import('@trek/shared').RoadtripPreferences) => unknown) => useSettingsStore(state => select(state.settings as import('@trek/shared').RoadtripPreferences)),
}))
it('shares service stops with Days by default and lets the trip turn it off', () => {
const onSave = vi.fn()
open(onSave)
const toggle = screen.getByRole('button', { name: 'Show in Days too' })
expect(toggle).toHaveAttribute('aria-pressed', 'true')
fireEvent.click(toggle)
expect(onSave).toHaveBeenCalledWith('roadtrip_service_stops_in_days', false)
})
@@ -1,3 +1,4 @@
import { useRoadtripSettings } from '../../hooks/useRoadtripSettings'
import React, { useState } from 'react'
import {
Clock, Fuel, CalendarClock, SlidersHorizontal, ChevronRight, Coins, Signpost, Ship, Check,
@@ -250,7 +251,8 @@ const SPEC_ROWS: Record<VehicleKind, { key: SpecKey; setting: string; Icon: type
*/
const SPEC_SETTINGS = ['roadtrip_tank_litres', 'roadtrip_litres_per_100', 'roadtrip_battery_kwh', 'roadtrip_kwh_per_100', 'roadtrip_battery_degradation'] as const
export default function RoadtripLimitsCard({ onSave, onResetDayBoundaries }: {
export default function RoadtripLimitsCard({ onSave, onResetDayBoundaries, loading = false }: {
loading?: boolean
onResetDayBoundaries?: () => Promise<void>
/**
* Persists one setting. Absent leaves the dialog read-only.
@@ -261,9 +263,10 @@ export default function RoadtripLimitsCard({ onSave, onResetDayBoundaries }: {
onSave?: (key: string, value: number | string | boolean) => void
}): React.ReactElement {
const { t } = useTranslation()
const settings = useSettingsStore(s => s.settings)
const settings = useRoadtripSettings(s => s)
const unit = useSettingsStore(s => s.settings.distance_unit)
const [open, setOpen] = useState(false)
const distanceUnit: DistanceUnit = settings.distance_unit === 'imperial' ? 'imperial' : 'metric'
const distanceUnit: DistanceUnit = unit === 'imperial' ? 'imperial' : 'metric'
const imperial = distanceUnit === 'imperial'
const legMinutes = settings.roadtrip_leg_minutes
@@ -380,6 +383,8 @@ export default function RoadtripLimitsCard({ onSave, onResetDayBoundaries }: {
<button
type="button"
onClick={() => setOpen(true)}
disabled={loading}
aria-busy={loading}
className="flex w-full items-center gap-3 rounded-xl border border-edge-faint bg-surface-card px-3.5 py-3 text-start transition-colors hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
{/* No icon tile on the trigger: the badges below already carry a clock, a
@@ -387,7 +392,7 @@ export default function RoadtripLimitsCard({ onSave, onResetDayBoundaries }: {
they need to sit on one line. */}
<span className="flex min-w-0 flex-1 flex-col gap-1">
<span className="truncate text-body font-semibold text-content">
{t('roadtrip.limit.title')}
{loading ? t('common.loading') : t('roadtrip.limit.title')}
</span>
{badges.length ? (
<span className="flex flex-wrap items-center gap-1">
@@ -636,6 +641,13 @@ export default function RoadtripLimitsCard({ onSave, onResetDayBoundaries }: {
onToggle={() => onSave?.('roadtrip_day_colors', !settings.roadtrip_day_colors)}
/>
</Panel>
<Panel icon={Signpost} title={t('roadtrip.stops.section')} note={t('roadtrip.stops.daysHint')}>
<AvoidRow icon={Link2} label={t('roadtrip.stops.inDays')}
on={settings.roadtrip_service_stops_in_days !== false}
disabled={!onSave}
onToggle={() => onSave?.('roadtrip_service_stops_in_days', settings.roadtrip_service_stops_in_days === false)}
/>
</Panel>
</div>
</div>
</div>
@@ -1,3 +1,4 @@
import { useRoadtripSettings } from '../../hooks/useRoadtripSettings'
import React, { useState } from 'react'
import {
CarFront, Footprints, Bike, Zap, AlertTriangle,
@@ -771,7 +772,7 @@ function ServiceStop({ stop, entry, late, driveFindings, selected, onSelect, onE
const { t } = useTranslation()
// Read here rather than threaded down: both stop shapes need the same two, and the
// badge is the only thing in the rail that depends on them.
const fillPercent = useSettingsStore(st => st.settings.roadtrip_fill_percent)
const fillPercent = useRoadtripSettings(s => s.roadtrip_fill_percent)
const { vehicleKind } = useVehicleRange()
const kind = STOP_KIND_BY_KEY[stop.stopType ?? '']
const Icon = kind?.Icon ?? ParkingSquare
@@ -1020,7 +1021,7 @@ function Stop({ stop, number, entry, late, driveFindings, selected, continues, s
const { t } = useTranslation()
// Read here rather than threaded down: both stop shapes need the same two, and the
// badge is the only thing in the rail that depends on them.
const fillPercent = useSettingsStore(st => st.settings.roadtrip_fill_percent)
const fillPercent = useRoadtripSettings(s => s.roadtrip_fill_percent)
const { vehicleKind } = useVehicleRange()
return (
<button
@@ -1325,7 +1326,7 @@ function DaySection({ day, selectedAssignmentId, onSelectStop, onReorderStop, on
const distanceUnit = useSettingsStore(s => s.settings.distance_unit)
// The colour the map draws this day in, or none at all while the map is drawing one
// blue line for the whole trip.
const dayColorsOn = useSettingsStore(s => !!s.settings.roadtrip_day_colors)
const dayColorsOn = useRoadtripSettings(s => !!s.roadtrip_day_colors)
const tint = dayColorsOn ? dayColor(day.dayNumber).line : null
const last = day.stops.length - 1
/**
@@ -110,3 +110,7 @@ describe('StopFillPicker', () => {
expect(onPick).toHaveBeenCalledWith(null)
})
})
vi.mock('../../hooks/useRoadtripSettings', () => ({
useRoadtripSettings: (select: (preferences: import('@trek/shared').RoadtripPreferences) => unknown) => useSettingsStore(state => select(state.settings as import('@trek/shared').RoadtripPreferences)),
}))
@@ -1,3 +1,4 @@
import { useRoadtripSettings } from '../../hooks/useRoadtripSettings'
import React from 'react'
import { RotateCcw } from 'lucide-react'
import { useTranslation } from '../../i18n/TranslationContext'
@@ -40,7 +41,7 @@ export default function StopFillPicker({ anchor, current, onPick, onClose }: {
}): React.ReactElement | null {
const { t } = useTranslation()
const unit: DistanceUnit = useSettingsStore(s => s.settings.distance_unit) === 'imperial' ? 'imperial' : 'metric'
const fallback = useSettingsStore(s => s.settings.roadtrip_fill_percent)
const fallback = useRoadtripSettings(s => s.roadtrip_fill_percent)
const { rangeKm } = useVehicleRange()
// Zero, absent and 100 all mean the same thing in the settings, so they read as full
@@ -10,8 +10,8 @@ const { pois, offline, stored } = vi.hoisted(() => ({
vi.mock('../../api/client', () => ({ mapsApi: { pois } }))
vi.mock('../../i18n', () => ({ useTranslation: () => ({ locale: 'en-US' }) }))
vi.mock('../../sync/networkMode', () => ({ isEffectivelyOffline: offline }))
vi.mock('../../store/settingsStore', () => ({
useSettingsStore: (select: (state: typeof stored) => unknown) => select(stored),
vi.mock('../../hooks/useRoadtripSettings', () => ({
useRoadtripSettings: (select: (settings: typeof stored.settings) => unknown) => select(stored.settings),
}))
import { useRefuelSearch } from './useRefuelSearch'
@@ -280,3 +280,20 @@ describe('useRefuelSearch', () => {
expect(result.current.loading).toBe(false)
})
})
it('searches farther back when nearby chargers cannot be reached', async () => {
pois.mockResolvedValueOnce(answer([station('too-late', 58)]))
.mockResolvedValueOnce(answer([station('earlier', 25)]))
const { result } = renderHook(() => useRefuelSearch())
await act(async () => { await result.current.ask('4:1', DRY, LINE, DRY_KM, []) })
expect(pois).toHaveBeenCalledTimes(2)
expect(result.current.results.map(p => p.osm_id)).toEqual(['earlier'])
expect(result.current.outcome).toBe('found')
})
it('does not offer stations behind the last refuelling stop', async () => {
pois.mockResolvedValue(answer([station('behind', 20)]))
const { result } = renderHook(() => useRefuelSearch())
await act(async () => { await result.current.ask('4:1', DRY, LINE, DRY_KM, [], 30) })
expect(result.current.results).toEqual([])
expect(pois).toHaveBeenCalledTimes(2)
})
@@ -1,28 +1,12 @@
import { useRoadtripSettings } from '../../hooks/useRoadtripSettings'
import { useCallback, useMemo, useRef, useState } from 'react'
import { mapsApi } from '../../api/client'
import { useTranslation } from '../../i18n'
import { isEffectivelyOffline } from '../../sync/networkMode'
import { useSettingsStore } from '../../store/settingsStore'
import { refuelStopTypeFor, type VehicleKind } from './roadtripModel'
import { boxAround, pointAtMeters, type LatLng } from './corridor'
import { reachableRefuels, outcomeOf, type RefuelCandidate, type RefuelOutcome } from './refuelSuggestion'
/**
* Somewhere to fill up before the tank runs out, asked for once, when asked for.
*
* Deliberately NOT automatic, for the same reason the corridor search next door is not:
* every run is a real request against a shared service. It is also not the corridor
* search itself, although it looks like a smaller version of it. Three reasons, all
* about behaviour rather than tidiness:
*
* - that search is bound to the day the panel has selected, so it cannot answer a
* warning on day five while the panel shows day one;
* - starting it clears the panel's results and the traveller's own name filter;
* - it asks up to sixteen boxes along a whole day. This question needs one small circle.
*
* One request, one day, no shared state touched.
*/
/**
* How far around the search point to look, in kilometres.
*
@@ -41,6 +25,8 @@ const LOOK_KM = 14
* reach, so it is pulled back far enough that the useful half becomes the whole of it.
*/
const LOOK_BACK_KM = 12
const SEARCH_STEP_KM = 20
const MAX_SEARCHES = 8
/** Nothing on offer, as one stable array, so an idle search never redraws the map. */
const NONE: RefuelCandidate[] = []
@@ -60,8 +46,8 @@ export interface RefuelSearch {
* reference changes.
*/
offered: RefuelCandidate[]
/** Runs the one request. `key` identifies the dry point, so only one is open at a time. */
ask: (key: string, at: LatLng, line: LatLng[], dryAlongKm: number, existing: LatLng[]) => Promise<void>
/** Searches backwards until an available stop is found. `key` identifies the dry point, so only one is open at a time. */
ask: (key: string, at: LatLng, line: LatLng[], dryAlongKm: number, existing: LatLng[], fromAlongKm?: number) => Promise<void>
close: () => void
}
@@ -69,7 +55,7 @@ export function useRefuelSearch(): RefuelSearch {
const { locale } = useTranslation()
// What to look for. Somebody who said they drive an electric car has no use for a
// petrol station in the list, and the other way round; with nothing said, both.
const vehicle = useSettingsStore(s => s.settings.roadtrip_vehicle)
const vehicle = useRoadtripSettings(s => s.roadtrip_vehicle)
const [openFor, setOpenFor] = useState<string | null>(null)
const [loading, setLoading] = useState(false)
const [outcome, setOutcome] = useState<RefuelOutcome | null>(null)
@@ -91,6 +77,7 @@ export function useRefuelSearch(): RefuelSearch {
line: LatLng[],
dryAlongKm: number,
existing: LatLng[],
fromAlongKm = 0,
) => {
abortRef.current?.abort()
const controller = new AbortController()
@@ -99,6 +86,7 @@ export function useRefuelSearch(): RefuelSearch {
setResults([])
setOutcome(null)
setLoading(false)
// Offline the answer would be a list of places that cannot be saved: the place write
// queues offline but the day assignment does not, so accepting one would leave an
// orphan. Say so instead of offering it.
@@ -115,12 +103,25 @@ export function useRefuelSearch(): RefuelSearch {
// Pulled back along the road, because only what lies before the dry point can be
// reached. `at` stays the dry point itself: it is what the band names and what the
// map is asked to show.
const centre = pointAtMeters(line, Math.max(0, (dryAlongKm - LOOK_BACK_KM) * 1000)) ?? at
const answer = await mapsApi.pois(wanted, boxAround(centre, LOOK_KM), locale, controller.signal)
if (controller.signal.aborted) return
const candidates = reachableRefuels(answer.pois, line, dryAlongKm, { existing })
setResults(candidates)
setOutcome(outcomeOf(candidates, answer))
let incomplete = false
for (let attempt = 0; attempt < MAX_SEARCHES; attempt++) {
const along = Math.max(fromAlongKm, dryAlongKm - LOOK_BACK_KM - attempt * SEARCH_STEP_KM)
const centre = pointAtMeters(line, along * 1000) ?? at
const answer = await mapsApi.pois(wanted, boxAround(centre, LOOK_KM), locale, controller.signal)
if (controller.signal.aborted) return
incomplete ||= !!answer.truncated
const candidates = reachableRefuels(answer.pois, line, dryAlongKm, { existing }).filter(p => p.alongKm >= fromAlongKm)
if (candidates.length) {
setResults(candidates)
setOutcome('found')
return
}
if (along === fromAlongKm) {
setOutcome(outcomeOf([], { truncated: incomplete }))
return
}
}
setOutcome('incomplete')
} catch {
if (!controller.signal.aborted) setOutcome('failed')
} finally {
@@ -721,3 +721,7 @@ describe('useRoadtripRoutes', () => {
})
})
})
vi.mock('../../hooks/useRoadtripSettings', () => ({
useRoadtripSettings: (select: (preferences: import('@trek/shared').RoadtripPreferences) => unknown) => useSettingsStore(state => select(state.settings as import('@trek/shared').RoadtripPreferences)),
}))
@@ -1,3 +1,4 @@
import { useRoadtripSettings } from '../../hooks/useRoadtripSettings'
import { assembleRoadtrip, foldRouteRun, type RoadtripStop, type RoadtripRoutes, type PlanDay, type QuietDay, type RoutedLeg } from '@trek/shared/roadtrip'
import { useEffect, useMemo, useRef, useState } from 'react'
import { calculateRouteWithLegs, RoutingRefusedError } from '../Map/RouteCalculator'
@@ -144,9 +145,9 @@ export function useRoadtripRoutes(
const [loading, setLoading] = useState(false)
const abortRef = useRef<AbortController | null>(null)
const legMinutes = useSettingsStore(s => s.settings.roadtrip_leg_minutes)
const dayMinutes = useSettingsStore(s => s.settings.roadtrip_day_minutes)
const fillPercent = useSettingsStore(s => s.settings.roadtrip_fill_percent)
const legMinutes = useRoadtripSettings(s => s.roadtrip_leg_minutes, tripId)
const dayMinutes = useRoadtripSettings(s => s.roadtrip_day_minutes, tripId)
const fillPercent = useRoadtripSettings(s => s.roadtrip_fill_percent, tripId)
/**
* Road classes to weight away, as the settings row stores them: a comma list.
*
@@ -155,7 +156,7 @@ export function useRoadtripRoutes(
* any value — and an unknown word here would become a costing option the router does
* not have.
*/
const avoidSetting = useSettingsStore(s => s.settings.roadtrip_avoid)
const avoidSetting = useRoadtripSettings(s => s.roadtrip_avoid, tripId)
/**
* Whether the gaps between days are driven too.
*
@@ -164,16 +165,16 @@ export function useRoadtripRoutes(
* the trip one continuous drive — every one of those gaps is routed, drawn, and counted
* towards the day it ARRIVES on, which is the same rule a night drive already follows.
*/
const connectSetting = useSettingsStore(s => !!s.settings.roadtrip_connect_days)
const startTime = useSettingsStore(s => s.settings.roadtrip_day_start)
const endTime = useSettingsStore(s => s.settings.roadtrip_day_end)
const endMode = useSettingsStore(s => s.settings.roadtrip_day_end_mode)
const connectSetting = useRoadtripSettings(s => !!s.roadtrip_connect_days, tripId)
const startTime = useRoadtripSettings(s => s.roadtrip_day_start, tripId)
const endTime = useRoadtripSettings(s => s.roadtrip_day_end, tripId)
const endMode = useRoadtripSettings(s => s.roadtrip_day_end_mode, tripId)
const window = useMemo(() => dayWindow(startTime, endTime, endMode), [startTime, endTime, endMode])
const connectDays = connectSetting || window !== null
const avoid = useMemo(() => parseAvoid(avoidSetting), [avoidSetting])
// What the car is and how far it goes on one fill, assembled in one place because the
// rail needs the same answer to say what a given fill buys at a given stop.
const { vehicleKind, rangeKm: planningRangeKm } = useVehicleRange()
const { vehicleKind, rangeKm: planningRangeKm } = useVehicleRange(tripId)
const avoidKey = avoid.join(',')
// Zero and absent both mean "no limit": zero is a legal thing to type and says the
// same thing, so it is folded here rather than guarded at every reading.
@@ -1,5 +1,5 @@
import { renderHook, act } from '@testing-library/react'
import { describe, it, expect, beforeEach } from 'vitest'
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { useSettingsStore } from '../../store/settingsStore'
import type { Settings } from '../../types'
import { useVehicleRange } from './useVehicleRange'
@@ -197,3 +197,7 @@ describe('useVehicleRange', () => {
expect(result.current).not.toBe(first)
})
})
vi.mock('../../hooks/useRoadtripSettings', () => ({
useRoadtripSettings: (select: (preferences: import('@trek/shared').RoadtripPreferences) => unknown) => useSettingsStore(state => select(state.settings as import('@trek/shared').RoadtripPreferences)),
}))
@@ -1,31 +1,16 @@
import { useRoadtripSettings } from '../../hooks/useRoadtripSettings'
import { useMemo } from 'react'
import { useSettingsStore } from '../../store/settingsStore'
import { effectiveRangeKm } from './vehicleRange'
import type { VehicleKind } from './roadtripModel'
/**
* How far the traveller's car goes on one fill, and what kind of car it is.
*
* One place rather than two, because the answer is assembled from seven settings and two
* readers need it: the routes hook, which turns it into the range budget every warning is
* measured against, and the rail, which tells a traveller what a given fill buys at a
* given stop. Assembling it twice is the hand-mirrored state this codebase refuses
* everywhere else, and the two copies would drift the first time a field is added.
*
* Each setting is read as its own primitive so the memo compares numbers. An object
* rebuilt on every render would give the result a new identity every time, and what
* depends on it is the effect that recalculates every day's driving.
*/
export function useVehicleRange(): { vehicleKind: VehicleKind | null; rangeKm: number | null } {
const rangeKm = useSettingsStore(s => s.settings.roadtrip_range_km)
// Validated rather than trusted: a per-user setting gets no server-side check, and an
// unknown word here would silently stop both kinds of stop counting as a fill-up.
const vehicle = useSettingsStore(s => s.settings.roadtrip_vehicle)
const tankLitres = useSettingsStore(s => s.settings.roadtrip_tank_litres)
const litresPer100 = useSettingsStore(s => s.settings.roadtrip_litres_per_100)
const batteryKwh = useSettingsStore(s => s.settings.roadtrip_battery_kwh)
const kwhPer100 = useSettingsStore(s => s.settings.roadtrip_kwh_per_100)
const degradationPercent = useSettingsStore(s => s.settings.roadtrip_battery_degradation)
export function useVehicleRange(tripId?: number | string | null): { vehicleKind: VehicleKind | null; rangeKm: number | null } {
const rangeKm = useRoadtripSettings(s => s.roadtrip_range_km, tripId)
const vehicle = useRoadtripSettings(s => s.roadtrip_vehicle, tripId)
const tankLitres = useRoadtripSettings(s => s.roadtrip_tank_litres, tripId)
const litresPer100 = useRoadtripSettings(s => s.roadtrip_litres_per_100, tripId)
const batteryKwh = useRoadtripSettings(s => s.roadtrip_battery_kwh, tripId)
const kwhPer100 = useRoadtripSettings(s => s.roadtrip_kwh_per_100, tripId)
const degradationPercent = useRoadtripSettings(s => s.roadtrip_battery_degradation, tripId)
const vehicleKind: VehicleKind | null =
vehicle === 'combustion' || vehicle === 'electric' ? vehicle : null
+5
View File
@@ -1,3 +1,4 @@
import type { RoadtripPreferences } from '@trek/shared';
import Dexie, { type Table } from 'dexie';
import type { Trip, Day, Place, PackingItem, TodoItem, BudgetItem, Reservation, TripFile, Accommodation, TripMember, Tag, Category } from '../types';
@@ -160,6 +161,7 @@ function initialDbName(): string {
}
class TrekOfflineDb extends Dexie {
roadtripPreferences!: Table<{ tripId: number; preferences: RoadtripPreferences }, number>;
trips!: Table<Trip, number>;
days!: Table<Day, number>;
places!: Table<Place, number>;
@@ -221,6 +223,7 @@ class TrekOfflineDb extends Dexie {
// v5: places from the TREK Places index for the trip's area, so search
// answers offline. `searchName` is indexed because that is what an offline
// query filters on; `tripId` so the set drops with its trip.
this.version(6).stores({ roadtripPreferences: 'tripId' });
this.version(5).stores({
areaPlaces: 'gers, tripId, searchName',
});
@@ -448,8 +451,10 @@ export async function clearTripData(tripId: number): Promise<void> {
offlineDb.syncMeta,
offlineDb.blobCache,
offlineDb.areaPlaces,
offlineDb.roadtripPreferences,
],
async () => {
await offlineDb.roadtripPreferences.delete(tripId);
await offlineDb.days.where('trip_id').equals(tripId).delete();
await offlineDb.places.where('trip_id').equals(tripId).delete();
await offlineDb.packingItems.where('trip_id').equals(tripId).delete();
@@ -1,24 +1,33 @@
import { act, renderHook } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { useRoadtripPreferencesSync } from './useRoadtripPreferencesSync'
import { useSettingsStore } from '../store/settingsStore'
import { useRoadtripSettings } from './useRoadtripSettings'
import { useRoadtripPreferencesStore } from '../store/roadtripPreferencesStore'
import { useAuthStore } from '../store/authStore'
import { addListener, removeListener } from '../api/websocket'
vi.mock('../api/websocket', () => ({ addListener: vi.fn(), removeListener: vi.fn() }))
vi.mock('../repo/roadtripPreferencesRepo', () => ({ cachedRoadtripPreferences: vi.fn(async () => ({})) }))
vi.mock('../db/offlineDb', () => ({ offlineDb: { roadtripPreferences: { put: vi.fn(async () => {}) } } }))
describe('Roadtrip settings from MCP', () => {
it('merges valid user events, refuses unrelated settings and unsubscribes', () => {
const before = useSettingsStore.getState().settings
const hook = renderHook(() => useRoadtripPreferencesSync())
const calls = vi.mocked(addListener).mock.calls
const listener = calls[calls.length - 1][0]
act(() => listener({ type: 'roadtripPreferences:changed', preferences: { roadtrip_day_start: '07:00' } }))
expect(useSettingsStore.getState().settings.roadtrip_day_start).toBe('07:00')
expect(useSettingsStore.getState().settings.distance_unit).toBe(before.distance_unit)
act(() => listener({ type: 'roadtripPreferences:changed', preferences: { roadtrip_day_start: '99:00' } }))
expect(useSettingsStore.getState().settings.roadtrip_day_start).toBe('07:00')
describe('shared Roadtrip settings', () => {
it('scopes events and reads by trip and signed-in account', () => {
useAuthStore.setState({ user: { id: 1 } as never })
useRoadtripPreferencesStore.setState({ byTrip: {} })
const hook = renderHook(() => {
useRoadtripPreferencesSync()
return useRoadtripSettings(s => s.roadtrip_day_start, 10)
})
const listener = vi.mocked(addListener).mock.calls[vi.mocked(addListener).mock.calls.length - 1][0]
act(() => listener({ type: 'roadtripPreferences:changed', tripId: '10', preferences: { roadtrip_day_start: '07:00' } }))
expect(hook.result.current).toBe('07:00')
act(() => listener({ type: 'roadtripPreferences:changed', tripId: '11', preferences: { roadtrip_day_start: '09:00' } }))
expect(hook.result.current).toBe('07:00')
act(() => listener({ type: 'roadtripPreferences:changed', tripId: '10', preferences: { roadtrip_day_start: '99:00' } }))
expect(hook.result.current).toBe('07:00')
act(() => useAuthStore.setState({ user: { id: 2 } as never }))
expect(hook.result.current).toBeUndefined()
hook.unmount()
expect(removeListener).toHaveBeenCalledWith(listener)
useSettingsStore.setState({ settings: before })
})
})
+15 -4
View File
@@ -1,16 +1,27 @@
import { useEffect } from 'react'
import { roadtripPreferencesSchema } from '@trek/shared'
import { addListener, removeListener } from '../api/websocket'
import { useSettingsStore } from '../store/settingsStore'
import { useAuthStore } from '../store/authStore'
import { publishRoadtripPreferences } from '../store/roadtripPreferencesStore'
import { offlineDb } from '../db/offlineDb'
import { cachedRoadtripPreferences } from '../repo/roadtripPreferencesRepo'
export function useRoadtripPreferencesSync() {
const userId = useAuthStore(s => s.user?.id)
useEffect(() => {
if (!userId) return
let disposed = false
const listener = (event: Record<string, unknown>) => {
if (event.type !== 'roadtripPreferences:changed') return
const tripId = Number(event.tripId)
const parsed = roadtripPreferencesSchema.safeParse(event.preferences)
if (parsed.success) useSettingsStore.setState(state => ({ settings: { ...state.settings, ...parsed.data } }))
if (!parsed.success || !Number.isSafeInteger(tripId) || tripId < 1) return
publishRoadtripPreferences(userId, tripId, parsed.data)
void offlineDb.roadtripPreferences.put({ tripId, preferences: parsed.data }).then(() => cachedRoadtripPreferences(tripId)).then(preferences => {
if (!disposed) publishRoadtripPreferences(userId, tripId, preferences)
}).catch(() => {})
}
addListener(listener)
return () => removeListener(listener)
}, [])
return () => { disposed = true; removeListener(listener) }
}, [userId])
}
+42
View File
@@ -0,0 +1,42 @@
import { liveQuery } from 'dexie'
import { onNetworkModeChange } from '../sync/networkMode'
import { useEffect, useState } from 'react'
import type { RoadtripPreferences } from '@trek/shared'
import { useAuthStore } from '../store/authStore'
import { useTripStore } from '../store/tripStore'
import { EMPTY_ROADTRIP_PREFERENCES, publishRoadtripPreferences, useRoadtripPreferencesStore } from '../store/roadtripPreferencesStore'
import { cachedRoadtripPreferences, roadtripPreferencesRepo } from '../repo/roadtripPreferencesRepo'
export function useRoadtripSettings<T>(select: (settings: RoadtripPreferences) => T, requestedTripId?: number | string | null): T {
const activeTripId = useTripStore(s => s.trip?.id)
const userId = useAuthStore(s => s.user?.id)
const key = `${userId}:${requestedTripId ?? activeTripId}`
return useRoadtripPreferencesStore(s => select(s.byTrip[key] ?? EMPTY_ROADTRIP_PREFERENCES))
}
export function useLoadRoadtripSettings(tripId: number, enabled: boolean) {
const userId = useAuthStore(s => s.user?.id)
const [loadedKey, setLoadedKey] = useState('')
const [failedKey, setFailedKey] = useState('')
const key = `${userId}:${tripId}`
useEffect(() => {
if (!enabled || !userId || !Number.isFinite(tripId)) return
let cancelled = false
const load = () => {
roadtripPreferencesRepo.read(tripId).then(preferences => {
if (cancelled) return
publishRoadtripPreferences(userId, tripId, preferences)
setLoadedKey(key)
setFailedKey('')
}).catch(() => { if (!cancelled) setFailedKey(key) })
}
const cacheSubscription = liveQuery(() => cachedRoadtripPreferences(tripId).catch(() => null)).subscribe(preferences => {
if (!cancelled && preferences) publishRoadtripPreferences(userId, tripId, preferences)
})
load()
const unsubscribe = onNetworkModeChange(load)
window.addEventListener('online', load)
return () => { cancelled = true; cacheSubscription.unsubscribe(); unsubscribe(); window.removeEventListener('online', load) }
}, [tripId, userId, enabled, key])
return { ready: loadedKey === key, failed: failedKey === key }
}
+6 -3
View File
@@ -1,3 +1,5 @@
import { useRoadtripSettings } from './useRoadtripSettings'
import { isServiceStopType } from '../components/Roadtrip/roadtripModel'
import { useState, useCallback, useRef, useEffect, useMemo } from 'react'
import { useTripStore } from '../store/tripStore'
import { useSettingsStore } from '../store/settingsStore'
@@ -24,6 +26,7 @@ export function useRouteCalculation(tripStore: TripStoreState, selectedDayId: nu
const [routeSegments, setRouteSegments] = useState<RouteSegment[]>([])
// Charging stops / rest areas a plugin route places on the drawn line.
const [routeVias, setRouteVias] = useState<RouteVia[]>([])
const mirrorServiceStops = useRoadtripSettings(s => s.roadtrip_service_stops_in_days !== false)
const routeAbortRef = useRef<AbortController | null>(null)
const reservationsForSignature = useTripStore((s) => s.reservations)
// Recompute when the selected day's whole-day default mode changes (#1281) —
@@ -45,7 +48,7 @@ export function useRouteCalculation(tripStore: TripStoreState, selectedDayId: nu
// Read directly from store (not a render-phase ref) so callers after optimistic
// updates or non-optimistic deletes always see the latest assignments.
const currentAssignments = useTripStore.getState().assignments || {}
const da = (currentAssignments[String(dayId)] || []).slice().sort((a, b) => a.order_index - b.order_index)
const da = (currentAssignments[String(dayId)] || []).filter(a => mirrorServiceStops || !isServiceStopType(a.place?.stop_type)).slice().sort((a, b) => a.order_index - b.order_index)
const allReservations = useTripStore.getState().reservations || []
const allDays = useTripStore.getState().days || []
const dayOrder = (id: number | null | undefined): number | null => {
@@ -275,7 +278,7 @@ export function useRouteCalculation(tripStore: TripStoreState, selectedDayId: nu
// Aborted (day changed) — newer call owns the state. Anything else: keep straight lines.
if (!(err instanceof Error) || err.name !== 'AbortError') { setRouteSegments([]); setRouteVias([]) }
}
}, [enabled, profile, accommodations, optimizeFromAccommodation, distanceUnit, selectedDayDefaultMode])
}, [enabled, profile, accommodations, optimizeFromAccommodation, distanceUnit, selectedDayDefaultMode, mirrorServiceStops])
// Stable signature for transport reservations on the selected day — changes when a transport
// is added, removed, or repositioned, ensuring route recalc fires even on transport-only reorders.
@@ -299,7 +302,7 @@ export function useRouteCalculation(tripStore: TripStoreState, selectedDayId: nu
if (!selectedDayId) { setRoute(null); setRouteSegments([]); setRouteVias([]); return }
updateRouteForDay(selectedDayId)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedDayId, selectedDayAssignments, transportSignature, enabled, profile, accommodations, optimizeFromAccommodation, distanceUnit, selectedDayDefaultMode])
}, [selectedDayId, selectedDayAssignments, transportSignature, enabled, profile, accommodations, optimizeFromAccommodation, distanceUnit, selectedDayDefaultMode, mirrorServiceStops])
return { route, routeSegments, routeVias, routeInfo, setRoute, setRouteInfo, updateRouteForDay }
}
+4 -4
View File
@@ -266,7 +266,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
stopDraft, setStopDraft, saveStopDraft, saveStopDraftAsNight, stopDraftToForm, stopDraftDuplicate, reorderRoadtripStop,
setRoadtripStopKind,
setRoadtripStopFill,
saveRoadtripLimit,
saveRoadtripLimit, roadtripSettingsLoading, storedAssignments,
roadtripVias, addRoadtripVia, moveRoadtripVia, removeRoadtripVia, resetDayBoundaries,
routeAlternatives, askRouteAlternatives, refuel, askRefuel, acceptRefuel, chooseRouteAlternative, alternativeOverlays, alternativeFocusPoints, mapFocusPoints, roadtripMapVias, focusRoadtripPoint, dayBoundaryControls,
stayDraft, setStayDraft, setRoadtripStay, roadtripEndDay, roadtripStay,
@@ -572,7 +572,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
days={days}
places={places}
categories={categories}
assignments={assignments}
assignments={storedAssignments}
selectedDayId={selectedDayId}
selectedPlaceId={selectedPlaceId}
selectedAssignmentId={selectedAssignmentId}
@@ -687,7 +687,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
{/* Under the search, because the limits are read while looking at
what the drive is doing rather than set up front. */}
<div className="px-3.5 pb-3.5">
<RoadtripLimitsCard onSave={saveRoadtripLimit} onResetDayBoundaries={resetDayBoundaries} />
<RoadtripLimitsCard loading={roadtripSettingsLoading} onSave={saveRoadtripLimit} onResetDayBoundaries={resetDayBoundaries} />
</div>
</LazyPanel>
) : (
@@ -869,7 +869,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
</div>
<div style={{ flex: 1, overflow: 'auto', paddingBottom: 'env(safe-area-inset-bottom, 0px)' }}>
{mobileSidebarOpen === 'left'
? <DayPlanSidebar tripId={tripId} trip={trip} days={days} places={places} categories={categories} assignments={assignments} selectedDayId={selectedDayId} selectedPlaceId={selectedPlaceId} selectedAssignmentId={selectedAssignmentId} onSelectDay={(id) => { handleSelectDay(id); setMobileSidebarOpen(null) }} onPlaceClick={(placeId, assignmentId) => { handlePlaceClick(placeId, assignmentId) }} onReorder={handleReorder} onReorderDays={handleReorderDays} onAddDay={handleAddDay} onUpdateDayTitle={handleUpdateDayTitle} onAssignToDay={handleAssignToDay} onRouteCalculated={(r) => { if (r) { setRoute([r.coordinates]); setRouteInfo(r) } else { setRoute(null); setRouteInfo(null) } }} reservations={reservations} visibleConnectionIds={visibleConnections} onToggleConnection={toggleConnection} allConnectionsShown={allConnectionsShown} onToggleAllConnections={toggleAllConnections} onAddReservation={(dayId) => { setEditingReservation(null); tripActions.setSelectedDay(dayId); setShowReservationModal(true); setMobileSidebarOpen(null) }} onAddTransport={can('day_edit', trip) ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(null); setTransportModalAutomated(false); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onOpenTransit={(r) => { setTransitJourney(r); setMobileSidebarOpen(null) }} onPlanTransit={can('day_edit', trip) && tripHasDates ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(null); setTransportModalAutomated(true); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onPlanTransitLeg={can('day_edit', trip) && tripHasDates ? ({ dayId, from, to, time }) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill({ from, to, time }); setTransportModalAutomated(true); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onAddPlace={() => { setEditingPlace(null); setPlaceFormDayId(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onCreatePlaceForDay={can('place_edit', trip) ? (dayId) => { setEditingPlace(null); setPlaceFormDayId(dayId); setShowPlaceForm(true); setMobileSidebarOpen(null) } : undefined} onDayDetail={(day) => { setShowDayDetail(day); setSelectedPlaceId(null); selectAssignment(null) }} onRemoveAssignment={handleRemoveAssignment} onEditPlace={(place, assignmentId) => { setEditingPlace(place); setEditingAssignmentId(assignmentId || null); setPlaceFormDayId(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onDeletePlace={(placeId) => handleDeletePlace(placeId)} accommodations={tripAccommodations} routeShown={routeShown} routeProfile={routeProfile} onToggleRoute={() => setRouteShown(v => !v)} onSetRouteProfile={setRouteProfile} onNavigateToFiles={() => { setMobileSidebarOpen(null); handleTabChange('dateien') }} onExpandedDaysChange={setExpandedDayIds} pushUndo={pushUndo} canUndo={canUndo} lastActionLabel={lastActionLabel} onUndo={handleUndo} onEditTransport={can('day_edit', trip) ? (reservation) => { setEditingTransport(reservation); setTransportModalDayId(reservation.day_id ?? null); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onEditReservation={can('reservation_edit', trip) ? (r) => { setEditingReservation(r); setShowReservationModal(true); setMobileSidebarOpen(null) } : undefined} initialScrollTop={mobilePlanScrollTopRef.current} onScrollTopChange={(top) => { mobilePlanScrollTopRef.current = top }} showRouteToolsWhenExpanded isMobile />
? <DayPlanSidebar tripId={tripId} trip={trip} days={days} places={places} categories={categories} assignments={storedAssignments} selectedDayId={selectedDayId} selectedPlaceId={selectedPlaceId} selectedAssignmentId={selectedAssignmentId} onSelectDay={(id) => { handleSelectDay(id); setMobileSidebarOpen(null) }} onPlaceClick={(placeId, assignmentId) => { handlePlaceClick(placeId, assignmentId) }} onReorder={handleReorder} onReorderDays={handleReorderDays} onAddDay={handleAddDay} onUpdateDayTitle={handleUpdateDayTitle} onAssignToDay={handleAssignToDay} onRouteCalculated={(r) => { if (r) { setRoute([r.coordinates]); setRouteInfo(r) } else { setRoute(null); setRouteInfo(null) } }} reservations={reservations} visibleConnectionIds={visibleConnections} onToggleConnection={toggleConnection} allConnectionsShown={allConnectionsShown} onToggleAllConnections={toggleAllConnections} onAddReservation={(dayId) => { setEditingReservation(null); tripActions.setSelectedDay(dayId); setShowReservationModal(true); setMobileSidebarOpen(null) }} onAddTransport={can('day_edit', trip) ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(null); setTransportModalAutomated(false); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onOpenTransit={(r) => { setTransitJourney(r); setMobileSidebarOpen(null) }} onPlanTransit={can('day_edit', trip) && tripHasDates ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(null); setTransportModalAutomated(true); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onPlanTransitLeg={can('day_edit', trip) && tripHasDates ? ({ dayId, from, to, time }) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill({ from, to, time }); setTransportModalAutomated(true); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onAddPlace={() => { setEditingPlace(null); setPlaceFormDayId(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onCreatePlaceForDay={can('place_edit', trip) ? (dayId) => { setEditingPlace(null); setPlaceFormDayId(dayId); setShowPlaceForm(true); setMobileSidebarOpen(null) } : undefined} onDayDetail={(day) => { setShowDayDetail(day); setSelectedPlaceId(null); selectAssignment(null) }} onRemoveAssignment={handleRemoveAssignment} onEditPlace={(place, assignmentId) => { setEditingPlace(place); setEditingAssignmentId(assignmentId || null); setPlaceFormDayId(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onDeletePlace={(placeId) => handleDeletePlace(placeId)} accommodations={tripAccommodations} routeShown={routeShown} routeProfile={routeProfile} onToggleRoute={() => setRouteShown(v => !v)} onSetRouteProfile={setRouteProfile} onNavigateToFiles={() => { setMobileSidebarOpen(null); handleTabChange('dateien') }} onExpandedDaysChange={setExpandedDayIds} pushUndo={pushUndo} canUndo={canUndo} lastActionLabel={lastActionLabel} onUndo={handleUndo} onEditTransport={can('day_edit', trip) ? (reservation) => { setEditingTransport(reservation); setTransportModalDayId(reservation.day_id ?? null); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onEditReservation={can('reservation_edit', trip) ? (r) => { setEditingReservation(r); setShowReservationModal(true); setMobileSidebarOpen(null) } : undefined} initialScrollTop={mobilePlanScrollTopRef.current} onScrollTopChange={(top) => { mobilePlanScrollTopRef.current = top }} showRouteToolsWhenExpanded isMobile />
: <PlacesSidebar tripId={tripId} places={places} categories={categories} assignments={assignments} accommodations={tripAccommodations} selectedDayId={selectedDayId} onClearSelectedDay={() => handleSelectDay(null)} selectedPlaceId={selectedPlaceId} onPlaceClick={(placeId) => { handlePlaceClick(placeId); setMobileSidebarOpen(null) }} onAddPlace={() => { setEditingPlace(null); setPlaceFormDayId(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onAssignToDay={handleAssignToDay} onEditPlace={(place) => { openPlaceEditor(place); setMobileSidebarOpen(null) }} onDeletePlace={(placeId) => handleDeletePlace(placeId)} onBulkDeletePlaces={(ids) => setDeletePlaceIds(ids)} onBulkDeleteConfirm={(ids) => confirmDeletePlaces(ids)} onBulkChangeCategory={(ids, catId) => confirmChangeCategory(ids, catId)} days={days} isMobile pushUndo={pushUndo} initialScrollTop={mobilePlacesScrollTopRef.current} onScrollTopChange={(top) => { mobilePlacesScrollTopRef.current = top }} />
}
</div>
@@ -1,3 +1,4 @@
import { roadtripPreferencesRepo } from '../../repo/roadtripPreferencesRepo'
// FE-TP-ROAD-001 to FE-TP-ROAD-074
import React from 'react'
import { renderHook, act, waitFor } from '@testing-library/react'
@@ -859,15 +860,15 @@ describe('useTripPlanner road trip: one stop at a time', () => {
it('FE-TP-ROAD-033: a driving limit goes straight to the settings, and a failure is said', async () => {
oneStop()
const updateSettings = vi.fn(async () => {})
useSettingsStore.setState({ updateSettings } as never)
const updateSettings = vi.mocked(roadtripPreferencesRepo.update)
updateSettings.mockResolvedValue({})
const { result } = await renderRoadtrip()
await act(async () => { await result.current.saveRoadtripLimit('roadtrip_max_leg_minutes', 180) })
expect(updateSettings).toHaveBeenCalledWith({ roadtrip_max_leg_minutes: 180 })
await act(async () => { await result.current.saveRoadtripLimit?.('roadtrip_leg_minutes', 180) })
expect(updateSettings).toHaveBeenCalledWith(42, { roadtrip_leg_minutes: 180 })
updateSettings.mockRejectedValue(new Error('nope'))
await act(async () => { await result.current.saveRoadtripLimit('roadtrip_max_leg_minutes', 90) })
await act(async () => { await result.current.saveRoadtripLimit?.('roadtrip_leg_minutes', 90) })
expect(toasts.some(t => t.type === 'error')).toBe(true)
})
})
@@ -1492,6 +1493,7 @@ describe('useTripPlanner road trip: somewhere to fill up', () => {
stops: [drawn(1201, 53, 10, 5, 1), drawn(1202, 52, 10, 5, 2), drawn(1203, 51, 10, 6, 0)],
geometry: [[53, 10], [52, 10], [51, 10]],
drivingGeometry: [[53, 10], [52, 10], [51, 10]],
legs: [{ mode: 'driving', distance: 111000 }, { mode: 'driving', distance: 111000 }],
}]
}
@@ -1599,3 +1601,36 @@ describe('useTripPlanner road trip: somewhere to fill up', () => {
expect(result.current.stopDraft).toBeNull()
})
})
vi.mock('../../hooks/useRoadtripSettings', () => ({
useRoadtripSettings: (select: (preferences: import('@trek/shared').RoadtripPreferences) => unknown) => useSettingsStore(state => select(state.settings as import('@trek/shared').RoadtripPreferences)),
useLoadRoadtripSettings: () => ({ ready: true, failed: false }),
}))
vi.mock('../../repo/roadtripPreferencesRepo', () => ({ roadtripPreferencesRepo: { update: vi.fn(async () => ({})) } }))
it('keeps exclusive service stops in Roadtrip, hides them in Days and restores them without duplicates', async () => {
const normal = buildPlace({ id: 101, name: 'Berlin' })
const charging = buildPlace({ id: 102, name: 'Charger', stop_type: 'charging' })
const visits = [buildAssignment({ id: 11, day_id: 5, place: normal }), buildAssignment({ id: 12, day_id: 5, place: charging })]
seedTrip({ places: [normal, charging], days: [buildDay({ id: 5 })], assignments: { '5': visits } })
useSettingsStore.setState(s => ({ settings: { ...s.settings, roadtrip_service_stops_in_days: false } }))
const { result } = await renderRoadtrip()
expect(result.current.assignments['5']).toHaveLength(2)
act(() => result.current.toggleRoadtripMode())
expect(result.current.assignments['5'].map(a => a.id)).toEqual([11])
expect(result.current.places.map(p => p.id)).toEqual([101])
expect(useTripStore.getState().assignments['5']).toHaveLength(2)
act(() => useSettingsStore.setState(s => ({ settings: { ...s.settings, roadtrip_service_stops_in_days: true } })))
expect(result.current.assignments['5']).toHaveLength(2)
expect(result.current.places).toHaveLength(2)
})
it('preserves exclusive service stops when reordering the visible Days stops', async () => {
const visits = [stopAt(11, 5, 0), stopAt(12, 5, 1, { place: buildPlace({ stop_type: 'charging' }) }), stopAt(13, 5, 2)]
seedTrip({ days: [buildDay({ id: 5 })], assignments: { '5': visits } })
useSettingsStore.setState(s => ({ settings: { ...s.settings, roadtrip_service_stops_in_days: false } }))
const { result } = await renderRoadtrip()
act(() => result.current.toggleRoadtripMode())
await act(async () => result.current.handleReorder(5, [13, 11]))
expect(actions.reorderAssignments).toHaveBeenCalledWith(42, 5, [13, 12, 11])
})
+53 -17
View File
@@ -1,3 +1,6 @@
import { useLoadRoadtripSettings, useRoadtripSettings } from '../../hooks/useRoadtripSettings'
import { roadtripPreferencesRepo } from '../../repo/roadtripPreferencesRepo'
import { publishRoadtripPreferences } from '../../store/roadtripPreferencesStore'
import { useState, useEffect, useCallback, useMemo, useRef } from 'react'
import { useParams, useNavigate, useSearchParams } from 'react-router'
import { useTripStore } from '../../store/tripStore'
@@ -41,7 +44,7 @@ import {
reanchorAfterInsert,
reanchorAfterRemove,
reanchorByStopOrder,
reanchorAfterReorder, type DryPoint } from '../../components/Roadtrip/roadtripModel'
isServiceStopType, refuelStopTypeFor, reanchorAfterReorder, type DryPoint } from '../../components/Roadtrip/roadtripModel'
import type { RoadtripStopDraft } from '../../components/Roadtrip/RoadtripStopPopup'
import type { RoadtripStopType } from '@trek/shared'
import { usePlaceSelection } from '../../hooks/usePlaceSelection'
@@ -49,7 +52,7 @@ import { usePlannerHistory } from '../../hooks/usePlannerHistory'
import { useAirtrailConnection } from '../../hooks/useAirtrailConnection'
import { useIsTouch } from '../../hooks/useIsTouch'
import { usePluginStore } from '../../store/pluginStore'
import type { Accommodation, TripMember, Day, Place, Reservation, Settings } from '../../types'
import type { Accommodation, TripMember, Day, Place, Reservation } from '../../types'
import { OFM_POSITRON, DEFAULT_MAP_LAT, DEFAULT_MAP_LNG, DEFAULT_MAP_ZOOM } from '../../constants/mapDefaults'
import { useTileUrl } from '../../hooks/useTileUrl'
import { resolvePoolAssignmentId } from './tripPlannerModel'
@@ -82,15 +85,16 @@ export function useTripPlanner() {
const navigate = useNavigate()
const toast = useToast()
const { t, language } = useTranslation()
const { settings, updateSettings } = useSettingsStore()
const { settings } = useSettingsStore()
const roadtripSettings = useRoadtripSettings(s => s, tripId)
// trip-page plugins mount as tabs inside this trip planner (tripId-scoped).
const allPlugins = usePluginStore(s => s.plugins)
const pluginsLoaded = usePluginStore(s => s.loaded)
const placesPhotosEnabled = useAuthStore(s => s.placesPhotosEnabled)
const trip = useTripStore(s => s.trip)
const days = useTripStore(s => s.days)
const places = useTripStore(s => s.places)
const assignments = useTripStore(s => s.assignments)
const allPlaces = useTripStore(s => s.places)
const storedAssignments = useTripStore(s => s.assignments)
const packingItems = useTripStore(s => s.packingItems)
const todoItems = useTripStore(s => s.todoItems)
const categories = useTripStore(s => s.categories)
@@ -121,6 +125,10 @@ export function useTripPlanner() {
// someone planning a road trip stays in it across reloads without it leaking into
// their next, non-driving trip.
const [roadtripMode, setRoadtripMode] = useState<boolean>(() => sessionStorage.getItem(`trip-roadtrip-${tripId}`) === '1')
const assignments = useMemo(() => roadtripMode || roadtripSettings.roadtrip_service_stops_in_days !== false ? storedAssignments : Object.fromEntries(
Object.entries(storedAssignments).map(([dayId, visits]) => [dayId, visits.filter(visit => !isServiceStopType(visit.place?.stop_type))]),
), [roadtripMode, roadtripSettings.roadtrip_service_stops_in_days, storedAssignments])
const places = useMemo(() => roadtripMode || roadtripSettings.roadtrip_service_stops_in_days !== false ? allPlaces : allPlaces.filter(place => !isServiceStopType(place.stop_type)), [roadtripMode, roadtripSettings.roadtrip_service_stops_in_days, allPlaces])
const toggleRoadtripMode = useCallback(() => {
setRoadtripMode(prev => {
const next = !prev
@@ -544,7 +552,11 @@ 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
const dailyTimesActive = !!dayWindow(settings.roadtrip_day_start, settings.roadtrip_day_end)
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)
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 () => {
@@ -556,7 +568,7 @@ export function useTripPlanner() {
const refuel = useRefuelSearch()
const roadtripRoutes = useRoadtripRoutes(
tripId,
roadtripActive ? days : EMPTY_DAYS,
roadtripActive && roadtripPreferencesState.ready ? days : EMPTY_DAYS,
assignments,
routeProfile,
roadtripVias.byDay,
@@ -858,22 +870,26 @@ export function useTripPlanner() {
const roadtripLineColors = useMemo(
() => {
if (!settings.roadtrip_day_colors) return undefined
if (!roadtripSettings.roadtrip_day_colors) return undefined
const hidden = new Set(
roadtripRoutes.days.filter(d => collapsedRoadtripDays.has(d.dayId)).map(d => d.dayNumber),
)
return roadtripRoutes.lineDays.filter(n => !hidden.has(n)).map(n => dayColor(n))
},
[settings.roadtrip_day_colors, roadtripRoutes.lineDays, roadtripRoutes.days, collapsedRoadtripDays],
[roadtripSettings.roadtrip_day_colors, roadtripRoutes.lineDays, roadtripRoutes.days, collapsedRoadtripDays],
)
const saveRoadtripLimit = useCallback(async (key: string, value: number | string | boolean) => {
try {
await updateSettings({ [key]: value } as Partial<Settings>)
if (!can('day_edit', trip) || !roadtripPreferencesState.ready) return
const userId = useAuthStore.getState().user?.id
if (!userId) return
const preferences = await roadtripPreferencesRepo.update(tripId, { [key]: value })
publishRoadtripPreferences(userId, tripId, preferences)
} catch {
toast.error(t('places.saveError'))
}
}, [updateSettings, toast, t])
}, [tripId, trip, can, roadtripPreferencesState.ready, toast, t])
const saveStopDraft = useCallback(async ({ stopType, dwellMinutes }: { stopType: RoadtripStopType | null; dwellMinutes: number }) => {
if (!stopDraft) return
@@ -1421,14 +1437,24 @@ export function useTripPlanner() {
if (!day) return
const line = (day.drivingGeometry ?? day.geometry).map(([lat, lng]) => ({ lat, lng }))
if (line.length < 2) return
const vehicle = roadtripSettings.roadtrip_vehicle
const refuelTypes = refuelStopTypeFor(vehicle === 'electric' || vehicle === 'combustion' ? vehicle : null)
let fromAlongKm = 0
let drivenKm = 0
for (let i = 0; i <= dry.legIndex; i++) {
if (refuelTypes.includes(day.stops[i]?.stopType as 'fuel' | 'charging')) fromAlongKm = drivenKm
const leg = day.legs[i]
if (leg?.mode === 'driving') drivenKm += (leg.distance ?? 0) / 1000
}
void refuel.ask(
`${dayId}:${dry.legIndex}`,
{ lat: dry.lat, lng: dry.lng },
line,
dry.drivenMeters / 1000,
day.stops.map(stop => ({ lat: stop.lat, lng: stop.lng })),
fromAlongKm,
)
}, [roadtripRoutes.days, refuel])
}, [roadtripRoutes.days, refuel, roadtripSettings.roadtrip_vehicle])
/**
* Accepting one hands it to the same popup a corridor hit goes through.
@@ -1446,7 +1472,13 @@ export function useTripPlanner() {
// Before the stop the tank would have run out on, which is the leg the dry point
// names. A station reached after the day's last stop is tomorrow's problem, and
// clamping it onto the final leg would re-route the arrival through it.
const at = Math.min(dry.legIndex + 1, day.stops.length - 1)
let drivenKm = 0
const stationLeg = day.legs.findIndex(leg => {
if (leg?.mode !== 'driving') return false
drivenKm += (leg.distance ?? 0) / 1000
return poi.alongKm <= drivenKm
})
const at = Math.min((stationLeg >= 0 ? stationLeg : dry.legIndex) + 1, day.stops.length - 1)
// That index counts along the CARD, and after a night drive a card is not one stored
// day: its first stops belong to yesterday. The new stop goes in front of the one it
// was measured against, so it is that stop's own day and position that place it —
@@ -1767,11 +1799,14 @@ export function useTripPlanner() {
// pinned behind instead of being shifted arithmetically. Without this the
// day's detours stayed on their old numbers and the drive quietly took a
// different road, persisted and visible to every collaborator.
const visible = new Set(orderedIds)
let nextVisible = 0
const completeOrder = prevIds.map(id => visible.has(id) ? orderedIds[nextVisible++] : id)
const stopIdsBefore = roadtripStopsOf(dayId).map(a => a.id)
const stopIdsAfter = orderedIds.filter(id => stopIdsBefore.includes(id))
const stopIdsAfter = completeOrder.filter(id => stopIdsBefore.includes(id))
const plan = reanchorByStopOrder(roadtripVias.byDay[dayId] ?? [], stopIdsBefore, stopIdsAfter)
try {
tripActions.reorderAssignments(tripId, dayId, orderedIds)
tripActions.reorderAssignments(tripId, dayId, completeOrder)
.then(async () => {
if (plan.vias.length || plan.remove.length) await roadtripVias.reanchor(dayId, plan)
const capturedDayId = dayId
@@ -2069,7 +2104,7 @@ export function useTripPlanner() {
return {
tripId, navigate, toast, t, language, settings, placesPhotosEnabled,
trip, days, places, assignments, packingItems, todoItems, categories, reservations, budgetItems, files,
trip, days, places, assignments, storedAssignments, packingItems, todoItems, categories, reservations, budgetItems, files,
selectedDayId, isLoading, tripActions, can, canUploadFiles,
pushUndo, undo, canUndo, lastActionLabel, handleUndo,
enabledAddons, collabFeatures, tripAccommodations, setTripAccommodations,
@@ -2088,7 +2123,8 @@ export function useTripPlanner() {
stopDraft, setStopDraft, saveStopDraft, saveStopDraftAsNight, stopDraftToForm, stopDraftDuplicate, reorderRoadtripStop,
setRoadtripStopKind,
setRoadtripStopFill,
saveRoadtripLimit,
roadtripSettingsLoading: !roadtripPreferencesState.ready && !roadtripPreferencesState.failed,
saveRoadtripLimit: roadtripPreferencesState.ready && can('day_edit', trip) ? saveRoadtripLimit : undefined,
roadtripVias, addRoadtripVia, moveRoadtripVia, removeRoadtripVia, dayBoundaryControls, resetDayBoundaries,
refuel, askRefuel, acceptRefuel,
routeAlternatives, askRouteAlternatives, chooseRouteAlternative, alternativeOverlays, alternativeFocusPoints, mapFocusPoints, roadtripMapVias, focusRoadtripPoint,
@@ -0,0 +1,44 @@
import 'fake-indexeddb/auto'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { roadtripPreferencesRepo } from './roadtripPreferencesRepo'
import { offlineDb, clearAll } from '../db/offlineDb'
import { isEffectivelyOffline } from '../sync/networkMode'
import { mutationQueue } from '../sync/mutationQueue'
import { apiClient } from '../api/client'
vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn(() => true) }))
vi.mock('../sync/authGate', () => ({ isAuthed: () => true }))
vi.mock('../api/client', () => ({ apiClient: { get: vi.fn(), put: vi.fn(), request: vi.fn() } }))
beforeEach(async () => {
await clearAll()
vi.clearAllMocks()
vi.mocked(isEffectivelyOffline).mockReturnValue(true)
await offlineDb.roadtripPreferences.put({ tripId: 9, preferences: { roadtrip_day_start: '08:00', roadtrip_day_end: '18:00', roadtrip_range_km: 120 } })
})
describe('trip driving preferences offline cache', () => {
it('overlays queued changes and replays into the same trip', async () => {
await roadtripPreferencesRepo.update(9, { roadtrip_range_km: 200 })
expect((await roadtripPreferencesRepo.read(9)).roadtrip_range_km).toBe(200)
expect((await offlineDb.roadtripPreferences.get(9))?.preferences.roadtrip_range_km).toBe(120)
expect(await offlineDb.mutationQueue.toArray()).toEqual([expect.objectContaining({ tripId: 9, url: '/trips/9/roadtrip/preferences', method: 'PUT', body: { roadtrip_range_km: 200 } })])
vi.mocked(isEffectivelyOffline).mockReturnValue(false)
vi.mocked(apiClient.request).mockResolvedValue({ data: { tripId: 9, preferences: { roadtrip_range_km: 200 } } })
await mutationQueue.flush()
expect(await offlineDb.mutationQueue.count()).toBe(0)
expect((await offlineDb.roadtripPreferences.get(9))?.preferences.roadtrip_range_km).toBe(200)
expect(await offlineDb.roadtripPreferences.get(10)).toBeUndefined()
})
it('refuses an uncached trip and an invalid merged day window', async () => {
await expect(roadtripPreferencesRepo.read(10)).rejects.toThrow('not available offline')
await expect(roadtripPreferencesRepo.update(9, { roadtrip_day_end: '07:00' })).rejects.toThrow('Day end')
expect(await offlineDb.mutationQueue.count()).toBe(0)
})
it('keeps cached preferences on a rejected online update', async () => {
vi.mocked(isEffectivelyOffline).mockReturnValue(false)
vi.mocked(apiClient.put).mockRejectedValue(new Error('Denied'))
await expect(roadtripPreferencesRepo.update(9, { roadtrip_range_km: 999 })).rejects.toThrow('Denied')
expect((await offlineDb.roadtripPreferences.get(9))?.preferences.roadtrip_range_km).toBe(120)
})
})
@@ -0,0 +1,55 @@
import { roadtripPreferencesResponseSchema, roadtripPreferencesUpdateSchema, type RoadtripPreferences } from '@trek/shared'
import { apiClient } from '../api/client'
import { offlineDb } from '../db/offlineDb'
import { generateUUID, mutationQueue } from '../sync/mutationQueue'
import { isEffectivelyOffline } from '../sync/networkMode'
import { onlineThenCache } from './withOfflineFallback'
export async function cachedRoadtripPreferences(tripId: number, excludeMutation?: string): Promise<RoadtripPreferences> {
const cached = await offlineDb.roadtripPreferences.get(tripId)
if (!cached) throw new Error('Driving settings are not available offline.')
const pending = await offlineDb.mutationQueue.where('tripId').equals(tripId).sortBy('createdAt')
return pending.reduce((preferences, mutation) => {
if (mutation.resource !== 'roadtripPreferences' || mutation.id === excludeMutation || !['pending', 'syncing'].includes(mutation.status)) return preferences
return { ...preferences, ...roadtripPreferencesUpdateSchema.parse(mutation.body) }
}, cached.preferences)
}
const writes = new Map<number, Promise<RoadtripPreferences>>()
export const roadtripPreferencesRepo = {
async read(tripId: number): Promise<RoadtripPreferences> {
const cacheName = offlineDb.name
return onlineThenCache(async () => {
const fetched = await apiClient.get(`/trips/${tripId}/roadtrip/preferences`)
if (offlineDb.name !== cacheName) throw new Error('Account changed.')
const saved = roadtripPreferencesResponseSchema.parse(fetched.data)
await offlineDb.roadtripPreferences.put(saved)
return cachedRoadtripPreferences(tripId)
}, () => cachedRoadtripPreferences(tripId))
},
update(tripId: number, patch: RoadtripPreferences): Promise<RoadtripPreferences> {
const cacheName = offlineDb.name
const save = (writes.get(tripId) ?? Promise.resolve({})).catch(() => ({})).then(async () => {
if (offlineDb.name !== cacheName) throw new Error('Account changed.')
const validated = roadtripPreferencesUpdateSchema.parse(patch)
if (!isEffectivelyOffline()) {
const saved = await apiClient.put(`/trips/${tripId}/roadtrip/preferences`, validated)
if (offlineDb.name !== cacheName) throw new Error('Account changed.')
await offlineDb.roadtripPreferences.put(roadtripPreferencesResponseSchema.parse(saved.data))
} else {
const next = { ...await cachedRoadtripPreferences(tripId), ...validated }
if (next.roadtrip_day_start && next.roadtrip_day_end && next.roadtrip_day_end <= next.roadtrip_day_start) throw new Error('Day end must be later than day start.')
await mutationQueue.enqueue({
id: generateUUID(), tripId, method: 'PUT', url: `/trips/${tripId}/roadtrip/preferences`,
body: validated, resource: 'roadtripPreferences', entityId: tripId,
})
}
return cachedRoadtripPreferences(tripId)
})
writes.set(tripId, save)
void save.finally(() => { if (writes.get(tripId) === save) writes.delete(tripId) }).catch(() => {})
return save
},
}
@@ -0,0 +1,14 @@
import { create } from 'zustand'
import type { RoadtripPreferences } from '@trek/shared'
export const EMPTY_ROADTRIP_PREFERENCES: RoadtripPreferences = {}
export const useRoadtripPreferencesStore = create<{
byTrip: Record<string, RoadtripPreferences>
}>(() => ({ byTrip: {} }))
export function publishRoadtripPreferences(userId: number, tripId: number, preferences: RoadtripPreferences) {
useRoadtripPreferencesStore.setState(state => ({
byTrip: { ...state.byTrip, [`${userId}:${tripId}`]: preferences },
}))
}
+5 -1
View File
@@ -13,7 +13,7 @@ import { getOfflinePrefs } from './offlinePrefs'
import { randomId } from '../utils/randomId'
import type { QueuedMutation } from '../db/offlineDb'
import type { Table } from 'dexie'
import { assignmentSchema } from '@trek/shared'
import { roadtripPreferencesResponseSchema, assignmentSchema } from '@trek/shared'
import { cacheAssignment } from '../db/cacheAssignment'
// Map Dexie table names used in `resource` field → actual Dexie tables.
@@ -195,6 +195,10 @@ export const mutationQueue = {
headers,
})
if (mutation.resource === 'roadtripPreferences') {
const saved = roadtripPreferencesResponseSchema.parse(response.data)
await offlineDb.roadtripPreferences.put(saved)
}
// Apply canonical server response to Dexie
if (mutation.resource === 'assignments') {
await cacheAssignment(assignmentSchema.parse(response.data.assignment))
@@ -357,3 +357,5 @@ describe('tripSyncManager.syncAll — background tile pass', () => {
expect(prefetchMock).not.toHaveBeenCalled()
})
})
vi.mock('../repo/roadtripPreferencesRepo', () => ({ roadtripPreferencesRepo: { read: vi.fn(async () => ({})) } }))
+4
View File
@@ -1,3 +1,4 @@
import { roadtripPreferencesRepo } from '../repo/roadtripPreferencesRepo'
/**
* Trip sync manager — seeds Dexie with trip data for offline use.
*
@@ -114,6 +115,9 @@ function isVideo(file: TripFile): boolean {
async function syncTrip(tripId: number): Promise<void> {
const bundle = await tripsApi.bundle(tripId) as TripBundle
await roadtripPreferencesRepo.read(tripId).catch((error: unknown) => {
if ((error as { response?: { status?: number } }).response?.status !== 404) throw error
})
await upsertTrip(bundle.trip)
await upsertDays(bundle.days)
await upsertPlaces(bundle.places)