mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 00:20:07 +00:00
feat(roadtrip): suggest where to fill up, not just warn that you cannot
The range budget has always been able to say "you have driven 245 km on this tank" and never "and here is where to do something about it". The review put it plainly: the value is in the suggestion, not in the warning. The warning sits on the stop the car ARRIVES at, which is where somebody finds out. The fuel runs out earlier, often most of a leg earlier, and a filling station offered at the warning is one the car cannot reach. So the dry point is computed where it actually is, a search runs around it on request, and what comes back is filtered to what can be reached. Three filters, each one there because its absence gives a wrong answer rather than an untidy one. Only what lies before the tank empties, because a pump past it is on the far side of an empty tank. The detour counts double, because 8 km off the road is 16 km of driving. And a reserve is kept back, because the range figure is a round number from a manual, not a measurement. Sorted by the detour rather than by how far it gets. Measured on a real day between Hamburg and Berlin: the station that got furthest was 9.2 km off the road for one kilometre more of range, while one 0.9 km off sat almost as late. Deduplicated by name and half a kilometre, which also came out of that measurement. OSM maps a charging site as one node per socket: the first three offers were the same "autostrom plus GmbH" three times over. The four nodes sat in two pairs 6 m and 7 m apart with 450 m between the pairs, while genuinely different branches of one chain were 18 to 36 km apart — so anything from 500 m upwards separates the two cases. An empty answer says which kind of empty it is. "Nothing on the reachable stretch" after a request that failed or was cut short states something that was never checked, and the server flags both cases itself. Offline it does not offer at all: the place write queues offline but the day assignment does not, so accepting one would leave an orphan. Nothing is searched until it is asked for, and one press is one request against a small circle rather than the sixteen boxes a corridor run costs. Accepting hands the choice to the same popup a corridor hit goes through, so the stop kind, the dwell time, the position, the via re-anchoring and the re-route are the paths that already work. The dry point counts DRIVING metres only. The day's drawn line concatenates every run, ferries and walks included, while the budget skips those, so walking that line to the same figure would overshoot by the length of any crossing and put the marker out at sea.
This commit is contained in:
@@ -5,6 +5,9 @@ import {
|
||||
type LucideIcon,
|
||||
} from 'lucide-react'
|
||||
import MDancingTrek from '../../mobile/components/MDancingTrek'
|
||||
import type { RefuelSearch } from './useRefuelSearch'
|
||||
import type { RefuelCandidate } from './refuelSuggestion'
|
||||
import type { DryPoint } from './roadtripModel'
|
||||
import { useTranslation } from '../../i18n/TranslationContext'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
@@ -35,6 +38,15 @@ interface RoadtripSidebarProps {
|
||||
onMoveStopToDay?: (fromDayId: number, assignmentId: number, toDayId: number, toIndex: number) => void
|
||||
/** Asks for other ways of driving one leg (#1797). */
|
||||
onAskAlternatives?: (dayId: number, legIndex: number) => void
|
||||
/**
|
||||
* The one-shot search for somewhere to fill up before the tank runs out.
|
||||
*
|
||||
* Absent leaves the range findings as they were, a warning and nothing else — which is
|
||||
* also what a viewer sees, since accepting one writes a stop.
|
||||
*/
|
||||
refuel?: RefuelSearch
|
||||
onAskRefuel?: (dayId: number, dry: DryPoint & { lat: number; lng: number }) => void
|
||||
onAcceptRefuel?: (dayId: number, poi: RefuelCandidate, dry: DryPoint & { lat: number; lng: number }) => void
|
||||
/** Which leg's alternatives are on show, so the rail can mark it. */
|
||||
openAlternatives?: { dayId: number; index: number } | null
|
||||
/**
|
||||
@@ -292,6 +304,108 @@ function TripSummary({ routes }: { routes: RoadtripRoutes }): React.ReactElement
|
||||
* distance and the time belong together, and it leaves the row's right edge for the
|
||||
* button instead of a second number.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Where the tank runs out on this leg, and somewhere to do something about it.
|
||||
*
|
||||
* Sits under the drive band rather than on the stop that carries the range warning,
|
||||
* because those are two different places: the warning is filed where somebody finds out,
|
||||
* this is where the fuel actually ends. A filling station offered at the warning is one
|
||||
* the car cannot reach.
|
||||
*
|
||||
* Nothing is searched until it is asked for. Every press is a real request against a
|
||||
* shared service, which is the same reason the corridor search next door is manual.
|
||||
*/
|
||||
function RefuelBand({ dry, refuel, dayId, onAsk, onAccept }: {
|
||||
dry: DryPoint & { lat: number; lng: number }
|
||||
refuel: RefuelSearch
|
||||
dayId: number
|
||||
onAsk: () => void
|
||||
onAccept?: (poi: RefuelCandidate) => void
|
||||
}): React.ReactElement {
|
||||
const { t } = useTranslation()
|
||||
const distanceUnit = useSettingsStore(s => s.settings.distance_unit)
|
||||
const key = `${dayId}:${dry.legIndex}`
|
||||
const open = refuel.openFor === key
|
||||
|
||||
return (
|
||||
<div className="my-1 ms-[30px] flex flex-col gap-1.5 rounded-lg border border-edge-faint bg-surface-secondary px-2.5 py-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Fuel size={12} className="shrink-0 text-content-faint" aria-hidden />
|
||||
<span className="min-w-0 flex-1 text-content-secondary" style={{ fontSize: FS.label }}>
|
||||
{t('roadtrip.refuel.dry', { distance: formatDistance(dry.sinceKm, distanceUnit) })}
|
||||
</span>
|
||||
{open ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={refuel.close}
|
||||
className="shrink-0 rounded px-1.5 py-0.5 text-content-faint transition-colors hover:text-content focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||
style={{ fontSize: FS.label }}
|
||||
>
|
||||
{t('common.close')}
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onAsk}
|
||||
className="shrink-0 rounded bg-surface-card px-2 py-0.5 font-semibold text-content-secondary transition-colors hover:bg-surface-hover hover:text-content focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||
style={{ fontSize: FS.label }}
|
||||
>
|
||||
{t('roadtrip.refuel.find')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{open && refuel.loading ? (
|
||||
<span className="text-content-faint" style={{ fontSize: FS.label }}>{t('roadtrip.refuel.looking')}</span>
|
||||
) : null}
|
||||
|
||||
{open && !refuel.loading && refuel.outcome ? (
|
||||
refuel.results.length ? (
|
||||
<ul className="flex flex-col gap-1">
|
||||
{/* Three at most. This is an offer beside a plan, not a list to browse; the
|
||||
corridor panel is where somebody goes to see all of them. */}
|
||||
{refuel.results.slice(0, 3).map(poi => (
|
||||
<li key={poi.osm_id} className="flex items-center gap-2">
|
||||
<span className="min-w-0 flex-1 truncate text-content" style={{ fontSize: FS.label }}>
|
||||
{poi.name}
|
||||
</span>
|
||||
<span className="shrink-0 tabular-nums text-content-faint" style={{ fontSize: FS.label }}>
|
||||
{/* What is left when the car draws level, which is the figure that
|
||||
decides whether this one is any use. The detour is in it already. */}
|
||||
{t('roadtrip.refuel.spare', { distance: formatDistance(Math.round(poi.spareKm), distanceUnit) })}
|
||||
</span>
|
||||
{onAccept ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onAccept(poi)}
|
||||
aria-label={t('roadtrip.refuel.add', { name: poi.name })}
|
||||
className="shrink-0 rounded bg-surface-card px-1.5 py-0.5 font-semibold text-content-secondary transition-colors hover:bg-surface-hover hover:text-content focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||
style={{ fontSize: FS.label }}
|
||||
>
|
||||
+
|
||||
</button>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
/* Three different sentences for three different facts. "Nothing on this
|
||||
stretch" after a request that failed or was cut short states something that
|
||||
was never checked, and that is worse than saying nothing. */
|
||||
<span className="text-content-faint" style={{ fontSize: FS.label }}>
|
||||
{refuel.outcome === 'none'
|
||||
? t('roadtrip.refuel.none')
|
||||
: refuel.outcome === 'incomplete'
|
||||
? t('roadtrip.refuel.incomplete')
|
||||
: t('roadtrip.refuel.failed')}
|
||||
</span>
|
||||
)
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DriveBand({ leg, onAskAlternatives, alternativesOpen }: {
|
||||
leg: RouteSegment | undefined
|
||||
/** Asks for other ways of driving this leg. Absent means the route is not editable. */
|
||||
@@ -813,7 +927,7 @@ function LateBadge({ late }: { late: ScheduleWarning | undefined }): React.React
|
||||
* (`dayOrderMap` numbers the selected day's assignments from 1). A rail counting across
|
||||
* the trip would put "17" beside a pin the map calls "3".
|
||||
*/
|
||||
function DaySection({ day, selectedAssignmentId, onSelectStop, onReorderStop, onMoveStopToDay, drag, onAskAlternatives, openAlternatives, onEditStay, onSetStopKind, onFollowTrack, viaCount, trackName }: {
|
||||
function DaySection({ day, selectedAssignmentId, onSelectStop, onReorderStop, onMoveStopToDay, drag, onAskAlternatives, openAlternatives, onEditStay, onSetStopKind, onFollowTrack, viaCount, trackName, refuel, onAskRefuel, onAcceptRefuel, loading }: {
|
||||
day: RoadtripDay
|
||||
selectedAssignmentId?: number | null
|
||||
onSelectStop?: (placeId: number, assignmentId: number) => void
|
||||
@@ -828,6 +942,11 @@ function DaySection({ day, selectedAssignmentId, onSelectStop, onReorderStop, on
|
||||
onFollowTrack?: RoadtripSidebarProps['onFollowTrack']
|
||||
viaCount?: number
|
||||
trackName?: string
|
||||
refuel?: RefuelSearch
|
||||
onAskRefuel?: RoadtripSidebarProps['onAskRefuel']
|
||||
onAcceptRefuel?: RoadtripSidebarProps['onAcceptRefuel']
|
||||
/** True while any day is still routing; the range findings are not settled until then. */
|
||||
loading?: boolean
|
||||
}): React.ReactElement {
|
||||
const { from, setFrom, dropAt, setDropAt } = drag
|
||||
const dragging = from?.dayId === day.dayId ? from.index : null
|
||||
@@ -1002,6 +1121,24 @@ function DaySection({ day, selectedAssignmentId, onSelectStop, onReorderStop, on
|
||||
alternativesOpen={openAlternatives?.dayId === day.dayId && openAlternatives.index === i}
|
||||
/>
|
||||
) : null}
|
||||
{/* Only on the leg the fuel actually runs out on, and only once the day has
|
||||
finished routing: the warnings are republished after every routing task
|
||||
and the early ones are wrong, so an offer that appears and moves while
|
||||
the trip loads reads as a fault. */}
|
||||
{refuel && !loading
|
||||
? (day.dryPoints ?? [])
|
||||
.filter(dry => dry.legIndex === i)
|
||||
.map(dry => (
|
||||
<RefuelBand
|
||||
key={`dry-${dry.legIndex}`}
|
||||
dry={dry}
|
||||
dayId={day.dayId}
|
||||
refuel={refuel}
|
||||
onAsk={() => onAskRefuel?.(day.dayId, dry)}
|
||||
onAccept={onAcceptRefuel ? poi => onAcceptRefuel(day.dayId, poi, dry) : undefined}
|
||||
/>
|
||||
))
|
||||
: null}
|
||||
{/* After the band, because a plugin halt happens on the drive it describes
|
||||
rather than before setting off. */}
|
||||
{i < last ? (day.legVias[i] ?? []).map((via, vi) => (
|
||||
@@ -1100,7 +1237,7 @@ function QuietDaySection({ day, onMoveStopToDay, drag }: {
|
||||
*/
|
||||
export default function RoadtripSidebar({
|
||||
routes, selectedAssignmentId, onSelectStop, onReorderStop, onMoveStopToDay, onAskAlternatives, openAlternatives, onEditStay,
|
||||
onSetStopKind, onFollowTrack, viaCounts, trackNames,
|
||||
onSetStopKind, onFollowTrack, viaCounts, trackNames, refuel, onAskRefuel, onAcceptRefuel,
|
||||
}: RoadtripSidebarProps): React.ReactElement {
|
||||
const { t } = useTranslation()
|
||||
// One drag state for the whole rail rather than one per day: a stop that cannot leave
|
||||
@@ -1155,6 +1292,10 @@ export default function RoadtripSidebar({
|
||||
onFollowTrack={onFollowTrack}
|
||||
viaCount={viaCounts?.[day.dayId] ?? 0}
|
||||
trackName={trackNames?.[day.dayId]}
|
||||
refuel={refuel}
|
||||
onAskRefuel={onAskRefuel}
|
||||
onAcceptRefuel={onAcceptRefuel}
|
||||
loading={routes.loading}
|
||||
/>
|
||||
))}
|
||||
{routes.quietDays.map(day => (
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { reachableRefuels, outcomeOf } from './refuelSuggestion'
|
||||
import type { LatLng } from './corridor'
|
||||
import type { Poi } from '../Map/poiCategories'
|
||||
|
||||
// A straight run due east at 52° north, where a degree of longitude is about 68.5 km.
|
||||
const LINE: LatLng[] = [
|
||||
{ lat: 52, lng: 13 },
|
||||
{ lat: 52, lng: 14 },
|
||||
{ lat: 52, lng: 15 },
|
||||
]
|
||||
|
||||
const poi = (name: string, lat: number, lng: number): Poi =>
|
||||
({ osm_id: `node:${name}`, name, lat, lng } as Poi)
|
||||
|
||||
describe('reachableRefuels', () => {
|
||||
it('FE-ROADTRIP-REFUEL-001: offers only what lies before the tank runs out', () => {
|
||||
// Dry at 100 km in. A pump at 50 km is reachable; one at 130 km is on the far side
|
||||
// of an empty tank, and offering it is offering a walk.
|
||||
const early = poi('early', 52, 13.73) // ~50 km
|
||||
const late = poi('late', 52, 14.9) // ~130 km
|
||||
const out = reachableRefuels([early, late], LINE, 100)
|
||||
expect(out.map(p => p.name)).toEqual(['early'])
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-REFUEL-002: the detour counts twice, because it is driven out and back', () => {
|
||||
// Both sit at the same point along the road, 60 km in, with 100 km of range. One is
|
||||
// on the road; the other is 20 km off it, so 40 km of driving, which no longer fits
|
||||
// in the 40 km that are left once the reserve is kept back.
|
||||
const onRoad = poi('on-road', 52, 13.876)
|
||||
const offRoad = poi('off-road', 52.18, 13.876) // ~20 km north
|
||||
const out = reachableRefuels([onRoad, offRoad], LINE, 100)
|
||||
expect(out.map(p => p.name)).toEqual(['on-road'])
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-REFUEL-003: a reserve is kept back, so nobody is sent to the last drop', () => {
|
||||
// 8 km before the dry point is inside the ten kilometre reserve.
|
||||
const onTheLimit = poi('on-the-limit', 52, 14.34) // ~93 km
|
||||
expect(reachableRefuels([onTheLimit], LINE, 100)).toEqual([])
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-REFUEL-004: the smallest detour comes first, however late the others sit', () => {
|
||||
// Measured on a real day: the station that got furthest was 9.2 km off the road for
|
||||
// one kilometre more of range. Everything in this list is already reachable, so what
|
||||
// separates them is what the stop costs.
|
||||
const nearRoad = poi('near-road', 52, 13.15) // on the line, early
|
||||
const bigDetour = poi('big-detour', 52.05, 13.9) // ~5.5 km off, later
|
||||
const out = reachableRefuels([bigDetour, nearRoad], LINE, 100)
|
||||
expect(out.map(p => p.name)).toEqual(['near-road', 'big-detour'])
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-REFUEL-009: with the same detour, the later one wins', () => {
|
||||
// Filling up early wastes the tank that was already paid for.
|
||||
const early = poi('early', 52, 13.15)
|
||||
const later = poi('later', 52, 14.16)
|
||||
const out = reachableRefuels([early, later], LINE, 100)
|
||||
expect(out.map(p => p.name)).toEqual(['later', 'early'])
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-REFUEL-005: a pump already on the plan is not suggested next to itself', () => {
|
||||
// Matched on position, not on id: the same station added by hand or from another
|
||||
// source carries a different osm_id.
|
||||
const pump = poi('pump', 52, 13.73)
|
||||
const out = reachableRefuels([pump], LINE, 100, { existing: [{ lat: 52.0005, lng: 13.7302 }] })
|
||||
expect(out).toEqual([])
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-REFUEL-006: something nowhere near the road is not on the way', () => {
|
||||
const wayOff = poi('way-off', 49, 13.5)
|
||||
expect(reachableRefuels([wayOff], LINE, 100)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('outcomeOf', () => {
|
||||
it('FE-ROADTRIP-REFUEL-007: no answer is not the same as no filling station', () => {
|
||||
// The distinction the whole band hangs on. Saying "none on this stretch" after a
|
||||
// failed request states a fact that was never checked.
|
||||
expect(outcomeOf([], null)).toBe('failed')
|
||||
expect(outcomeOf([], { truncated: true })).toBe('incomplete')
|
||||
expect(outcomeOf([], { clamped: true })).toBe('incomplete')
|
||||
expect(outcomeOf([], {})).toBe('none')
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-REFUEL-008: a hit is a hit even when the answer was cut short', () => {
|
||||
const found = [{ name: 'x' }] as never
|
||||
expect(outcomeOf(found, { truncated: true })).toBe('found')
|
||||
})
|
||||
})
|
||||
|
||||
describe('reachableRefuels — one entry per station', () => {
|
||||
const at = (name: string, lat: number, lng: number): Poi =>
|
||||
({ osm_id: `node:${name}-${lat}-${lng}`, name, lat, lng } as Poi)
|
||||
|
||||
it('FE-ROADTRIP-REFUEL-010: a charging site mapped as one node per socket is offered once', () => {
|
||||
// Measured on a real day: the top three offers were the same "autostrom plus GmbH"
|
||||
// three times over, because OSM maps every socket as its own node.
|
||||
// The real shape of it: four nodes in two pairs, 6 m and 7 m apart, with 450 m
|
||||
// between the pairs.
|
||||
const sockets = [
|
||||
at('autostrom plus GmbH', 52, 13.3),
|
||||
at('autostrom plus GmbH', 52.00005, 13.30005),
|
||||
at('autostrom plus GmbH', 52.004, 13.3005),
|
||||
at('autostrom plus GmbH', 52.00405, 13.30045),
|
||||
]
|
||||
const out = reachableRefuels(sockets, LINE, 100)
|
||||
expect(out).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-REFUEL-011: the same chain in two towns stays two entries', () => {
|
||||
// Name alone is not identity: a chain has a branch everywhere.
|
||||
// Measured: genuinely different branches were 18 to 36 km apart.
|
||||
const out = reachableRefuels([at('Aral', 52, 13.2), at('Aral', 52, 13.6)], LINE, 100)
|
||||
expect(out).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-REFUEL-012: two operators sharing one services are both offered', () => {
|
||||
// Position alone is not identity either.
|
||||
const out = reachableRefuels([at('Aral', 52, 13.3), at('Shell', 52.0003, 13.3)], LINE, 100)
|
||||
expect(out.map(p => p.name).sort()).toEqual(['Aral', 'Shell'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,120 @@
|
||||
import { haversineKm, projectOntoRoute, type LatLng } from './corridor'
|
||||
import type { Poi } from '../Map/poiCategories'
|
||||
|
||||
/**
|
||||
* Picking a filling station for a tank that is about to run out.
|
||||
*
|
||||
* Pure: no React, no network. The caller does the one request and hands the answers
|
||||
* here, which keeps the judgement — which of these can the car actually reach — testable
|
||||
* without a server.
|
||||
*/
|
||||
|
||||
/** A candidate, with the two figures that decide whether it is any use. */
|
||||
export interface RefuelCandidate extends Poi {
|
||||
/** Kilometres along the day's driving line, in the same space as the dry point. */
|
||||
alongKm: number
|
||||
/** How far off the road it sits. */
|
||||
offRouteKm: number
|
||||
/** Kilometres of range still in the tank when the car draws level with it. */
|
||||
spareKm: number
|
||||
}
|
||||
|
||||
/**
|
||||
* How much of the last drop to keep back, in kilometres.
|
||||
*
|
||||
* Arriving at a pump with nothing left is not a plan, and the range figure a traveller
|
||||
* types is a round number from a manual rather than a measurement. Ten kilometres is
|
||||
* small enough not to move the suggestion and large enough not to promise the
|
||||
* impossible.
|
||||
*/
|
||||
const RESERVE_KM = 10
|
||||
|
||||
/**
|
||||
* The stations that can actually be reached, nearest to the dry point first.
|
||||
*
|
||||
* Three filters, and each one exists because its absence produces a wrong answer rather
|
||||
* than an untidy one:
|
||||
*
|
||||
* - Only what lies BEFORE the point the tank empties. A station 20 km past it is on the
|
||||
* far side of an empty tank, and offering it is offering a walk.
|
||||
* - The detour counts double. A pump 8 km off the road is 16 km of driving, and on a
|
||||
* tank this close to empty that is the difference between arriving and not.
|
||||
* - What is left has to fit in the range that remains, minus a reserve.
|
||||
*
|
||||
* Sorted by the detour, not by how far along the road it sits. Measured against a real
|
||||
* day: the station that got furthest was 9.2 km off the road for one kilometre more of
|
||||
* range, while one 0.9 km off sat almost as late. Everything in this list is already
|
||||
* reachable, so what separates them is what the stop costs, and that is the detour. Ties
|
||||
* go to the later one, because filling up early wastes the tank you already paid for.
|
||||
*/
|
||||
export function reachableRefuels(
|
||||
pois: Poi[],
|
||||
line: LatLng[],
|
||||
dryAlongKm: number,
|
||||
{ existing = [] }: { existing?: { lat: number; lng: number }[] } = {},
|
||||
): RefuelCandidate[] {
|
||||
const out: RefuelCandidate[] = []
|
||||
for (const poi of pois) {
|
||||
const hit = projectOntoRoute({ lat: poi.lat, lng: poi.lng }, line)
|
||||
if (!hit) continue
|
||||
// Reached before the tank empties, once the detour out and back is paid for.
|
||||
const spareKm = dryAlongKm - hit.alongKm - hit.offRouteKm * 2 - RESERVE_KM
|
||||
if (spareKm < 0) continue
|
||||
// Already planned. Matched on position rather than on id: the same pump added by
|
||||
// hand, or from another source, carries a different osm_id and would otherwise be
|
||||
// suggested next to itself.
|
||||
if (existing.some(e => haversineKm(e, { lat: poi.lat, lng: poi.lng }) < 0.15)) continue
|
||||
out.push({ ...poi, alongKm: hit.alongKm, offRouteKm: hit.offRouteKm, spareKm })
|
||||
}
|
||||
return oneEach(out.sort((a, b) => a.offRouteKm - b.offRouteKm || a.spareKm - b.spareKm))
|
||||
}
|
||||
|
||||
/**
|
||||
* What a search actually established, as opposed to what it returned.
|
||||
*
|
||||
* An empty list means one of two very different things, and saying the wrong one is
|
||||
* worse than saying nothing: either there is no filling station on this stretch, or we
|
||||
* never managed to look. The server flags the second case itself (`truncated` when it
|
||||
* hit its own ceiling, `clamped` when it narrowed the area), and a failed request is the
|
||||
* third. Only `none` is a statement about the road.
|
||||
*/
|
||||
export type RefuelOutcome = 'found' | 'none' | 'incomplete' | 'failed'
|
||||
|
||||
export function outcomeOf(
|
||||
candidates: RefuelCandidate[],
|
||||
answer: { truncated?: boolean; clamped?: boolean } | null,
|
||||
): RefuelOutcome {
|
||||
if (!answer) return 'failed'
|
||||
if (candidates.length) return 'found'
|
||||
return answer.truncated || answer.clamped ? 'incomplete' : 'none'
|
||||
}
|
||||
|
||||
/**
|
||||
* One entry per filling station, not one per pump.
|
||||
*
|
||||
* A charging site is mapped in OSM as a node per socket and a forecourt often as one per
|
||||
* pump, all with the same name a few metres apart. Deduplicating by id keeps every one of
|
||||
* them, which is right on a map and wrong in a list of three offers: measured on a real
|
||||
* day, the top three were the same "autostrom plus GmbH" three times over.
|
||||
*
|
||||
* Same name and within half a kilometre counts as the same place. Both halves matter:
|
||||
* not position alone, because two operators do share a motorway services, and not name
|
||||
* alone, because a chain has a branch in every town.
|
||||
*
|
||||
* Half a kilometre comes from the data rather than from taste. In one 25 km search the
|
||||
* four nodes of one charging site sat in two pairs, 6 m and 7 m apart, with 450 m between
|
||||
* the pairs — while genuinely different branches of the same chain were 18 to 36 km
|
||||
* apart. Anything from 500 m to a few kilometres separates those two cases; the lower end
|
||||
* is the safer place to stand.
|
||||
*/
|
||||
const SAME_PLACE_KM = 0.5
|
||||
|
||||
function oneEach(sorted: RefuelCandidate[]): RefuelCandidate[] {
|
||||
const kept: RefuelCandidate[] = []
|
||||
for (const poi of sorted) {
|
||||
const twin = kept.some(k =>
|
||||
k.name === poi.name && haversineKm(k, { lat: poi.lat, lng: poi.lng }) < SAME_PLACE_KM)
|
||||
if (!twin) kept.push(poi)
|
||||
}
|
||||
return kept
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { useCallback, useRef, useState } from 'react'
|
||||
import { mapsApi } from '../../api/client'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { isEffectivelyOffline } from '../../sync/networkMode'
|
||||
import { boxAround, 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 dry point to look, in kilometres. */
|
||||
const LOOK_KM = 25
|
||||
|
||||
export interface RefuelSearch {
|
||||
/** Which dry point is being answered, as `<dayId>:<legIndex>`, or null when idle. */
|
||||
openFor: string | null
|
||||
loading: boolean
|
||||
outcome: RefuelOutcome | null
|
||||
results: 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>
|
||||
close: () => void
|
||||
}
|
||||
|
||||
export function useRefuelSearch(): RefuelSearch {
|
||||
const { locale } = useTranslation()
|
||||
const [openFor, setOpenFor] = useState<string | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [outcome, setOutcome] = useState<RefuelOutcome | null>(null)
|
||||
const [results, setResults] = useState<RefuelCandidate[]>([])
|
||||
const abortRef = useRef<AbortController | null>(null)
|
||||
|
||||
const close = useCallback(() => {
|
||||
abortRef.current?.abort()
|
||||
abortRef.current = null
|
||||
setOpenFor(null)
|
||||
setResults([])
|
||||
setOutcome(null)
|
||||
setLoading(false)
|
||||
}, [])
|
||||
|
||||
const ask = useCallback(async (
|
||||
key: string,
|
||||
at: LatLng,
|
||||
line: LatLng[],
|
||||
dryAlongKm: number,
|
||||
existing: LatLng[],
|
||||
) => {
|
||||
abortRef.current?.abort()
|
||||
const controller = new AbortController()
|
||||
abortRef.current = controller
|
||||
setOpenFor(key)
|
||||
setResults([])
|
||||
setOutcome(null)
|
||||
|
||||
// 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.
|
||||
if (isEffectivelyOffline()) {
|
||||
setOutcome('failed')
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
try {
|
||||
const answer = await mapsApi.pois('fuel,charging', boxAround(at, LOOK_KM), locale, controller.signal)
|
||||
if (controller.signal.aborted) return
|
||||
const candidates = reachableRefuels(answer.pois, line, dryAlongKm, { existing })
|
||||
setResults(candidates)
|
||||
setOutcome(outcomeOf(candidates, answer))
|
||||
} catch {
|
||||
if (!controller.signal.aborted) setOutcome('failed')
|
||||
} finally {
|
||||
if (!controller.signal.aborted) setLoading(false)
|
||||
}
|
||||
}, [locale])
|
||||
|
||||
return { openFor, loading, outcome, results, ask, close }
|
||||
}
|
||||
@@ -68,6 +68,11 @@ export interface RoadtripDay {
|
||||
* not route — the budget gives up rather than guessing, and so does this.
|
||||
*/
|
||||
dryPoints?: (DryPoint & { lat: number; lng: number })[]
|
||||
/**
|
||||
* `geometry` with the non-driving runs left out, which is what `dryPoints` are measured
|
||||
* along. The same array as `geometry` on a day that drives the whole way.
|
||||
*/
|
||||
drivingGeometry?: [number, number][]
|
||||
/**
|
||||
* The roads actually driven that day, as [lat, lng] — not the straight lines between
|
||||
* stops. Anything asking "what is along this day" has to use this: between Hamburg and
|
||||
@@ -561,8 +566,13 @@ export function useRoadtripRoutes(
|
||||
return at ? { ...dry, lat: at.lat, lng: at.lng } : null
|
||||
})
|
||||
.filter((d): d is DryPoint & { lat: number; lng: number } => d !== null)
|
||||
// The same line the dry points are measured along, so anything offered against
|
||||
// them is projected in the same space. Handed on as the SAME array when the day
|
||||
// drives all the way through, which is nearly every day — only a day carrying a
|
||||
// ferry or a walk pays for a second copy.
|
||||
const drivingGeometry = drivingLine.length === geometry.length ? geometry : drivingLine
|
||||
out.push({
|
||||
...day, stops, legs, legVias, schedule, geometry, distance, duration, dryPoints,
|
||||
...day, stops, legs, legVias, schedule, geometry, distance, duration, dryPoints, drivingGeometry,
|
||||
driveWarnings: drive.warnings,
|
||||
dayWarning: drive.day,
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user