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