mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-06 10:44:23 +00:00
fix(tours): tell a router that did not answer from a walk no way joins, count each boat of a leg on its own into the day and its arrivals
This commit is contained in:
@@ -687,4 +687,21 @@ describe('crossings by boat on a walk (CW-12)', () => {
|
||||
expect(bodies[0].locations.map(location => location.search_filter)).toEqual([{ exclude_ferry: true }, { exclude_ferry: true }])
|
||||
expect(bodies[1].locations.every(location => !('search_filter' in location))).toBe(true)
|
||||
})
|
||||
|
||||
it('VALHALLA-FERRY-006: a "no path" from the router reads apart from a refusal about anything else, asked once', async () => {
|
||||
const points = [{ lat: 45.4342798, lng: 12.338111 }, { lat: 45.4367609, lng: 12.3287531 }]
|
||||
let calls = 0
|
||||
setSettings({ valhalla_base_url: 'https://valhalla.test' })
|
||||
server.use(http.post('https://valhalla.test/route', () => {
|
||||
calls++
|
||||
return HttpResponse.json({ error_code: 442, error: 'No path could be found for input', status_code: 400 }, { status: 400 })
|
||||
}))
|
||||
expect(await valhallaRunOnFoot(points, undefined, { use_ferry: 0 }, { exclude_ferry: true })).toEqual({ noPath: true })
|
||||
expect(calls).toBe(1)
|
||||
expect(await valhallaRun(points, 'walking', [])).toBeNull()
|
||||
|
||||
server.use(http.post('https://valhalla.test/route', () =>
|
||||
HttpResponse.json({ error_code: 154, error: 'Path distance exceeds the max distance limit' }, { status: 400 })))
|
||||
expect(await valhallaRunOnFoot(points, undefined, { use_ferry: 0 }, { exclude_ferry: true })).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -136,6 +136,22 @@ export interface ValhallaLeg {
|
||||
ferrySpans?: FerrySpan[]
|
||||
}
|
||||
|
||||
/**
|
||||
* CW-12: the router's own word that no way joins the points, apart from a
|
||||
* router that gave no answer at all: down, rate limited, or not asked.
|
||||
*/
|
||||
export interface ValhallaNoPath {
|
||||
noPath: true
|
||||
}
|
||||
|
||||
/**
|
||||
* The refusals that are about the way rather than the host: points in
|
||||
* regions no edge connects (170), a point with no edge near it (171), and no
|
||||
* path found between them (442).
|
||||
*/
|
||||
const NO_PATH_CODES = new Set([170, 171, 442])
|
||||
const NO_PATH: ValhallaNoPath = { noPath: true }
|
||||
|
||||
/** A routed chain: one leg per pair of consecutive waypoints, plus the whole of it. */
|
||||
export interface ValhallaRun {
|
||||
legs: ValhallaLeg[]
|
||||
@@ -219,21 +235,24 @@ export async function valhallaRun(
|
||||
signal?: AbortSignal,
|
||||
costingOptions: Readonly<CostingOptions> = {},
|
||||
): Promise<ValhallaRun | null> {
|
||||
return chainRun(waypoints, profile, avoid, signal, { costingOptions, searchFilter: null })
|
||||
const run = await chainRun(waypoints, profile, avoid, signal, { costingOptions, searchFilter: null })
|
||||
if (!run || 'noPath' in run) return null
|
||||
return run
|
||||
}
|
||||
|
||||
/**
|
||||
* CW-12: a chain walked on foot, every point bound off the boat lines. Measured
|
||||
* on Venice: a stop by a vaporetto pier bound onto the boat line ended the
|
||||
* route on the ferry to its next landing, which `use_ferry` cannot weigh away
|
||||
* because the edge is where the route starts, not a choice along it.
|
||||
* because the edge is where the route starts, not a choice along it. Tells a
|
||||
* walk no way joins (`noPath`) from a router that did not answer (null).
|
||||
*/
|
||||
export function valhallaRunOnFoot(
|
||||
waypoints: Waypoint[],
|
||||
signal: AbortSignal | undefined,
|
||||
costingOptions: Readonly<CostingOptions>,
|
||||
searchFilter: Readonly<SearchFilter>,
|
||||
): Promise<ValhallaRun | null> {
|
||||
): Promise<ValhallaRun | ValhallaNoPath | null> {
|
||||
return chainRun(waypoints, 'walking', [], signal, { costingOptions, searchFilter })
|
||||
}
|
||||
|
||||
@@ -249,7 +268,7 @@ async function chainRun(
|
||||
avoid: readonly AvoidClass[],
|
||||
signal: AbortSignal | undefined,
|
||||
ask: RunAsk,
|
||||
): Promise<ValhallaRun | null> {
|
||||
): Promise<ValhallaRun | ValhallaNoPath | null> {
|
||||
const base = valhallaBase()
|
||||
if (!base || notValhalla.has(base) || waypoints.length < 2) return null
|
||||
|
||||
@@ -267,6 +286,7 @@ async function chainRun(
|
||||
// the schedule chains leg times blindly and cannot tell that it is missing some, so
|
||||
// it would print a complete, plausible, wrong timetable rather than a gap.
|
||||
if (!run) return null
|
||||
if ('noPath' in run) return run
|
||||
legs.push(...run.legs)
|
||||
}
|
||||
if (legs.length !== waypoints.length - 1) return null
|
||||
@@ -395,7 +415,7 @@ function routeBody(
|
||||
}
|
||||
}
|
||||
|
||||
/** The parsed answer to one POST, or null for every failure. */
|
||||
/** The parsed answer to one POST, `NO_PATH` when the router found no way, or null for every other failure. */
|
||||
async function postRoute(base: string, body: Record<string, unknown>, signal?: AbortSignal): Promise<unknown> {
|
||||
try {
|
||||
await valhallaTurn(base, signal)
|
||||
@@ -414,6 +434,7 @@ async function postRoute(base: string, body: Record<string, unknown>, signal?: A
|
||||
// 400 carries the real refusals (unroutable point, over 1500 km apart) and 429
|
||||
// is the public instance's one-per-second.
|
||||
if (response.status === 404 || response.status === 405) notValhalla.add(base)
|
||||
if (response.status === 400 && (await refusesTheWay(response))) return NO_PATH
|
||||
return null
|
||||
}
|
||||
return await response.json()
|
||||
@@ -422,6 +443,15 @@ async function postRoute(base: string, body: Record<string, unknown>, signal?: A
|
||||
}
|
||||
}
|
||||
|
||||
async function refusesTheWay(response: Response): Promise<boolean> {
|
||||
try {
|
||||
const code = ((await response.json()) as { error_code?: unknown })?.error_code
|
||||
return typeof code === 'number' && NO_PATH_CODES.has(code)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** The most points a description of a line asks about; a longer line is thinned evenly, its ends kept. */
|
||||
const TRACE_MAX_POINTS = 4000
|
||||
/** How long a description may take before it counts as failed, so a router that hangs does not leave its card waiting. */
|
||||
@@ -507,8 +537,9 @@ async function requestRun(
|
||||
avoid: readonly AvoidClass[],
|
||||
signal: AbortSignal | undefined,
|
||||
{ costingOptions, searchFilter }: RunAsk,
|
||||
): Promise<Omit<ValhallaRun, 'snapped'> | null> {
|
||||
): Promise<Omit<ValhallaRun, 'snapped'> | ValhallaNoPath | null> {
|
||||
const data = await postRoute(base, routeBody(waypoints, profile, avoid, costingOptions, searchFilter), signal)
|
||||
if (data === NO_PATH) return NO_PATH
|
||||
return data === null ? null : runFrom(data)
|
||||
}
|
||||
|
||||
|
||||
@@ -733,7 +733,7 @@ function plannerTimeFields(planner: TourPlannerController, t: Translate): TourMe
|
||||
}
|
||||
if (planner.stationStays) {
|
||||
return walkTimeFields({ walking: estimate, walkingMinutes: planner.walkingDurationMinutes, stays: planner.stationStays,
|
||||
manualMinutes: planner.plannedDurationMinutes, ferries: planner.walkFerries.crossings, t })
|
||||
manualMinutes: planner.plannedDurationMinutes, t })
|
||||
}
|
||||
return [
|
||||
{
|
||||
|
||||
@@ -16,21 +16,29 @@ export interface WalkTimes {
|
||||
unknownStays: number;
|
||||
/** The walk's stations, so that some stays unknown and all of them unknown read apart. */
|
||||
stations: number;
|
||||
/** Walking and the known stays; the known stays alone while the walking time is not known, null while nothing is. */
|
||||
/**
|
||||
* CW-12: the minutes its crossings by boat take, never walking; null while
|
||||
* the router gave one of them no time, absent for a walk without any.
|
||||
*/
|
||||
ferryMinutes?: number | null;
|
||||
/** Walking, the boat and the known stays; what is known of them while the walking time is not, null while nothing is. */
|
||||
totalMinutes: number | null;
|
||||
/** The total leaves out a stay or the walking time that is not known. */
|
||||
/** The total leaves out a stay, a boat's time or the walking time that is not known. */
|
||||
partial: boolean;
|
||||
}
|
||||
|
||||
/** The times of a walk from its parts: the walking time, the stays entered, how many are unknown and of how many. */
|
||||
export function walkTimesOf(parts: Omit<WalkTimes, 'totalMinutes' | 'partial'>): WalkTimes {
|
||||
const { walkingMinutes, stayMinutes, unknownStays, stations } = parts;
|
||||
const { walkingMinutes, stayMinutes, unknownStays, stations, ferryMinutes } = parts;
|
||||
// Without a walking time the stays entered are still part of the whole: at least that much, never nothing.
|
||||
const totalMinutes = walkingMinutes !== null ? walkingMinutes + stayMinutes : stayMinutes > 0 ? stayMinutes : null;
|
||||
const known = stayMinutes + (ferryMinutes ?? 0);
|
||||
const totalMinutes = walkingMinutes !== null ? walkingMinutes + known : known > 0 ? known : null;
|
||||
return {
|
||||
...parts,
|
||||
totalMinutes,
|
||||
partial: totalMinutes !== null && (someStaysUnknown({ unknownStays, stations }) || walkingMinutes === null),
|
||||
partial:
|
||||
totalMinutes !== null &&
|
||||
(someStaysUnknown({ unknownStays, stations }) || walkingMinutes === null || ferryMinutes === null),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ export interface TourPlannerFactsInput {
|
||||
* CW-02: a city walk's stays as far as known, and of how many stations; null
|
||||
* for any other type, which takes its breaks.
|
||||
*/
|
||||
stays?: Pick<WalkTimes, 'stayMinutes' | 'unknownStays' | 'stations'> | null;
|
||||
stays?: Pick<WalkTimes, 'stayMinutes' | 'unknownStays' | 'stations' | 'ferryMinutes'> | null;
|
||||
/** The router's own time, seconds: a bike tour's riding time; stands in for a hike until the heights are in. */
|
||||
durationSeconds: number | null;
|
||||
/** MDT-01: the stages the tour is split into, one for a day tour; a day each is what the times may take. */
|
||||
|
||||
@@ -300,7 +300,7 @@ describe('a city walk across the water (CW-12)', () => {
|
||||
expect(routed.durationSeconds).toBe(1005)
|
||||
expect(routed.distanceMeters).toBe(2700)
|
||||
expect(routed.ferries).toEqual([
|
||||
{ leg: 1, geometry: boatLeg.coordinates, crossing: [1, 2], metres: 1236, seconds: 745, walkSeconds: 355, accepted: false },
|
||||
{ leg: 1, geometry: boatLeg.coordinates, crossings: [[1, 2]], metres: 1236, seconds: 745, walkSeconds: 355, accepted: false },
|
||||
])
|
||||
})
|
||||
|
||||
@@ -321,7 +321,7 @@ describe('a city walk across the water (CW-12)', () => {
|
||||
const ferry = {
|
||||
kind: 'ferry' as const,
|
||||
geometry: boatLeg.coordinates as [number, number][],
|
||||
crossing: [1, 2] as [number, number],
|
||||
crossings: [[1, 2]] as [number, number][],
|
||||
minutes: 12,
|
||||
walk_minutes: 6,
|
||||
}
|
||||
@@ -331,18 +331,47 @@ describe('a city walk across the water (CW-12)', () => {
|
||||
expect(valhallaRunOnFoot).toHaveBeenCalledTimes(1)
|
||||
expect(routed.durationSeconds).toBe(650 + 6 * 60)
|
||||
expect(routed.parts.map((part) => part.mark ?? null)).toEqual([null, 'ferry', null])
|
||||
expect(routed.ferries).toMatchObject([{ leg: 1, crossing: [1, 2], seconds: 720, walkSeconds: 360, accepted: true }])
|
||||
expect(routed.ferries).toMatchObject([{ leg: 1, crossings: [[1, 2]], seconds: 720, walkSeconds: 360, accepted: true }])
|
||||
})
|
||||
|
||||
it('TOUR-ROUTING-041: two boats on one leg stay two crossings, the walk between them walking, before and after they are taken', async () => {
|
||||
const line = [[45.4368, 12.3288], [45.4352, 12.3275], [45.4331, 12.3262], [45.434, 12.325], [45.4345, 12.323], [45.4361, 12.3214]]
|
||||
const twoBoats = { coordinates: line, distance: 2000, duration: 1200, hasFerry: true,
|
||||
ferrySpans: [{ from: 0, to: 1, metres: 200, seconds: 120 }, { from: 3, to: 4, metres: 150, seconds: 90 }] }
|
||||
valhallaRunOnFoot.mockResolvedValueOnce({ legs: [twoBoats], total: twoBoats, snapped: [3, 4].map((meters) => ({ asked: [0, 0], at: [0, 0], meters })) })
|
||||
const routed = (await routeCityWalk([saoneri, moresco])) as TourRouteResult
|
||||
expect(routed.ferries?.[0]).toMatchObject({ crossings: [[0, 1], [3, 4]], metres: 350, seconds: 210, walkSeconds: 990 })
|
||||
const drawn = routed.parts.map((part) => [part.coordinates.length, part.mark ?? null])
|
||||
expect(drawn).toEqual([[2, 'ferry'], [3, null], [2, 'ferry'], [2, null]])
|
||||
|
||||
valhallaRunOnFoot.mockReset()
|
||||
const taken = { kind: 'ferry' as const, geometry: line as [number, number][], crossings: [[0, 1], [3, 4]] as [number, number][], minutes: 4, walk_minutes: 17 }
|
||||
const kept = (await routeCityWalk([{ ...saoneri, fixedLeg: taken }, moresco])) as TourRouteResult
|
||||
expect(kept.parts.map((part) => [part.coordinates.length, part.mark ?? null])).toEqual(drawn)
|
||||
expect(kept.ferries?.[0]).toMatchObject({ crossings: [[0, 1], [3, 4]], accepted: true })
|
||||
})
|
||||
|
||||
const answered = { total: { coordinates: [[0, 0], [1, 1]], distance: 1, duration: 1 }, legs: [], snapped: [] }
|
||||
const noPath = { noPath: true }
|
||||
const stops = [sanMarco, saoneri, moresco, { lat: 45.43, lng: 12.31 }, { lat: 45.42, lng: 12.3 }]
|
||||
|
||||
it('TOUR-ROUTING-039: two stops no way joins are named by halving the walk, and a host that answers after all names none', async () => {
|
||||
const answered = { total: { coordinates: [[0, 0], [1, 1]], distance: 1, duration: 1 }, legs: [], snapped: [] }
|
||||
const stops = [sanMarco, saoneri, moresco, { lat: 45.43, lng: 12.31 }, { lat: 45.42, lng: 12.3 }]
|
||||
// The whole walk fails, its first half [0..2] answers, then [2..3] fails: the gap is the leg from stop 2.
|
||||
valhallaRunOnFoot.mockResolvedValueOnce(null).mockResolvedValueOnce(answered).mockResolvedValueOnce(null)
|
||||
// The whole walk has no way, its first half [0..2] answers, then [2..3] has none: the gap is the leg from stop 2.
|
||||
valhallaRunOnFoot.mockResolvedValueOnce(noPath).mockResolvedValueOnce(answered).mockResolvedValueOnce(noPath)
|
||||
expect(await routeCityWalk(stops)).toEqual({ gap: 2 })
|
||||
expect(valhallaRunOnFoot.mock.calls.map((call) => (call[0] as unknown[]).length)).toEqual([5, 3, 2])
|
||||
|
||||
valhallaRunOnFoot.mockReset().mockResolvedValueOnce(null).mockResolvedValue(answered)
|
||||
valhallaRunOnFoot.mockReset().mockResolvedValueOnce(noPath).mockResolvedValue(answered)
|
||||
expect(await routeCityWalk([sanMarco, saoneri])).toBeNull()
|
||||
})
|
||||
|
||||
it('TOUR-ROUTING-040: a router that does not answer names no gap and asks no more, the walk failing as a routing error', async () => {
|
||||
expect(await routeCityWalk(stops)).toBeNull()
|
||||
expect(valhallaRunOnFoot).toHaveBeenCalledTimes(1)
|
||||
|
||||
// No way through the whole walk, but the host goes quiet while the halves are asked: nothing is known about the way.
|
||||
valhallaRunOnFoot.mockReset().mockResolvedValueOnce(noPath).mockResolvedValue(null)
|
||||
expect(await routeCityWalk(stops)).toBeNull()
|
||||
expect(valhallaRunOnFoot).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -17,6 +17,8 @@ import {
|
||||
type FerrySpan,
|
||||
type SearchFilter,
|
||||
type ValhallaLeg,
|
||||
type ValhallaNoPath,
|
||||
type ValhallaRun,
|
||||
} from '../../Map/valhallaRoute'
|
||||
import { hikingCosting, TOURS_MAX_HIKING_DIFFICULTY } from './hikingCosting'
|
||||
import { densifyLine, lineLengthM } from './tourFixedLegs'
|
||||
@@ -50,8 +52,8 @@ export interface WalkFerryCrossing {
|
||||
/** The leg, by the place along the tour of the point it starts at. */
|
||||
leg: number
|
||||
geometry: [number, number][]
|
||||
/** The points of `geometry` the boat leaves from and lands at. */
|
||||
crossing: [number, number]
|
||||
/** Each stretch of `geometry` by boat, as the points the boat leaves from and lands at, in order. */
|
||||
crossings: Array<[number, number]>
|
||||
metres: number
|
||||
/** Null where the router gave no time for the boat. */
|
||||
seconds: number | null
|
||||
@@ -227,19 +229,22 @@ function splitAtCrossings(coordinates: [number, number][], spans: readonly Pick<
|
||||
return parts
|
||||
}
|
||||
|
||||
/** The length of a leg's stretches by boat, measured along its line. */
|
||||
function boatMetresOf(geometry: [number, number][], crossings: ReadonlyArray<[number, number]>): number {
|
||||
return crossings.reduce((sum, [from, to]) => sum + lineLengthM(geometry.slice(from, to + 1)), 0)
|
||||
}
|
||||
|
||||
/**
|
||||
* CW-12: the crossing of a routed leg, from where its first boat stretch
|
||||
* leaves to where its last one lands. The walk on the leg is the router's time
|
||||
* less the boat's; where the router gave the boat no time, the walk is the
|
||||
* leg's time shared out by the length walked.
|
||||
* CW-12: the crossing of a routed leg, each of its stretches by boat kept on
|
||||
* its own, so a walk between two boats stays walking. The walk on the leg is
|
||||
* the router's time less the boat's; where the router gave the boat no time,
|
||||
* the walk is the leg's time shared out by the length walked.
|
||||
*/
|
||||
function crossingOf(leg: ValhallaLeg, index: number): WalkFerryCrossing | null {
|
||||
const spans = leg.ferrySpans ?? []
|
||||
const first = spans[0]
|
||||
const last = spans[spans.length - 1]
|
||||
if (!first || !last) return null
|
||||
const crossing: [number, number] = [first.from, last.to]
|
||||
const metres = spans.reduce((sum, span) => sum + span.metres, 0) || lineLengthM(leg.coordinates.slice(first.from, last.to + 1))
|
||||
if (spans.length === 0) return null
|
||||
const crossings = spans.map(({ from, to }): [number, number] => [from, to])
|
||||
const metres = spans.reduce((sum, span) => sum + span.metres, 0) || boatMetresOf(leg.coordinates, crossings)
|
||||
const seconds = spans.every((span) => span.seconds !== null)
|
||||
? spans.reduce((sum, span) => sum + (span.seconds ?? 0), 0)
|
||||
: null
|
||||
@@ -247,18 +252,18 @@ function crossingOf(leg: ValhallaLeg, index: number): WalkFerryCrossing | null {
|
||||
const walkSeconds = seconds !== null
|
||||
? Math.max(0, leg.duration - seconds)
|
||||
: length > 0 ? leg.duration * Math.max(0, 1 - metres / length) : 0
|
||||
return { leg: index, geometry: leg.coordinates, crossing, metres, seconds, walkSeconds, accepted: false }
|
||||
return { leg: index, geometry: leg.coordinates, crossings, metres, seconds, walkSeconds, accepted: false }
|
||||
}
|
||||
|
||||
/** CW-12: a ferry leg the travellers took, as the walk counts it: the boat apart from the walk. */
|
||||
function acceptedCrossing(leg: Extract<TourFixedLeg, { kind: 'ferry' }>, index: number): WalkFerryCrossing {
|
||||
const geometry = leg.geometry.map(([lat, lng]): [number, number] => [lat, lng])
|
||||
const crossing: [number, number] = [leg.crossing[0], leg.crossing[1]]
|
||||
const crossings = leg.crossings.map(([from, to]): [number, number] => [from, to])
|
||||
return {
|
||||
leg: index,
|
||||
geometry,
|
||||
crossing,
|
||||
metres: lineLengthM(geometry.slice(crossing[0], crossing[1] + 1)),
|
||||
crossings,
|
||||
metres: boatMetresOf(geometry, crossings),
|
||||
seconds: leg.minutes === null ? null : leg.minutes * 60,
|
||||
walkSeconds: leg.walk_minutes * 60,
|
||||
accepted: true,
|
||||
@@ -267,13 +272,14 @@ function acceptedCrossing(leg: Extract<TourFixedLeg, { kind: 'ferry' }>, index:
|
||||
|
||||
/**
|
||||
* CW-12: the leg of a run no way joins, found by halving the run: whichever
|
||||
* half still fails holds it. Null where every piece answers after all, a
|
||||
* failure of the host rather than of the way, or once the run is called off.
|
||||
* half the router still finds no way through holds it. Null where every piece
|
||||
* answers after all, where the router stops answering at all (a host that is
|
||||
* down says nothing about the way), or once the run is called off.
|
||||
*/
|
||||
async function gapOf(
|
||||
run: Array<Pick<Waypoint, 'lat' | 'lng'>>,
|
||||
first: number,
|
||||
ask: (points: Array<Pick<Waypoint, 'lat' | 'lng'>>) => Promise<unknown>,
|
||||
ask: (points: Array<Pick<Waypoint, 'lat' | 'lng'>>) => Promise<ValhallaRun | ValhallaNoPath | null>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<TourRouteGap | null> {
|
||||
let low = 0
|
||||
@@ -282,15 +288,18 @@ async function gapOf(
|
||||
while (high - low > 1) {
|
||||
const middle = Math.floor((low + high) / 2)
|
||||
const answer = await ask(run.slice(low, middle + 1))
|
||||
if (signal?.aborted) return null
|
||||
if (answer) {
|
||||
low = middle
|
||||
} else {
|
||||
if (!answer || signal?.aborted) return null
|
||||
if ('noPath' in answer) {
|
||||
high = middle
|
||||
failed = true
|
||||
} else {
|
||||
low = middle
|
||||
}
|
||||
}
|
||||
if (!failed && (await ask(run.slice(low, high + 1)))) return null
|
||||
if (!failed) {
|
||||
const last = await ask(run.slice(low, high + 1))
|
||||
if (!last || !('noPath' in last)) return null
|
||||
}
|
||||
return signal?.aborted ? null : { gap: first + low }
|
||||
}
|
||||
|
||||
@@ -321,7 +330,7 @@ async function routeOnLand(
|
||||
let durationSeconds = 0
|
||||
let unreachable: TourRouteUnreachable | TourRouteGap | null = null
|
||||
// A city walk binds no point to a boat line (CW-12); no other type asks for that.
|
||||
const ask = (points: Array<Pick<Waypoint, 'lat' | 'lng'>>) => {
|
||||
const ask = (points: Array<Pick<Waypoint, 'lat' | 'lng'>>): Promise<ValhallaRun | ValhallaNoPath | null> => {
|
||||
const asked = points.map(({ lat, lng }) => ({ lat, lng }))
|
||||
return searchFilter
|
||||
? valhallaRunOnFoot(asked, signal, costingOptions, searchFilter)
|
||||
@@ -331,8 +340,9 @@ async function routeOnLand(
|
||||
const routeRun = async (run: Array<Pick<Waypoint, 'lat' | 'lng'>>, first: number) => {
|
||||
if (run.length < 2) return true
|
||||
const routed = await ask(run)
|
||||
if (!routed) {
|
||||
if (searchFilter && !signal?.aborted) unreachable = await gapOf(run, first, ask, signal)
|
||||
if (!routed || 'noPath' in routed) {
|
||||
// Only the router's own "no way" names a leg; no answer at all stays a routing failure, with its retry.
|
||||
if (routed && !signal?.aborted) unreachable = await gapOf(run, first, ask, signal)
|
||||
return false
|
||||
}
|
||||
const far = routed.snapped.findIndex((point) => point.meters > MAX_TOUR_SNAP_M)
|
||||
@@ -366,7 +376,7 @@ async function routeOnLand(
|
||||
if (!(await routeRun(run, runStart))) return unreachable
|
||||
if (leg.kind === 'ferry') {
|
||||
const crossing = acceptedCrossing(leg, i)
|
||||
lines.push(...splitAtCrossings(crossing.geometry, [{ from: crossing.crossing[0], to: crossing.crossing[1] }]))
|
||||
lines.push(...splitAtCrossings(crossing.geometry, crossing.crossings.map(([from, to]) => ({ from, to }))))
|
||||
ferries.push(crossing)
|
||||
distanceMeters += lineLengthM(crossing.geometry)
|
||||
durationSeconds += crossing.walkSeconds
|
||||
|
||||
@@ -6,7 +6,6 @@ import { randomId } from '../../../utils/randomId'
|
||||
import { analyzeRouteGeometry, type RouteProfileFocus } from '../../../utils/routeGeometry'
|
||||
import { closeLoop, reverseRoute, toggleFreeLeg, withPointAppended } from './tourRouteActions'
|
||||
import { holdsHorseSection } from '../horse/horseLegs'
|
||||
import { walkTimes } from './stationModel'
|
||||
import { hasCompleteElevation, useTourRoute } from './useTourRoute'
|
||||
import { normalizePlannerWaypoints, plannerWaypointsOf, ridablePoints, routeInputsKey, sameWaypointSnapshot, savedWaypointsOf, unlinkedPoint, withSavedKeys, type TourPlannerWaypoint } from './tourPlannerWaypoints'
|
||||
import { openedTourFields, tourPlannerFacts } from './tourPlannerFacts'
|
||||
@@ -29,7 +28,7 @@ import { savedSkiSeed } from '../ski/savedSkiRoute'
|
||||
import { useSkiFields } from '../ski/useSkiFields'
|
||||
import { lostStageEnds } from '../stages/tourStages'
|
||||
import { useTourStages } from '../stages/useTourStages'
|
||||
import { useWalkFerries } from '../walk/useWalkFerries'
|
||||
import { useWalkFerries, useWalkStays } from '../walk/useWalkFerries'
|
||||
|
||||
/** What a tour planned from an import starts with. */
|
||||
export interface DerivedTourDraft {
|
||||
@@ -523,8 +522,8 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
const routedLegLengths = paddleRoute && routeCurrent ? paddleRoute.legLengths : undefined
|
||||
const paddleEstimate = useMemo(() => isPaddle ? paddleEstimateOf(waypoints, { effectiveSpeedKmh, portageSpeedKmh }, paddleSpeedInvalid, routedLegLengths) : null,
|
||||
[effectiveSpeedKmh, isPaddle, paddleSpeedInvalid, portageSpeedKmh, routedLegLengths, waypoints])
|
||||
// CW-02: a city walk's stays, what of them is known.
|
||||
const stays = useMemo(() => (tourType === 'walk' ? walkTimes(waypoints, null) : null), [tourType, waypoints])
|
||||
// CW-02: a city walk's stays, what of them is known; CW-12: and the minutes of its boats, never walking.
|
||||
const stays = useWalkStays(tourType, waypoints, routeCurrent ? routing.ferries : null)
|
||||
const runPaceSecondsPerKm = runPace.paceSecondsPerKm
|
||||
// MDT-01: the stages, cut from the route while it is the one planned for these points.
|
||||
const stagePaddle = useMemo(() => isPaddle
|
||||
|
||||
@@ -30,7 +30,7 @@ const boatLine: [number, number][] = [ZATTERE, [45.4291, 12.3266], [45.4275, 12.
|
||||
const crossing = (accepted: boolean): WalkFerryCrossing => ({
|
||||
leg: 1,
|
||||
geometry: boatLine,
|
||||
crossing: [1, 2],
|
||||
crossings: [[1, 2]],
|
||||
metres: 268,
|
||||
seconds: 396,
|
||||
walkSeconds: 120,
|
||||
@@ -118,7 +118,7 @@ describe('useTourPlanner, a city walk across the water (CW-12)', () => {
|
||||
expect(result.current.waypoints[1]?.fixedLeg).toEqual({
|
||||
kind: 'ferry',
|
||||
geometry: boatLine,
|
||||
crossing: [1, 2],
|
||||
crossings: [[1, 2]],
|
||||
minutes: 7,
|
||||
walk_minutes: 2,
|
||||
});
|
||||
@@ -130,7 +130,7 @@ describe('useTourPlanner, a city walk across the water (CW-12)', () => {
|
||||
await result.current.save();
|
||||
});
|
||||
const body = createTour.mock.calls[0]?.[1] as TourCreateRequest;
|
||||
expect(body.waypoints[1]?.fixed_leg).toMatchObject({ kind: 'ferry', crossing: [1, 2], minutes: 7 });
|
||||
expect(body.waypoints[1]?.fixed_leg).toMatchObject({ kind: 'ferry', crossings: [[1, 2]], minutes: 7 });
|
||||
// The walking time saved is the walk alone; the boat's minutes stay on the leg.
|
||||
expect(body.duration_seconds).toBe(17 * 60);
|
||||
});
|
||||
|
||||
@@ -36,7 +36,7 @@ export interface TourPlannedTimes {
|
||||
}
|
||||
|
||||
type PlannedTimesSource = Pick<TourListItem, 'duration' | 'planned_duration_minutes' | 'break_additional_minutes'>
|
||||
& Partial<Pick<TourListItem, 'tour_type' | 'station_count' | 'station_stay_minutes' | 'station_stays_unknown'>>
|
||||
& Partial<Pick<TourListItem, 'tour_type' | 'station_count' | 'station_stay_minutes' | 'station_stays_unknown' | 'walk_ferry_minutes'>>
|
||||
& Partial<Pick<TourListItem, 'distance' | 'elevation_gain' | 'elevation_loss' | 'run_pace_seconds_per_km'>>
|
||||
|
||||
/** TIME-01: the estimate of a tour, by the rule `@trek/shared` keeps for the app and the server alike. */
|
||||
@@ -60,6 +60,8 @@ function walkTimesOfTour(tour: PlannedTimesSource): WalkTimes | null {
|
||||
stayMinutes: tour.station_stay_minutes,
|
||||
unknownStays: tour.station_stays_unknown ?? 0,
|
||||
stations: tour.station_count ?? 0,
|
||||
// CW-12: the boat is part of the day, never of the walking time.
|
||||
...(tour.walk_ferry_minutes !== undefined ? { ferryMinutes: tour.walk_ferry_minutes } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { WalkFerryCrossing } from '../planner/tourRouting';
|
||||
import type { TourPlannerController } from '../planner/useTourPlanner';
|
||||
import { WalkFerryNotice } from './WalkFerryNotice';
|
||||
|
||||
// FE-WALK-FERRY-NOTICE-001 to FE-WALK-FERRY-NOTICE-003: a city walk's crossings by boat in the planner (CW-12).
|
||||
// FE-WALK-FERRY-NOTICE-001 to FE-WALK-FERRY-NOTICE-005: a city walk's crossings by boat in the planner (CW-12).
|
||||
|
||||
const crossing = (extra: Partial<WalkFerryCrossing> = {}): WalkFerryCrossing => ({
|
||||
leg: 0,
|
||||
@@ -13,7 +13,7 @@ const crossing = (extra: Partial<WalkFerryCrossing> = {}): WalkFerryCrossing =>
|
||||
[45.429, 12.329],
|
||||
[45.427, 12.33],
|
||||
],
|
||||
crossing: [1, 2],
|
||||
crossings: [[1, 2]],
|
||||
metres: 268,
|
||||
seconds: 396,
|
||||
walkSeconds: 120,
|
||||
@@ -21,14 +21,27 @@ const crossing = (extra: Partial<WalkFerryCrossing> = {}): WalkFerryCrossing =>
|
||||
...extra,
|
||||
});
|
||||
|
||||
function plannerWith(walkFerries: Partial<TourPlannerController['walkFerries']>) {
|
||||
const ZATTERE_TO_STOP_2 = [
|
||||
{ id: 'a', lat: 45.43, lng: 12.33, role: 'start', name: 'Zattere' },
|
||||
{ id: 'b', lat: 45.427, lng: 12.33, role: 'end', name: null },
|
||||
];
|
||||
|
||||
function plannerWith(
|
||||
walkFerries: Partial<TourPlannerController['walkFerries']>,
|
||||
waypoints: unknown[] = ZATTERE_TO_STOP_2
|
||||
) {
|
||||
const actions = { accept: vi.fn(), release: vi.fn(), show: vi.fn(), select: vi.fn() };
|
||||
const planner = {
|
||||
walkFerries: { crossings: [], pending: [], blocksSave: false, gap: null, ...actions, ...walkFerries },
|
||||
waypoints: [
|
||||
{ id: 'a', lat: 45.43, lng: 12.33, role: 'start', name: 'Zattere' },
|
||||
{ id: 'b', lat: 45.427, lng: 12.33, role: 'end', name: null },
|
||||
],
|
||||
walkFerries: {
|
||||
crossings: [],
|
||||
pending: [],
|
||||
blocksSave: false,
|
||||
gap: null,
|
||||
acceptable: () => true,
|
||||
...actions,
|
||||
...walkFerries,
|
||||
},
|
||||
waypoints,
|
||||
setSelectedWaypointId: actions.select,
|
||||
canEdit: true,
|
||||
isSaving: false,
|
||||
@@ -71,4 +84,35 @@ describe('WalkFerryNotice (CW-12)', () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Select stop 2' }));
|
||||
expect(actions.select).toHaveBeenCalledWith('b');
|
||||
});
|
||||
|
||||
it('FE-WALK-FERRY-NOTICE-004: a leg through a shaping point is named by the stations around it, numbered as the stop list numbers them', () => {
|
||||
const { planner, actions } = plannerWith({ gap: { leg: 1 } }, [
|
||||
{ id: 'a', lat: 45.43, lng: 12.33, role: 'start', name: 'Zattere' },
|
||||
{ id: 's', lat: 45.429, lng: 12.331, role: 'via', shaping: true },
|
||||
{ id: 'b', lat: 45.428, lng: 12.332, role: 'via', name: null },
|
||||
{ id: 'c', lat: 45.427, lng: 12.33, role: 'end', name: 'Redentore' },
|
||||
]);
|
||||
render(<WalkFerryNotice planner={planner} />);
|
||||
expect(screen.getByTestId('walk-ferry-gap')).toHaveTextContent(
|
||||
'No way joins Zattere and Stop 2, neither on foot nor by ferry.'
|
||||
);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Select stop 2' }));
|
||||
expect(actions.select).toHaveBeenCalledWith('b');
|
||||
});
|
||||
|
||||
it('FE-WALK-FERRY-NOTICE-005: a crossing too long to keep cannot be taken, and says why', () => {
|
||||
const pending = crossing();
|
||||
const { planner, actions } = plannerWith({
|
||||
crossings: [pending],
|
||||
pending: [pending],
|
||||
blocksSave: true,
|
||||
acceptable: () => false,
|
||||
});
|
||||
render(<WalkFerryNotice planner={planner} />);
|
||||
const take = screen.getByRole('button', { name: 'Take ferry' });
|
||||
expect(take).toBeDisabled();
|
||||
fireEvent.click(take);
|
||||
expect(actions.accept).not.toHaveBeenCalled();
|
||||
expect(screen.getByTestId('walk-ferry-accept-too-long')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,21 +4,43 @@ import { useSettingsStore } from '../../../store/settingsStore';
|
||||
import { formatDistance } from '../../../utils/units';
|
||||
import { SoftPill } from '../../Planner/planParts';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import { stopNumbersOf, type TourPlannerWaypoint } from '../planner/tourPlannerWaypoints';
|
||||
import type { WalkFerryCrossing } from '../planner/tourRouting';
|
||||
import type { TourPlannerController } from '../planner/useTourPlanner';
|
||||
import { CardAction, TourNotice } from '../tourParts';
|
||||
import { formatPlannedTourDuration } from '../tourPresentation';
|
||||
import { ferryMinutesOf } from './walkFerry';
|
||||
import { useLinkedPlaceOf } from './useWalkSchedule';
|
||||
import { ferryMinutesOf, legStationsOf } from './walkFerry';
|
||||
import { FERRY_CSS_COLOR } from './walkRoutePaint';
|
||||
|
||||
type Planner = Pick<
|
||||
TourPlannerController,
|
||||
'walkFerries' | 'waypoints' | 'setSelectedWaypointId' | 'canEdit' | 'isSaving'
|
||||
>;
|
||||
type Translate = ReturnType<typeof useTranslation>['t'];
|
||||
|
||||
function pointName(planner: Planner, index: number, t: Translate): string {
|
||||
return planner.waypoints[index]?.name?.trim() || t('tours.walk.stationNumbered', { number: index + 1 });
|
||||
/** A leg's two stations as the stop list shows them: by name, the trip place they stand for, else their number. */
|
||||
interface LegStop {
|
||||
id: string | null;
|
||||
name: string;
|
||||
number: number;
|
||||
}
|
||||
|
||||
function useLegStops(planner: Planner): (leg: number) => { from: LegStop; to: LegStop } {
|
||||
const { t } = useTranslation();
|
||||
const placeOf = useLinkedPlaceOf();
|
||||
const numbers = stopNumbersOf(planner.waypoints);
|
||||
const stopOf = (point: TourPlannerWaypoint | null): LegStop => {
|
||||
const number = point ? (numbers.get(point.id) ?? 0) : 0;
|
||||
return {
|
||||
id: point?.id ?? null,
|
||||
name: point?.name?.trim() || (point && placeOf(point)?.name) || t('tours.walk.stationNumbered', { number }),
|
||||
number,
|
||||
};
|
||||
};
|
||||
return (leg) => {
|
||||
const { from, to } = legStationsOf(planner.waypoints, leg);
|
||||
return { from: stopOf(from), to: stopOf(to) };
|
||||
};
|
||||
}
|
||||
|
||||
/** The crossing's length and time as badges; a time the router did not give says so, dimmed. */
|
||||
@@ -44,15 +66,39 @@ function CrossingFacts({ crossing }: { crossing: WalkFerryCrossing }) {
|
||||
);
|
||||
}
|
||||
|
||||
function selectAction(planner: Planner, index: number, t: Translate) {
|
||||
const select = () => planner.setSelectedWaypointId(planner.waypoints[index]?.id ?? null);
|
||||
function SelectStop({ planner, stop }: { planner: Planner; stop: LegStop }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<CardAction icon={<MapPin size={12} strokeWidth={2} />} onClick={select}>
|
||||
{t('tours.walk.ferry.selectStop', { number: index + 1 })}
|
||||
<CardAction icon={<MapPin size={12} strokeWidth={2} />} onClick={() => planner.setSelectedWaypointId(stop.id)}>
|
||||
{t('tours.walk.ferry.selectStop', { number: stop.number })}
|
||||
</CardAction>
|
||||
);
|
||||
}
|
||||
|
||||
/** Take ferry; one whose line is too long to keep as a leg is dimmed, with why and what to do instead. */
|
||||
function AcceptAction({ planner, crossing }: { planner: Planner; crossing: WalkFerryCrossing }) {
|
||||
const { t } = useTranslation();
|
||||
const { accept, acceptable } = planner.walkFerries;
|
||||
const fits = acceptable(crossing);
|
||||
const action = (
|
||||
<CardAction
|
||||
icon={<Check size={12} strokeWidth={2} />}
|
||||
onClick={() => accept(crossing)}
|
||||
disabled={!planner.canEdit || planner.isSaving || !fits}
|
||||
>
|
||||
{t('tours.walk.ferry.accept')}
|
||||
</CardAction>
|
||||
);
|
||||
if (fits) return action;
|
||||
return (
|
||||
<Tooltip label={t('tours.walk.ferry.acceptTooLong')}>
|
||||
<span className="inline-flex" data-testid="walk-ferry-accept-too-long">
|
||||
{action}
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* CW-12: a city walk's crossings by boat in the planner. One the router took
|
||||
* is named with its length and the boat's time, shown on the map on demand,
|
||||
@@ -63,26 +109,23 @@ function selectAction(planner: Planner, index: number, t: Translate) {
|
||||
*/
|
||||
export function WalkFerryNotice({ planner }: { planner: Planner }) {
|
||||
const { t } = useTranslation();
|
||||
const { gap, crossings, accept, show } = planner.walkFerries;
|
||||
const locked = !planner.canEdit || planner.isSaving;
|
||||
const { gap, crossings, show } = planner.walkFerries;
|
||||
const stopsOf = useLegStops(planner);
|
||||
const gapStops = gap ? stopsOf(gap.leg) : null;
|
||||
return (
|
||||
<>
|
||||
{gap && (
|
||||
{gapStops && (
|
||||
<TourNotice tone="warning" icon={<Unlink size={13} strokeWidth={2} />}>
|
||||
<span className="flex flex-col items-start gap-1.5" data-testid="walk-ferry-gap">
|
||||
<span>
|
||||
{t('tours.walk.ferry.gap', {
|
||||
from: pointName(planner, gap.leg, t),
|
||||
to: pointName(planner, gap.leg + 1, t),
|
||||
})}
|
||||
</span>
|
||||
<span>{t('tours.walk.ferry.gap', { from: gapStops.from.name, to: gapStops.to.name })}</span>
|
||||
<span className="text-content-muted">{t('tours.walk.ferry.gapHint')}</span>
|
||||
{selectAction(planner, gap.leg + 1, t)}
|
||||
<SelectStop planner={planner} stop={gapStops.to} />
|
||||
</span>
|
||||
</TourNotice>
|
||||
)}
|
||||
{crossings.map((crossing) => {
|
||||
const names = { from: pointName(planner, crossing.leg, t), to: pointName(planner, crossing.leg + 1, t) };
|
||||
const stops = stopsOf(crossing.leg);
|
||||
const names = { from: stops.from.name, to: stops.to.name };
|
||||
return (
|
||||
<TourNotice
|
||||
key={`${crossing.leg}:${crossing.accepted ? 'kept' : 'open'}`}
|
||||
@@ -94,19 +137,11 @@ export function WalkFerryNotice({ planner }: { planner: Planner }) {
|
||||
<CrossingFacts crossing={crossing} />
|
||||
{!crossing.accepted && <span className="text-content-muted">{t('tours.walk.ferry.pendingHint')}</span>}
|
||||
<span className="flex flex-wrap gap-1.5">
|
||||
{!crossing.accepted && (
|
||||
<CardAction
|
||||
icon={<Check size={12} strokeWidth={2} />}
|
||||
onClick={() => accept(crossing)}
|
||||
disabled={locked}
|
||||
>
|
||||
{t('tours.walk.ferry.accept')}
|
||||
</CardAction>
|
||||
)}
|
||||
{!crossing.accepted && <AcceptAction planner={planner} crossing={crossing} />}
|
||||
<CardAction icon={<Eye size={12} strokeWidth={2} />} onClick={() => show(crossing)}>
|
||||
{t('tours.walk.ferry.show')}
|
||||
</CardAction>
|
||||
{!crossing.accepted && selectAction(planner, crossing.leg + 1, t)}
|
||||
{!crossing.accepted && <SelectStop planner={planner} stop={stops.to} />}
|
||||
</span>
|
||||
</span>
|
||||
</TourNotice>
|
||||
|
||||
@@ -200,15 +200,17 @@ export function WalkStationsCard({
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const isWalk = tour.tour_type === 'walk';
|
||||
const stations = useWalkStations(tripId, tour.place_id, isWalk, tour.revision);
|
||||
const walk = useWalkStations(tripId, tour.place_id, isWalk, tour.revision);
|
||||
const stations = walk?.stations ?? null;
|
||||
const ferries = walk?.ferries;
|
||||
const assignmentId = assignment?.id ?? null;
|
||||
const visits = useDayVisits(assignmentId);
|
||||
const mark = useTourVisitStore((state) => state.mark);
|
||||
const placeOf = useLinkedPlaceOf();
|
||||
const choice = useWalkDay(isWalk ? tour.place_id : null, days, assignments, assignment?.day_id ?? null);
|
||||
const walkingMinutes = tour.duration ?? null;
|
||||
const schedule = useWalkSchedule({ stations, route, walkingMinutes, day: choice.day, placeOf });
|
||||
const remainder = useWalkRemaining({ stations, visits, route, walkingMinutes, placeOf });
|
||||
const schedule = useWalkSchedule({ stations, route, walkingMinutes, day: choice.day, placeOf, ferries });
|
||||
const remainder = useWalkRemaining({ stations, visits, route, walkingMinutes, placeOf, ferries });
|
||||
if (!isWalk) return null;
|
||||
const onMark = (key: string, status: TourVisitStatus | 'planned') => {
|
||||
if (assignmentId === null) return;
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import type { PlannableTourType } from '@trek/shared';
|
||||
import { useCallback } from 'react';
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { focusPaddleArea } from '../../../store/paddleObstacleStore';
|
||||
import { walkTimes, type WalkTimes } from '../planner/stationModel';
|
||||
import type { TourPlannerWaypoint } from '../planner/tourPlannerWaypoints';
|
||||
import type { WalkFerryCrossing } from '../planner/tourRouting';
|
||||
import { crossingLine, ferryLegOf } from './walkFerry';
|
||||
import { crossingLine, crossingsMinutesOf, ferryLegOf } from './walkFerry';
|
||||
|
||||
interface WalkFerriesInput {
|
||||
tourType: PlannableTourType;
|
||||
@@ -14,12 +15,38 @@ interface WalkFerriesInput {
|
||||
editWaypoints: (change: (current: TourPlannerWaypoint[]) => TourPlannerWaypoint[]) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* CW-02, CW-12: a city walk's stays, what of them is known, with the minutes
|
||||
* of its crossings by boat, taken or not, which are never walking; null for
|
||||
* any other type.
|
||||
*/
|
||||
export function useWalkStays(
|
||||
tourType: PlannableTourType,
|
||||
waypoints: readonly TourPlannerWaypoint[],
|
||||
ferries: readonly WalkFerryCrossing[] | null
|
||||
): WalkTimes | null {
|
||||
const ferryMinutes = tourType === 'walk' && ferries ? crossingsMinutesOf(ferries) : undefined;
|
||||
return useMemo(() => {
|
||||
if (tourType !== 'walk') return null;
|
||||
const known = walkTimes(waypoints, null);
|
||||
return ferryMinutes === undefined ? known : { ...known, ferryMinutes };
|
||||
}, [ferryMinutes, tourType, waypoints]);
|
||||
}
|
||||
|
||||
/** The ferry leg a crossing would be kept as; null where its line is longer than a leg may keep. */
|
||||
function legOf(crossing: WalkFerryCrossing, points: readonly TourPlannerWaypoint[]) {
|
||||
const from = points[crossing.leg];
|
||||
const to = points[crossing.leg + 1];
|
||||
return from && to && !from.fixedLeg ? ferryLegOf(crossing, from, to) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* CW-12: a city walk's crossings by boat as the planner handles them. A
|
||||
* crossing the router took is shown and explained but not saved until the
|
||||
* travellers take it as a ferry leg (`accept`, one step of the history), so
|
||||
* the boat never passes for walking unnoticed. `gap` is the leg no way
|
||||
* joins at all, while that is why the route failed.
|
||||
* the boat never passes for walking unnoticed; `acceptable` is false for one
|
||||
* too long to keep. `gap` is the leg no way joins at all, while that is why
|
||||
* the route failed.
|
||||
*/
|
||||
export function useWalkFerries({
|
||||
tourType,
|
||||
@@ -29,15 +56,17 @@ export function useWalkFerries({
|
||||
waypoints,
|
||||
editWaypoints,
|
||||
}: WalkFerriesInput) {
|
||||
const crossings = tourType === 'walk' && routeCurrent ? (ferries ?? []) : [];
|
||||
const pending = crossings.filter((crossing) => !crossing.accepted);
|
||||
const crossings = useMemo(
|
||||
() => (tourType === 'walk' && routeCurrent ? (ferries ?? []) : []),
|
||||
[ferries, routeCurrent, tourType]
|
||||
);
|
||||
const pending = useMemo(() => crossings.filter((crossing) => !crossing.accepted), [crossings]);
|
||||
const acceptable = useCallback((crossing: WalkFerryCrossing) => legOf(crossing, waypoints) !== null, [waypoints]);
|
||||
|
||||
const accept = useCallback(
|
||||
(crossing: WalkFerryCrossing) => {
|
||||
editWaypoints((current) => {
|
||||
const from = current[crossing.leg];
|
||||
const to = current[crossing.leg + 1];
|
||||
const leg = from && to && !from.fixedLeg ? ferryLegOf(crossing, from, to) : null;
|
||||
const leg = legOf(crossing, current);
|
||||
return leg
|
||||
? current.map((point, index) => (index === crossing.leg ? { ...point, fixedLeg: leg } : point))
|
||||
: current;
|
||||
@@ -68,6 +97,7 @@ export function useWalkFerries({
|
||||
/** Save waits while a crossing is not taken on purpose. */
|
||||
blocksSave: pending.length > 0,
|
||||
gap: tourType === 'walk' && walkGap !== null && waypoints[walkGap + 1] ? { leg: walkGap } : null,
|
||||
acceptable,
|
||||
accept,
|
||||
release,
|
||||
show,
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
import { walkStationsOf } from '@trek/shared';
|
||||
import { walkStationsOf, type WalkFerryLeg } from '@trek/shared';
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { useTripStore } from '../../../store/tripStore';
|
||||
import type { AssignmentsMap, Day, Place } from '../../../types';
|
||||
import type { TourPlannerWaypoint } from '../planner/tourPlannerWaypoints';
|
||||
import type { TourPlannerController } from '../planner/useTourPlanner';
|
||||
import { useWalkDay, type WalkDayChoice } from './useWalkDay';
|
||||
import { ferryLegsOfCrossings } from './walkFerry';
|
||||
import { walkScheduleOf, type LinkedPlaceOf, type WalkSchedule, type WalkScheduleInput } from './walkSchedule';
|
||||
|
||||
const NO_PLACES: Place[] = [];
|
||||
const NO_DAYS: Day[] = [];
|
||||
const NO_ASSIGNMENTS: AssignmentsMap = {};
|
||||
const NO_STATIONS: TourPlannerWaypoint[] = [];
|
||||
const NO_FERRIES: WalkFerryLeg[] = [];
|
||||
|
||||
/** PR1-10: the trip place a point stands for, while the trip still has it. */
|
||||
export function useLinkedPlaceOf(): (point: Pick<TourPlannerWaypoint, 'linkedPlaceId'>) => Place | null {
|
||||
@@ -24,10 +26,17 @@ export function useLinkedPlaceOf(): (point: Pick<TourPlannerWaypoint, 'linkedPla
|
||||
}
|
||||
|
||||
/** CW-04: `walkScheduleOf`, worked out again only when one of its parts changes. */
|
||||
export function useWalkSchedule({ stations, route, walkingMinutes, day, placeOf }: WalkScheduleInput): WalkSchedule {
|
||||
export function useWalkSchedule({
|
||||
stations,
|
||||
route,
|
||||
walkingMinutes,
|
||||
day,
|
||||
placeOf,
|
||||
ferries = NO_FERRIES,
|
||||
}: WalkScheduleInput): WalkSchedule {
|
||||
return useMemo(
|
||||
() => walkScheduleOf({ stations, route, walkingMinutes, day, placeOf }),
|
||||
[day, placeOf, route, stations, walkingMinutes]
|
||||
() => walkScheduleOf({ stations, route, walkingMinutes, day, placeOf, ferries }),
|
||||
[day, ferries, placeOf, route, stations, walkingMinutes]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -48,22 +57,24 @@ export interface PlannerWalkSchedule {
|
||||
export function usePlannerWalkSchedule(
|
||||
planner: Pick<
|
||||
TourPlannerController,
|
||||
'tourType' | 'editingPlaceId' | 'waypoints' | 'route' | 'routeCurrent' | 'walkingDurationMinutes'
|
||||
'tourType' | 'editingPlaceId' | 'waypoints' | 'route' | 'routeCurrent' | 'walkingDurationMinutes' | 'walkFerries'
|
||||
>,
|
||||
placeOf: LinkedPlaceOf
|
||||
): PlannerWalkSchedule {
|
||||
const days = useTripStore((state) => state.days) ?? NO_DAYS;
|
||||
const assignments = useTripStore((state) => state.assignments) ?? NO_ASSIGNMENTS;
|
||||
const { tourType, editingPlaceId, waypoints, route, routeCurrent, walkingDurationMinutes } = planner;
|
||||
const { tourType, editingPlaceId, waypoints, route, routeCurrent, walkingDurationMinutes, walkFerries } = planner;
|
||||
const enabled = tourType === 'walk';
|
||||
const choice = useWalkDay(enabled ? (editingPlaceId ?? null) : null, days, assignments, null);
|
||||
const stations = useMemo(() => (enabled ? walkStationsOf(waypoints) : NO_STATIONS), [enabled, waypoints]);
|
||||
const ferries = useMemo(() => ferryLegsOfCrossings(walkFerries.crossings), [walkFerries.crossings]);
|
||||
const schedule = useWalkSchedule({
|
||||
stations,
|
||||
route: routeCurrent ? (route ?? null) : null,
|
||||
walkingMinutes: walkingDurationMinutes ?? null,
|
||||
day: choice.day,
|
||||
placeOf,
|
||||
ferries,
|
||||
});
|
||||
return { enabled, choice, schedule, stationCount: stations.length };
|
||||
}
|
||||
|
||||
@@ -1,31 +1,33 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { TourPlannerWaypoint } from '../planner/tourPlannerWaypoints';
|
||||
import { readWalkStations } from './walkStationsRead';
|
||||
import { readWalkPoints, type WalkPoints } from './walkStationsRead';
|
||||
|
||||
const UNREAD: WalkPoints = { stations: [], ferries: [] };
|
||||
|
||||
/**
|
||||
* CW-03: a saved walk's stations in order: null while they load, none where
|
||||
* they could not be read. Read again when the walk is saved (its revision
|
||||
* moves on), here or by someone else, so the detail never shows the stations
|
||||
* of before; the ones shown stay until the new ones are in.
|
||||
* CW-03: a saved walk's stations in order, with its ferry legs (CW-12): null
|
||||
* while they load, none where they could not be read. Read again when the
|
||||
* walk is saved (its revision moves on), here or by someone else, so the
|
||||
* detail never shows the stations of before; the ones shown stay until the
|
||||
* new ones are in.
|
||||
*/
|
||||
export function useWalkStations(
|
||||
tripId: number | string,
|
||||
placeId: number,
|
||||
enabled: boolean,
|
||||
revision?: number
|
||||
): TourPlannerWaypoint[] | null {
|
||||
const [stations, setStations] = useState<{ placeId: number; points: TourPlannerWaypoint[] } | null>(null);
|
||||
): WalkPoints | null {
|
||||
const [walk, setWalk] = useState<{ placeId: number; points: WalkPoints } | null>(null);
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
const controller = new AbortController();
|
||||
readWalkStations(tripId, placeId, controller.signal)
|
||||
readWalkPoints(tripId, placeId, controller.signal)
|
||||
.then((points) => {
|
||||
if (!controller.signal.aborted) setStations({ placeId, points });
|
||||
if (!controller.signal.aborted) setWalk({ placeId, points });
|
||||
})
|
||||
.catch(() => {
|
||||
if (!controller.signal.aborted) setStations({ placeId, points: [] });
|
||||
if (!controller.signal.aborted) setWalk({ placeId, points: UNREAD });
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [enabled, placeId, revision, tripId]);
|
||||
return enabled && stations?.placeId === placeId ? stations.points : null;
|
||||
return enabled && walk?.placeId === placeId ? walk.points : null;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { TOUR_FIXED_LEG_MAX_POINTS, type PlannableTourType, type TourFixedLeg } from '@trek/shared';
|
||||
import { TOUR_FIXED_LEG_MAX_POINTS, type PlannableTourType, type TourFixedLeg, type WalkFerryLeg } from '@trek/shared';
|
||||
import { haversineKm } from '../../../utils/geo';
|
||||
import type { WalkFerryCrossing } from '../planner/tourRouting';
|
||||
|
||||
@@ -44,18 +44,54 @@ export function ferryLegOf(crossing: WalkFerryCrossing, from: LegPoint, to: LegP
|
||||
return {
|
||||
kind: 'ferry',
|
||||
geometry,
|
||||
crossing: [crossing.crossing[0] + shift, crossing.crossing[1] + shift],
|
||||
minutes: crossing.seconds === null ? null : Math.round(crossing.seconds / 60),
|
||||
crossings: crossing.crossings.map(([from, to]): [number, number] => [from + shift, to + shift]),
|
||||
minutes: ferryMinutesOf(crossing),
|
||||
walk_minutes: Math.round(crossing.walkSeconds / 60),
|
||||
};
|
||||
}
|
||||
|
||||
/** The crossing as a line of its own, for the map to show it. */
|
||||
/** The stretch of the leg from where its first boat leaves to where its last lands, for the map to show it. */
|
||||
export function crossingLine(crossing: WalkFerryCrossing): [number, number][] {
|
||||
return crossing.geometry.slice(crossing.crossing[0], crossing.crossing[1] + 1);
|
||||
const first = crossing.crossings[0];
|
||||
const last = crossing.crossings[crossing.crossings.length - 1];
|
||||
return first && last ? crossing.geometry.slice(first[0], last[1] + 1) : crossing.geometry;
|
||||
}
|
||||
|
||||
/** The minutes a crossing takes by boat, null where the router gave none. */
|
||||
export function ferryMinutesOf(crossing: Pick<WalkFerryCrossing, 'seconds'>): number | null {
|
||||
return crossing.seconds === null ? null : Math.max(1, Math.round(crossing.seconds / 60));
|
||||
}
|
||||
|
||||
/** The planner's crossings as the ferry legs a walk's times read: the boat parts of each leg and their minutes. */
|
||||
export function ferryLegsOfCrossings(crossings: readonly WalkFerryCrossing[]): WalkFerryLeg[] {
|
||||
return crossings.map((crossing) => ({
|
||||
crossings: crossing.crossings.map(([from, to]) => crossing.geometry.slice(from, to + 1)),
|
||||
minutes: ferryMinutesOf(crossing),
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* The stations a leg runs between as the stop list shows them: a leg from or
|
||||
* to a shaping point is named by the station before it and the one after it.
|
||||
*/
|
||||
export function legStationsOf<T extends { shaping?: boolean }>(
|
||||
points: readonly T[],
|
||||
leg: number
|
||||
): { from: T | null; to: T | null } {
|
||||
let from = leg;
|
||||
while (from > 0 && points[from]?.shaping) from -= 1;
|
||||
let to = leg + 1;
|
||||
while (to < points.length - 1 && points[to]?.shaping) to += 1;
|
||||
return { from: points[from] ?? null, to: points[to] ?? null };
|
||||
}
|
||||
|
||||
/** The minutes a walk's crossings take by boat: their sum, null while one has no time, undefined without any. */
|
||||
export function crossingsMinutesOf(
|
||||
crossings: readonly Pick<WalkFerryCrossing, 'seconds'>[]
|
||||
): number | null | undefined {
|
||||
if (crossings.length === 0) return undefined;
|
||||
const minutes = crossings.map(ferryMinutesOf);
|
||||
return minutes.every((value) => value !== null)
|
||||
? minutes.reduce<number>((sum, value) => sum + (value ?? 0), 0)
|
||||
: null;
|
||||
}
|
||||
|
||||
@@ -74,6 +74,14 @@ describe('walkRemainingOf', () => {
|
||||
it('reads every station as planned before anything is checked off', () => {
|
||||
expect(walkRemainingOf(input())?.walking).toMatchObject({ remaining_minutes: 40, upper_bound: false });
|
||||
});
|
||||
|
||||
it('leaves out a ferry leg that starts at a shaping point, as the server reads it off all the points (CW-12)', () => {
|
||||
const visits = { 'stop-museum': 'visited', 'stop-square': 'visited' } as const;
|
||||
// The boat from a shaping point by the square to the cafe: the last stretch is no walking.
|
||||
const ferries = [{ crossings: [ROUTE.slice(1)], minutes: 6 }];
|
||||
expect(walkRemainingOf(input({ visits }))?.walking.remaining_minutes).toBe(20);
|
||||
expect(walkRemainingOf(input({ visits, ferries }))?.walking.remaining_minutes).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('walkRemainingText', () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ferryCrossingsOf, walkRemainderOf, type WalkRemainder, type WalkStationRef } from '@trek/shared';
|
||||
import { walkRemainderOf, type WalkFerryLeg, type WalkRemainder, type WalkStationRef } from '@trek/shared';
|
||||
import { useMemo } from 'react';
|
||||
import type { useTranslation } from '../../../i18n';
|
||||
import type { VisitsByStation } from '../../../store/tourVisitStore';
|
||||
@@ -16,8 +16,15 @@ export interface WalkRemainingInput {
|
||||
route: ReadonlyArray<readonly [number, number]> | null;
|
||||
walkingMinutes: number | null;
|
||||
placeOf: LinkedPlaceOf;
|
||||
/**
|
||||
* CW-12: the walk's ferry legs, read off all its points as the server reads
|
||||
* them, so one from a shaping point counts too.
|
||||
*/
|
||||
ferries?: readonly WalkFerryLeg[];
|
||||
}
|
||||
|
||||
const NO_FERRIES: readonly WalkFerryLeg[] = [];
|
||||
|
||||
/**
|
||||
* CW-13: what is left of a walk on the day it was opened from, by the same
|
||||
* rule the assistant reads over MCP (`walk-remaining.ts` in `@trek/shared`),
|
||||
@@ -30,6 +37,7 @@ export function walkRemainingOf({
|
||||
route,
|
||||
walkingMinutes,
|
||||
placeOf,
|
||||
ferries = NO_FERRIES,
|
||||
}: WalkRemainingInput): WalkRemainder | null {
|
||||
if (!stations || stations.length === 0) return null;
|
||||
return walkRemainderOf({
|
||||
@@ -44,8 +52,8 @@ export function walkRemainingOf({
|
||||
})),
|
||||
line: route,
|
||||
walkingMinutes,
|
||||
// CW-12: a ferry leg taken from a station is crossed by boat and takes none of the walking time.
|
||||
crossings: ferryCrossingsOf(stations.map((station) => ({ fixed_leg: station.fixedLeg }))),
|
||||
// CW-12: a ferry leg is crossed by boat and takes none of the walking time.
|
||||
crossings: ferries.flatMap((leg) => leg.crossings),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -55,10 +63,11 @@ export function useWalkRemaining({
|
||||
route,
|
||||
walkingMinutes,
|
||||
placeOf,
|
||||
ferries = NO_FERRIES,
|
||||
}: WalkRemainingInput): WalkRemainder | null {
|
||||
return useMemo(
|
||||
() => walkRemainingOf({ stations, visits, route, walkingMinutes, placeOf }),
|
||||
[placeOf, route, stations, visits, walkingMinutes]
|
||||
() => walkRemainingOf({ stations, visits, route, walkingMinutes, placeOf, ferries }),
|
||||
[ferries, placeOf, route, stations, visits, walkingMinutes]
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -80,6 +80,18 @@ describe('walkScheduleOf', () => {
|
||||
expect(schedule.byStation.get('square')?.fit).toEqual({ kind: 'open', source: 'place', window: [540, 1410] });
|
||||
});
|
||||
|
||||
it('reaches a station after a crossing by boat its minutes later, the walk shared out on land only (CW-12)', () => {
|
||||
// 20 min of walking to the square, then the boat to the cafe.
|
||||
const stations = [museum, { ...square, stayMinutes: 0 }, cafe];
|
||||
const boat = (minutes: number | null) => [{ crossings: [ROUTE.slice(1)], minutes }];
|
||||
const crossed = walkScheduleOf(input({ stations, walkingMinutes: 20, ferries: boat(12) }));
|
||||
expect(crossed.byStation.get('square')).toMatchObject({ arrival: 680, atLeast: false });
|
||||
expect(crossed.byStation.get('cafe')).toMatchObject({ arrival: 692, atLeast: false, leave: 722 });
|
||||
|
||||
const untimed = walkScheduleOf(input({ stations, walkingMinutes: 20, ferries: boat(null) }));
|
||||
expect(untimed.byStation.get('cafe')).toMatchObject({ arrival: 680, atLeast: true });
|
||||
});
|
||||
|
||||
it('knows no hours where no station has any', () => {
|
||||
const schedule = walkScheduleOf(input({ stations: [{ ...museum, openingHours: null }, square, cafe] }));
|
||||
expect(schedule.state).toBe('ready');
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
import { minutesOf, stationArrivals, stationFit, stationHoursOn, type StationFit } from '@trek/shared';
|
||||
import {
|
||||
boatsAlong,
|
||||
minutesOf,
|
||||
stationArrivals,
|
||||
stationFit,
|
||||
stationHoursOn,
|
||||
type StationFit,
|
||||
type WalkFerryLeg,
|
||||
} from '@trek/shared';
|
||||
import type { Assignment, Day, Place } from '../../../types';
|
||||
import type { TourPlannerWaypoint } from '../planner/tourPlannerWaypoints';
|
||||
|
||||
@@ -44,6 +52,8 @@ export interface WalkScheduleInput {
|
||||
/** The day it is looked at, with the walk's start that day; null when it is on none. */
|
||||
day: { day: Pick<Day, 'date'>; start: string | null } | null;
|
||||
placeOf: LinkedPlaceOf;
|
||||
/** CW-12: the walk's ferry legs; a station after a boat lands is reached the boat's minutes later. */
|
||||
ferries?: readonly WalkFerryLeg[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -67,11 +77,18 @@ function startOf(day: WalkScheduleInput['day']): { date: string; start: number }
|
||||
return start === null ? 'noStart' : { date: day.day.date, start };
|
||||
}
|
||||
|
||||
export function walkScheduleOf({ stations, route, walkingMinutes, day, placeOf }: WalkScheduleInput): WalkSchedule {
|
||||
export function walkScheduleOf({
|
||||
stations,
|
||||
route,
|
||||
walkingMinutes,
|
||||
day,
|
||||
placeOf,
|
||||
ferries = [],
|
||||
}: WalkScheduleInput): WalkSchedule {
|
||||
const from = startOf(day);
|
||||
if (typeof from === 'string') return emptySchedule(from);
|
||||
if (!stations || !route) return emptySchedule('noRoute');
|
||||
const arrivals = stationArrivals(stations, route, from.start, walkingMinutes);
|
||||
const arrivals = stationArrivals(stations, route, from.start, walkingMinutes, boatsAlong(route, ferries));
|
||||
if (!arrivals) return emptySchedule('noRoute');
|
||||
const byStation = new Map<string, StationSchedule>();
|
||||
let anyHours = false;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { walkStationsOf } from '@trek/shared';
|
||||
import { ferryLegsOf, walkStationsOf, type WalkFerryLeg } from '@trek/shared';
|
||||
import { tourRepo } from '../../../repo/tourRepo';
|
||||
import { randomId } from '../../../utils/randomId';
|
||||
import { plannerWaypointsOf, type TourPlannerWaypoint } from '../planner/tourPlannerWaypoints';
|
||||
@@ -23,6 +23,23 @@ export async function readWalkStations(
|
||||
placeId: number,
|
||||
signal?: AbortSignal
|
||||
): Promise<TourPlannerWaypoint[]> {
|
||||
const detail = await tourRepo.detail(tripId, placeId, signal);
|
||||
return ownStations(walkStationsOf(plannerWaypointsOf(detail.waypoints, randomId)), placeId);
|
||||
return (await readWalkPoints(tripId, placeId, signal)).stations;
|
||||
}
|
||||
|
||||
/** A saved walk's stations with its ferry legs (CW-12), which may run from any of its points, a shaping point too. */
|
||||
export interface WalkPoints {
|
||||
stations: TourPlannerWaypoint[];
|
||||
ferries: WalkFerryLeg[];
|
||||
}
|
||||
|
||||
export async function readWalkPoints(
|
||||
tripId: number | string,
|
||||
placeId: number,
|
||||
signal?: AbortSignal
|
||||
): Promise<WalkPoints> {
|
||||
const detail = await tourRepo.detail(tripId, placeId, signal);
|
||||
return {
|
||||
stations: ownStations(walkStationsOf(plannerWaypointsOf(detail.waypoints, randomId)), placeId),
|
||||
ferries: ferryLegsOf(detail.waypoints),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
import { someStaysUnknown, walkTimesOf, type WalkTimes } from '../planner/stationModel';
|
||||
import type { WalkFerryCrossing } from '../planner/tourRouting';
|
||||
import type { TourMetricField } from '../tourParts';
|
||||
import { formatPlannedTourDuration, plannedTotalText } from '../tourPresentation';
|
||||
import { ferryMinutesOf } from './walkFerry';
|
||||
|
||||
type Translate = (key: string, params?: Record<string, unknown>) => string;
|
||||
|
||||
/** What a city walk's stays are known of: how many, how many have no stay entered, and the stays entered. */
|
||||
type WalkStays = Pick<WalkTimes, 'stayMinutes' | 'unknownStays' | 'stations'>;
|
||||
/** What a city walk's stays are known of: how many, how many have no stay entered, and the stays entered; with its boats (CW-12). */
|
||||
type WalkStays = Pick<WalkTimes, 'stayMinutes' | 'unknownStays' | 'stations' | 'ferryMinutes'>;
|
||||
|
||||
/**
|
||||
* A city walk's stays as said: their sum, and at least the sum while some
|
||||
@@ -29,22 +27,16 @@ export interface WalkTimeFieldsInput {
|
||||
stays: WalkStays;
|
||||
/** A total entered by hand, which stays apart from the one worked out; null when there is none. */
|
||||
manualMinutes: number | null;
|
||||
/** CW-12: the walk's crossings by boat, whose time is never walking time. */
|
||||
ferries?: readonly Pick<WalkFerryCrossing, 'seconds'>[];
|
||||
t: Translate;
|
||||
}
|
||||
|
||||
/** CW-12: the time of a walk's crossings by boat, as a field of its own; none without a crossing. */
|
||||
function ferryField(ferries: readonly Pick<WalkFerryCrossing, 'seconds'>[], t: Translate): TourMetricField[] {
|
||||
if (ferries.length === 0) return [];
|
||||
const minutes = ferries.map(ferryMinutesOf);
|
||||
const known = minutes.every((value) => value !== null);
|
||||
function ferryField(minutes: number | null | undefined, t: Translate): TourMetricField[] {
|
||||
if (minutes === undefined) return [];
|
||||
return [
|
||||
{
|
||||
label: t('tours.walk.ferry.field'),
|
||||
value: known
|
||||
? formatPlannedTourDuration(minutes.reduce<number>((sum, value) => sum + (value ?? 0), 0))
|
||||
: t('tours.walk.ferry.timeUnknown'),
|
||||
value: minutes === null ? t('tours.walk.ferry.timeUnknown') : formatPlannedTourDuration(minutes),
|
||||
info: { label: t('tours.walk.ferry.fieldInfoLabel'), description: t('tours.walk.ferry.fieldInfo') },
|
||||
},
|
||||
];
|
||||
@@ -52,7 +44,8 @@ function ferryField(ferries: readonly Pick<WalkFerryCrossing, 'seconds'>[], t: T
|
||||
|
||||
/**
|
||||
* CW-02: a city walk's times as fields, in one wording for the planner and the
|
||||
* tour detail: the walking time, the stays, and the planned total of both. A
|
||||
* tour detail: the walking time, the boat apart (CW-12), the stays, and the
|
||||
* planned total of them. A
|
||||
* total entered by hand keeps its own label, and the total worked out shows
|
||||
* beside it as computed, so the two never read as one. 45 min of walking, a
|
||||
* museum of 90 min and a cafe of 30 min read 45 min, 2 h and 2 h 45 min.
|
||||
@@ -62,18 +55,17 @@ export function walkTimeFields({
|
||||
walkingMinutes,
|
||||
stays,
|
||||
manualMinutes,
|
||||
ferries = [],
|
||||
t,
|
||||
}: WalkTimeFieldsInput): TourMetricField[] {
|
||||
const notCalculated = t('tours.planner.walkingTimeUnknown');
|
||||
const { stayMinutes, unknownStays, stations } = stays;
|
||||
const times = walkTimesOf({ walkingMinutes, stayMinutes, unknownStays, stations });
|
||||
const { stayMinutes, unknownStays, stations, ferryMinutes } = stays;
|
||||
const times = walkTimesOf({ walkingMinutes, stayMinutes, unknownStays, stations, ferryMinutes });
|
||||
const computed =
|
||||
plannedTotalText({ plannedTotalMinutes: times.totalMinutes, atLeast: times.partial }, t) ?? notCalculated;
|
||||
const staysText = walkStaysText(stays, t);
|
||||
const parts: TourMetricField[] = [
|
||||
{ ...walking, value: walkingMinutes == null ? notCalculated : formatPlannedTourDuration(walkingMinutes) },
|
||||
...ferryField(ferries, t),
|
||||
...ferryField(ferryMinutes, t),
|
||||
...(staysText ? [{ label: t('tours.walk.stays'), value: staysText }] : []),
|
||||
];
|
||||
const planned = t('tours.planner.plannedShort');
|
||||
|
||||
@@ -72,8 +72,8 @@ export function useTripPlannerPage() {
|
||||
// What no router planned is dotted; a paddle tour's portages brown, whitewater amber, gaps red, a walk's ferry blue.
|
||||
const paddlePaint = usePaddlePaint()
|
||||
const walkPaint = useWalkRoutePaint()
|
||||
// A route kept from before a plan that failed no longer stands for the points: greyed, not hidden.
|
||||
const staleRoute = editingRoute && !tourPlanner.routeCurrent && tourPlanner.status === 'routing-failed'
|
||||
// CW-12: a walk kept from before a leg no way joins no longer stands for its stations: greyed, not hidden.
|
||||
const staleRoute = editingRoute && !tourPlanner.routeCurrent && tourPlanner.error === 'walk-gap'
|
||||
const partStyle = tourRouteStyle(
|
||||
!wandererBrowser.open && editingRoute ? tourPlanner.routeParts : !tourConversion.line ? trackParts : null,
|
||||
tourPlanner.isPaddle || !!trackParts,
|
||||
|
||||
@@ -79,6 +79,17 @@ export function hikePlannerDefaults() {
|
||||
toggleStageEnd: vi.fn(),
|
||||
canEnd: vi.fn(() => false),
|
||||
},
|
||||
// CW-12: a walk with no crossing by boat and no leg it cannot join.
|
||||
walkFerries: {
|
||||
crossings: [],
|
||||
pending: [],
|
||||
blocksSave: false,
|
||||
gap: null,
|
||||
acceptable: vi.fn(() => true),
|
||||
accept: vi.fn(),
|
||||
release: vi.fn(),
|
||||
show: vi.fn(),
|
||||
},
|
||||
// P2C-03: a tour opened at its first revision, with nothing known about others.
|
||||
revision: {
|
||||
base: null,
|
||||
|
||||
@@ -188,6 +188,7 @@ export function derivedFields(detail: TourDetailResponse, { controlsFromTrack, l
|
||||
...(line ? ['line.preview'] : []),
|
||||
...(controlsFromTrack ? ['waypoints'] : []),
|
||||
...(type === 'walk' ? ['tour.station_count', 'tour.station_stay_minutes', 'tour.station_stays_unknown'] : []),
|
||||
...(detail.tour.walk_ferry_minutes !== undefined ? ['tour.walk_ferry_minutes'] : []),
|
||||
...(run ? ['run.open'] : []),
|
||||
...(type === 'kayak' ? ['tour.paddle_check', 'obstacle_check'] : []),
|
||||
...((detail.activities?.length ?? 0) > 0 ? ['activities[].metrics'] : []),
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -378,7 +378,7 @@ describe('City walks e2e (real guards + temp SQLite)', () => {
|
||||
[48.12, 11.52],
|
||||
[48.13, 11.53],
|
||||
],
|
||||
crossing: [0, 1],
|
||||
crossings: [[0, 1]],
|
||||
minutes: 7,
|
||||
walk_minutes: 3,
|
||||
};
|
||||
@@ -398,13 +398,15 @@ describe('City walks e2e (real guards + temp SQLite)', () => {
|
||||
const detail = await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', cookie(VIEWER));
|
||||
expect(detail.body.waypoints[1].fixed_leg).toEqual(FERRY);
|
||||
expect(detail.body.tour.duration).toBe(60);
|
||||
// The boat is part of the day apart from the walking time, so a list can count it into the planned total.
|
||||
expect(detail.body.tour.walk_ferry_minutes).toBe(7);
|
||||
});
|
||||
|
||||
it('refuses it on any other type, and a crossing that does not run forwards within its leg', async () => {
|
||||
const bodies = [
|
||||
across(FERRY, 'hike'),
|
||||
across({ ...FERRY, crossing: [1, 0] }),
|
||||
across({ ...FERRY, crossing: [1, 3] }),
|
||||
across({ ...FERRY, crossings: [[1, 0]] }),
|
||||
across({ ...FERRY, crossings: [[1, 3]] }),
|
||||
across({ ...FERRY, minutes: -1 }),
|
||||
];
|
||||
const statuses = await bodies.reduce<Promise<number[]>>(
|
||||
|
||||
@@ -34,8 +34,6 @@ interface StationColumns {
|
||||
opening_hours?: string | null;
|
||||
/** 1 for a shaping point. */
|
||||
shaping?: number;
|
||||
/** The leg to the next point as a fixed line, as JSON. */
|
||||
fixed_leg?: string | null;
|
||||
/** MDT-01: 1 for a stop that ends a stage of a multi-day tour. */
|
||||
stage_end?: number;
|
||||
/** The id of the place of the trip the point stands for. */
|
||||
|
||||
@@ -383,7 +383,7 @@ describe('TourVisitsService', () => {
|
||||
[48.11, 11.51],
|
||||
[48.12, 11.52],
|
||||
],
|
||||
crossing: [0, 1],
|
||||
crossings: [[0, 1]],
|
||||
minutes: 7,
|
||||
walk_minutes: 0,
|
||||
};
|
||||
|
||||
@@ -763,6 +763,7 @@ const tours: TranslationStrings = {
|
||||
'لا يُحتسب العبور وقتَ مشي. للحفظ، اعتمد العبّارة أو انقل محطة كي يربطهما طريق سيرًا.',
|
||||
'tours.walk.ferry.accepted': 'عبّارة من {from} إلى {to}، اعتُمدت عن قصد. يبقى وقتها منفصلًا عن وقت المشي.',
|
||||
'tours.walk.ferry.accept': 'اعتماد العبّارة',
|
||||
'tours.walk.ferry.acceptTooLong': 'خط هذا العبور أطول من أن يُحفظ كمقطع واحد. أضف محطة في الطريق أو انقل واحدة.',
|
||||
'tours.walk.ferry.show': 'إظهار العبور',
|
||||
'tours.walk.ferry.selectStop': 'اختيار المحطة {number}',
|
||||
'tours.walk.ferry.time': '{time} بالقارب',
|
||||
@@ -771,7 +772,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'عبّارة',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'عن وقت العبّارة',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'الوقت الذي تستغرقه العبورات بالقارب كما يعطيه الموجّه. يبقى منفصلًا عن وقت المشي وليس ضمن الإجمالي المخطط.',
|
||||
'الوقت الذي تستغرقه العبورات بالقارب كما يعطيه الموجّه. يبقى منفصلًا عن وقت المشي لكنه يُحسب في الإجمالي المخطط؛ وبدونه يكون الإجمالي حدًا أدنى.',
|
||||
'tours.walk.ferry.leg': 'عبور بالعبّارة',
|
||||
'tours.walk.ferry.legInfo': 'عُبر بالقارب لا سيرًا. وقته ليس ضمن وقت المشي.',
|
||||
'tours.walk.ferry.release': 'التخطيط سيرًا من جديد',
|
||||
|
||||
@@ -765,6 +765,8 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.accepted':
|
||||
'{from}-dan {to}-a bərə, qəsdən qəbul edilib. Onun vaxtı yürüş vaxtından ayrı saxlanılır.',
|
||||
'tours.walk.ferry.accept': 'Bərəni qəbul et',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'Bu keçidin xətti bir hissə kimi saxlanmaq üçün çox uzundur. Yolda bir dayanacaq əlavə et və ya birini köçür.',
|
||||
'tours.walk.ferry.show': 'Keçidi göstər',
|
||||
'tours.walk.ferry.selectStop': '{number} nömrəli dayanacağı seç',
|
||||
'tours.walk.ferry.time': 'Qayıqla {time}',
|
||||
@@ -773,7 +775,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'Bərə',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'Bərə vaxtı haqqında',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'Qayıqla keçidlərin vaxtı, marşrutlaşdırıcının verdiyi kimi. Yürüş vaxtından ayrı saxlanılır və planlanan cəmə daxil deyil.',
|
||||
'Qayıqla keçidlərin vaxtı, marşrutlaşdırıcının verdiyi kimi. Yürüş vaxtından ayrı saxlanılır, amma planlanan cəmə daxildir; o olmadan cəm minimum həddir.',
|
||||
'tours.walk.ferry.leg': 'Bərə keçidi',
|
||||
'tours.walk.ferry.legInfo': 'Qayıqla keçilib, piyada deyil. Vaxtı yürüş vaxtına daxil deyil.',
|
||||
'tours.walk.ferry.release': 'Yenidən piyada planla',
|
||||
|
||||
@@ -773,6 +773,8 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.accepted':
|
||||
'Balsa de {from} a {to}, aceita de propósito. O tempo dela fica separado do tempo de caminhada.',
|
||||
'tours.walk.ferry.accept': 'Aceitar balsa',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'A linha desta travessia é longa demais para ser guardada como um trecho. Adicione uma parada no caminho ou mova uma.',
|
||||
'tours.walk.ferry.show': 'Mostrar travessia',
|
||||
'tours.walk.ferry.selectStop': 'Selecionar parada {number}',
|
||||
'tours.walk.ferry.time': '{time} de barco',
|
||||
@@ -781,7 +783,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'Balsa',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'Sobre o tempo de balsa',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'O tempo das travessias de barco, como o roteador o informa. Fica separado do tempo de caminhada e não entra no total planejado.',
|
||||
'O tempo das travessias de barco, como o roteador o informa. Fica separado do tempo de caminhada, mas entra no total planejado; sem ele, o total é um mínimo.',
|
||||
'tours.walk.ferry.leg': 'Travessia de balsa',
|
||||
'tours.walk.ferry.legInfo': 'Atravessado de barco, não a pé. O tempo não está no tempo de caminhada.',
|
||||
'tours.walk.ferry.release': 'Planejar a pé de novo',
|
||||
|
||||
@@ -777,6 +777,8 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.accepted':
|
||||
'Ferri de {from} a {to}, acceptat expressament. El seu temps es manté a part del temps a peu.',
|
||||
'tours.walk.ferry.accept': 'Acceptar el ferri',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
"La línia d'aquesta travessia és massa llarga per desar-la com un sol tram. Afegeix una parada pel camí o mou-ne una.",
|
||||
'tours.walk.ferry.show': 'Mostrar la travessia',
|
||||
'tours.walk.ferry.selectStop': 'Tria la parada {number}',
|
||||
'tours.walk.ferry.time': '{time} en vaixell',
|
||||
@@ -785,7 +787,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'Ferri',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'Sobre el temps de ferri',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'El temps de les travessies en vaixell, tal com el dona el router. Es manté a part del temps a peu i no és al total planificat.',
|
||||
'El temps de les travessies en vaixell, tal com el dona el router. Es manté a part del temps a peu però compta al total planificat; sense ell, el total és un mínim.',
|
||||
'tours.walk.ferry.leg': 'Travessia en ferri',
|
||||
'tours.walk.ferry.legInfo': 'Travessat en vaixell, no a peu. El seu temps no és al temps a peu.',
|
||||
'tours.walk.ferry.release': 'Tornar a planificar a peu',
|
||||
|
||||
@@ -759,6 +759,8 @@ const tours: TranslationStrings = {
|
||||
'Přeprava se nepočítá do doby chůze. Pro uložení převezmi trajekt nebo přesuň zastávku, aby je spojila pěší cesta.',
|
||||
'tours.walk.ferry.accepted': 'Trajekt z {from} do {to}, převzatý záměrně. Jeho čas je oddělen od doby chůze.',
|
||||
'tours.walk.ferry.accept': 'Převzít trajekt',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'Trasa této přepravy je příliš dlouhá na to, aby se uložila jako jeden úsek. Přidej zastávku po cestě, nebo jednu přesuň.',
|
||||
'tours.walk.ferry.show': 'Ukázat přepravu',
|
||||
'tours.walk.ferry.selectStop': 'Vybrat zastávku {number}',
|
||||
'tours.walk.ferry.time': '{time} lodí',
|
||||
@@ -767,7 +769,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'Trajekt',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'O čase trajektu',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'Čas přeprav lodí, jak ho udává plánovač. Je oddělen od doby chůze a není v plánovaném celku.',
|
||||
'Čas přeprav lodí, jak ho udává plánovač. Je oddělen od doby chůze, ale počítá se do plánovaného celku; bez něj je celek jen spodní hranice.',
|
||||
'tours.walk.ferry.leg': 'Přeprava trajektem',
|
||||
'tours.walk.ferry.legInfo': 'Přepluto lodí, ne prošlo. Jeho čas není v době chůze.',
|
||||
'tours.walk.ferry.release': 'Znovu naplánovat pěšky',
|
||||
|
||||
@@ -781,6 +781,8 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.accepted':
|
||||
'Fähre von {from} nach {to}, bewusst übernommen. Ihre Zeit steht getrennt von der Gehzeit.',
|
||||
'tours.walk.ferry.accept': 'Fähre übernehmen',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'Die Linie dieser Überfahrt ist zu lang, um sie als einen Abschnitt zu speichern. Setze unterwegs eine Station oder verschiebe eine.',
|
||||
'tours.walk.ferry.show': 'Überfahrt zeigen',
|
||||
'tours.walk.ferry.selectStop': 'Station {number} wählen',
|
||||
'tours.walk.ferry.time': '{time} mit dem Boot',
|
||||
@@ -789,7 +791,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'Fähre',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'Zur Fährzeit',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'Die Zeit der Überfahrten mit dem Boot, so wie der Router sie angibt. Sie steht getrennt von der Gehzeit und ist nicht in der geplanten Gesamtzeit.',
|
||||
'Die Zeit der Überfahrten mit dem Boot, so wie der Router sie angibt. Sie steht getrennt von der Gehzeit, zählt aber zur geplanten Gesamtzeit; fehlt sie, ist die Gesamtzeit ein Mindestwert.',
|
||||
'tours.walk.ferry.leg': 'Überfahrt mit der Fähre',
|
||||
'tours.walk.ferry.legInfo': 'Mit dem Boot übergesetzt, nicht gegangen. Ihre Zeit ist nicht in der Gehzeit.',
|
||||
'tours.walk.ferry.release': 'Wieder zu Fuß planen',
|
||||
|
||||
@@ -760,6 +760,8 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.accepted':
|
||||
'Ferry from {from} to {to}, taken on purpose. Its time is kept apart from the walking time.',
|
||||
'tours.walk.ferry.accept': 'Take ferry',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'The line of this crossing is too long to keep as one leg. Add a stop on the way, or move one.',
|
||||
'tours.walk.ferry.show': 'Show crossing',
|
||||
'tours.walk.ferry.selectStop': 'Select stop {number}',
|
||||
'tours.walk.ferry.time': '{time} by boat',
|
||||
@@ -768,7 +770,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'Ferry',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'About the ferry time',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'The time the crossings by boat take, as the router gives it. It is kept apart from the walking time and is not in the planned total.',
|
||||
'The time the crossings by boat take, as the router gives it. It is kept apart from the walking time but counted in the planned total; without it, the total is a lower bound.',
|
||||
'tours.walk.ferry.leg': 'Ferry crossing',
|
||||
'tours.walk.ferry.legInfo': 'Crossed by boat, not walked. Its time is not in the walking time.',
|
||||
'tours.walk.ferry.release': 'Plan on foot again',
|
||||
|
||||
@@ -773,6 +773,8 @@ const tours: TranslationStrings = {
|
||||
'La travesía no cuenta como tiempo a pie. Para guardar, acepta el ferri o mueve una parada para que un camino a pie las una.',
|
||||
'tours.walk.ferry.accepted': 'Ferri de {from} a {to}, aceptado a propósito. Su tiempo queda aparte del tiempo a pie.',
|
||||
'tours.walk.ferry.accept': 'Aceptar ferri',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'La línea de esta travesía es demasiado larga para guardarla como un solo tramo. Añade una parada en el camino o mueve una.',
|
||||
'tours.walk.ferry.show': 'Mostrar travesía',
|
||||
'tours.walk.ferry.selectStop': 'Elegir parada {number}',
|
||||
'tours.walk.ferry.time': '{time} en barco',
|
||||
@@ -781,7 +783,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'Ferri',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'Sobre el tiempo en ferri',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'El tiempo de las travesías en barco, tal como lo da el enrutador. Queda aparte del tiempo a pie y no está en el total planificado.',
|
||||
'El tiempo de las travesías en barco, tal como lo da el enrutador. Queda aparte del tiempo a pie, pero cuenta en el total planificado; sin él, el total es un mínimo.',
|
||||
'tours.walk.ferry.leg': 'Travesía en ferri',
|
||||
'tours.walk.ferry.legInfo': 'Cruzado en barco, no a pie. Su tiempo no está en el tiempo a pie.',
|
||||
'tours.walk.ferry.release': 'Planificar a pie de nuevo',
|
||||
|
||||
@@ -761,6 +761,8 @@ const tours: TranslationStrings = {
|
||||
'Ülesõitu ei loeta kõndimisajaks. Salvestamiseks võta praam üle või liiguta peatust, et jalgtee need ühendaks.',
|
||||
'tours.walk.ferry.accepted': 'Praam {from} kuni {to}, meelega üle võetud. Selle aeg on kõndimisajast eraldi.',
|
||||
'tours.walk.ferry.accept': 'Võta praam',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'Selle ülesõidu joon on liiga pikk, et seda ühe lõiguna hoida. Lisa teele peatus või liiguta mõnda.',
|
||||
'tours.walk.ferry.show': 'Näita ülesõitu',
|
||||
'tours.walk.ferry.selectStop': 'Vali peatus {number}',
|
||||
'tours.walk.ferry.time': '{time} paadiga',
|
||||
@@ -769,7 +771,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'Praam',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'Praamiajast',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'Paadiga ülesõitude aeg, nagu marsruutija selle annab. See on kõndimisajast eraldi ega kuulu planeeritud koguaega.',
|
||||
'Paadiga ülesõitude aeg, nagu marsruutija selle annab. See on kõndimisajast eraldi, kuid kuulub planeeritud koguaega; ilma selleta on koguaeg alampiir.',
|
||||
'tours.walk.ferry.leg': 'Praamiga ülesõit',
|
||||
'tours.walk.ferry.legInfo': 'Ületatud paadiga, mitte jalgsi. Selle aeg pole kõndimisajas.',
|
||||
'tours.walk.ferry.release': 'Planeeri uuesti jalgsi',
|
||||
|
||||
@@ -787,6 +787,8 @@ const tours: TranslationStrings = {
|
||||
"La traversée ne compte pas comme temps de marche. Pour enregistrer, prends le ferry ou déplace une étape pour qu'un chemin à pied les relie.",
|
||||
'tours.walk.ferry.accepted': 'Ferry de {from} à {to}, pris exprès. Son temps reste à part du temps de marche.',
|
||||
'tours.walk.ferry.accept': 'Prendre le ferry',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'La ligne de cette traversée est trop longue pour être gardée comme un seul tronçon. Ajoute une étape en chemin ou déplace-en une.',
|
||||
'tours.walk.ferry.show': 'Montrer la traversée',
|
||||
'tours.walk.ferry.selectStop': "Choisir l'étape {number}",
|
||||
'tours.walk.ferry.time': '{time} en bateau',
|
||||
@@ -796,7 +798,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'Ferry', // same-as-en
|
||||
'tours.walk.ferry.fieldInfoLabel': 'À propos du temps de ferry',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
"Le temps des traversées en bateau, tel que le calculateur le donne. Il reste à part du temps de marche et n'entre pas dans le total prévu.",
|
||||
'Le temps des traversées en bateau, tel que le calculateur le donne. Il reste à part du temps de marche mais entre dans le total prévu. Sans lui, le total est un minimum.',
|
||||
'tours.walk.ferry.leg': 'Traversée en ferry',
|
||||
'tours.walk.ferry.legInfo': "Traversé en bateau, pas à pied. Son temps n'est pas dans le temps de marche.",
|
||||
'tours.walk.ferry.release': 'Replanifier à pied',
|
||||
|
||||
@@ -792,6 +792,8 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.accepted':
|
||||
'Φέρι από {from} προς {to}, κρατημένο σκόπιμα. Ο χρόνος του μένει χωριστά από τον χρόνο περπατήματος.',
|
||||
'tours.walk.ferry.accept': 'Κράτηση φέρι',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'Η γραμμή αυτής της διάβασης είναι πολύ μεγάλη για να κρατηθεί ως ένα τμήμα. Πρόσθεσε μια στάση στη διαδρομή ή μετακίνησε μία.',
|
||||
'tours.walk.ferry.show': 'Εμφάνιση διάβασης',
|
||||
'tours.walk.ferry.selectStop': 'Επιλογή στάσης {number}',
|
||||
'tours.walk.ferry.time': '{time} με σκάφος',
|
||||
@@ -800,7 +802,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'Φέρι',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'Σχετικά με τον χρόνο φέρι',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'Ο χρόνος των διαβάσεων με σκάφος, όπως τον δίνει η δρομολόγηση. Μένει χωριστά από τον χρόνο περπατήματος και δεν μπαίνει στο προγραμματισμένο σύνολο.',
|
||||
'Ο χρόνος των διαβάσεων με σκάφος, όπως τον δίνει η δρομολόγηση. Μένει χωριστά από τον χρόνο περπατήματος, αλλά μετρά στο προγραμματισμένο σύνολο· χωρίς αυτόν, το σύνολο είναι ελάχιστο.',
|
||||
'tours.walk.ferry.leg': 'Διάβαση με φέρι',
|
||||
'tours.walk.ferry.legInfo': 'Διασχίστηκε με σκάφος, όχι με τα πόδια. Ο χρόνος του δεν είναι στον χρόνο περπατήματος.',
|
||||
'tours.walk.ferry.release': 'Ξανά σχεδιασμός με τα πόδια',
|
||||
|
||||
@@ -774,6 +774,8 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.accepted':
|
||||
'Komp {from} és {to} között, szándékosan elfogadva. Az ideje külön áll a gyaloglási időtől.',
|
||||
'tours.walk.ferry.accept': 'Komp elfogadása',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'Ennek az átkelésnek a vonala túl hosszú ahhoz, hogy egy szakaszként megmaradjon. Adj hozzá egy megállót útközben, vagy helyezz át egyet.',
|
||||
'tours.walk.ferry.show': 'Átkelés mutatása',
|
||||
'tours.walk.ferry.selectStop': '{number}. megálló kiválasztása',
|
||||
'tours.walk.ferry.time': '{time} hajóval',
|
||||
@@ -782,7 +784,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'Komp',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'A kompidőről',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'A hajós átkelések ideje, ahogy az útvonaltervező megadja. Külön áll a gyaloglási időtől, és nincs benne a tervezett összidőben.',
|
||||
'A hajós átkelések ideje, ahogy az útvonaltervező megadja. Külön áll a gyaloglási időtől, de beleszámít a tervezett összidőbe; nélküle az összidő csak alsó becslés.',
|
||||
'tours.walk.ferry.leg': 'Kompos átkelés',
|
||||
'tours.walk.ferry.legInfo': 'Hajóval átkelve, nem gyalog. Az ideje nincs a gyaloglási időben.',
|
||||
'tours.walk.ferry.release': 'Újratervezés gyalog',
|
||||
|
||||
@@ -772,6 +772,8 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.accepted':
|
||||
'Feri dari {from} ke {to}, diambil dengan sengaja. Waktunya dipisahkan dari waktu jalan kaki.',
|
||||
'tours.walk.ferry.accept': 'Ambil feri',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'Garis penyeberangan ini terlalu panjang untuk disimpan sebagai satu ruas. Tambahkan perhentian di jalan atau pindahkan salah satunya.',
|
||||
'tours.walk.ferry.show': 'Tampilkan penyeberangan',
|
||||
'tours.walk.ferry.selectStop': 'Pilih perhentian {number}',
|
||||
'tours.walk.ferry.time': '{time} dengan perahu',
|
||||
@@ -781,7 +783,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'Feri',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'Tentang waktu feri',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'Waktu penyeberangan dengan perahu, seperti yang diberikan perute. Dipisahkan dari waktu jalan kaki dan tidak termasuk total yang direncanakan.',
|
||||
'Waktu penyeberangan dengan perahu, seperti yang diberikan perute. Dipisahkan dari waktu jalan kaki, tetapi dihitung dalam total yang direncanakan; tanpanya, total adalah batas bawah.',
|
||||
'tours.walk.ferry.leg': 'Penyeberangan feri',
|
||||
'tours.walk.ferry.legInfo': 'Diseberangi dengan perahu, bukan berjalan. Waktunya tidak termasuk waktu jalan kaki.',
|
||||
'tours.walk.ferry.release': 'Rencanakan jalan kaki lagi',
|
||||
|
||||
@@ -779,6 +779,8 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.accepted':
|
||||
'Traghetto da {from} a {to}, accettato di proposito. Il suo tempo resta separato dal tempo a piedi.',
|
||||
'tours.walk.ferry.accept': 'Accetta traghetto',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'La linea di questa traversata è troppo lunga per essere tenuta come un solo tratto. Aggiungi una tappa lungo il percorso o spostane una.',
|
||||
'tours.walk.ferry.show': 'Mostra traversata',
|
||||
'tours.walk.ferry.selectStop': 'Scegli la tappa {number}',
|
||||
'tours.walk.ferry.time': '{time} in barca',
|
||||
@@ -787,7 +789,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'Traghetto',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'Sul tempo in traghetto',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'Il tempo delle traversate in barca, come lo indica il calcolatore. Resta separato dal tempo a piedi e non è nel totale pianificato.',
|
||||
'Il tempo delle traversate in barca, come lo indica il calcolatore. Resta separato dal tempo a piedi ma conta nel totale pianificato; senza di esso, il totale è un minimo.',
|
||||
'tours.walk.ferry.leg': 'Traversata in traghetto',
|
||||
'tours.walk.ferry.legInfo': 'Attraversato in barca, non a piedi. Il suo tempo non è nel tempo a piedi.',
|
||||
'tours.walk.ferry.release': 'Ripianifica a piedi',
|
||||
|
||||
@@ -750,6 +750,8 @@ const tours: TranslationStrings = {
|
||||
'渡航は歩行時間に数えません。保存するには、フェリーを採用するか、徒歩の道でつながるよう立ち寄り先を動かしてください。',
|
||||
'tours.walk.ferry.accepted': '{from} から {to} へのフェリー、意図して採用済み。その時間は歩行時間とは別です。',
|
||||
'tours.walk.ferry.accept': 'フェリーを採用',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'この渡航の線は長すぎて1つの区間として保存できません。途中に立ち寄り先を追加するか、どれかを動かしてください。',
|
||||
'tours.walk.ferry.show': '渡航を表示',
|
||||
'tours.walk.ferry.selectStop': '立ち寄り先 {number} を選択',
|
||||
'tours.walk.ferry.time': '船で {time}',
|
||||
@@ -758,7 +760,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'フェリー',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'フェリーの時間について',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'船での渡航にかかる時間で、ルート検索が示すものです。歩行時間とは別で、予定合計にも含まれません。',
|
||||
'船での渡航にかかる時間で、ルート検索が示すものです。歩行時間とは別ですが、予定合計には含まれます。不明な場合、合計は最低値です。',
|
||||
'tours.walk.ferry.leg': 'フェリーで渡航',
|
||||
'tours.walk.ferry.legInfo': '歩かずに船で渡ります。その時間は歩行時間に含まれません。',
|
||||
'tours.walk.ferry.release': 'もう一度徒歩で計画',
|
||||
|
||||
@@ -744,6 +744,8 @@ const tours: TranslationStrings = {
|
||||
'횡단은 도보 시간에 포함되지 않습니다. 저장하려면 페리를 채택하거나 도보 길이 이어지도록 정류지를 옮기세요.',
|
||||
'tours.walk.ferry.accepted': '{from}에서 {to}까지의 페리, 의도적으로 채택됨. 그 시간은 도보 시간과 따로 둡니다.',
|
||||
'tours.walk.ferry.accept': '페리 채택',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'이 횡단의 경로가 너무 길어 한 구간으로 저장할 수 없습니다. 중간에 정류지를 추가하거나 하나를 옮기세요.',
|
||||
'tours.walk.ferry.show': '횡단 보기',
|
||||
'tours.walk.ferry.selectStop': '정류지 {number} 선택',
|
||||
'tours.walk.ferry.time': '배로 {time}',
|
||||
@@ -752,7 +754,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': '페리',
|
||||
'tours.walk.ferry.fieldInfoLabel': '페리 시간 안내',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'배로 건너는 데 걸리는 시간으로, 경로 탐색이 알려 준 값입니다. 도보 시간과 따로 두며 계획 총계에도 들어가지 않습니다.',
|
||||
'배로 건너는 데 걸리는 시간으로, 경로 탐색이 알려 준 값입니다. 도보 시간과 따로 두지만 계획 총계에는 들어갑니다. 알 수 없으면 총계는 최소값입니다.',
|
||||
'tours.walk.ferry.leg': '페리 횡단',
|
||||
'tours.walk.ferry.legInfo': '걷지 않고 배로 건넙니다. 그 시간은 도보 시간에 없습니다.',
|
||||
'tours.walk.ferry.release': '다시 도보로 계획',
|
||||
|
||||
@@ -777,6 +777,8 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.accepted':
|
||||
'Veerpont van {from} naar {to}, bewust overgenomen. De tijd ervan staat los van de looptijd.',
|
||||
'tours.walk.ferry.accept': 'Veerpont overnemen',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'De lijn van deze overtocht is te lang om als één stuk te bewaren. Voeg onderweg een halte toe of verplaats er een.',
|
||||
'tours.walk.ferry.show': 'Overtocht tonen',
|
||||
'tours.walk.ferry.selectStop': 'Halte {number} kiezen',
|
||||
'tours.walk.ferry.time': '{time} per boot',
|
||||
@@ -785,7 +787,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'Veerpont',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'Over de veerponttijd',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'De tijd van de overtochten per boot, zoals de routeplanner die geeft. Staat los van de looptijd en zit niet in het geplande totaal.',
|
||||
'De tijd van de overtochten per boot, zoals de routeplanner die geeft. Staat los van de looptijd, maar telt mee in het geplande totaal; zonder die tijd is het totaal een minimum.',
|
||||
'tours.walk.ferry.leg': 'Overtocht met veerpont',
|
||||
'tours.walk.ferry.legInfo': 'Per boot overgestoken, niet gelopen. De tijd zit niet in de looptijd.',
|
||||
'tours.walk.ferry.release': 'Opnieuw te voet plannen',
|
||||
|
||||
@@ -781,6 +781,8 @@ const tours: TranslationStrings = {
|
||||
'Przeprawa nie liczy się jako czas marszu. Aby zapisać, przyjmij prom albo przesuń przystanek, żeby łączyła je droga piesza.',
|
||||
'tours.walk.ferry.accepted': 'Prom z {from} do {to}, przyjęty celowo. Jego czas jest oddzielony od czasu marszu.',
|
||||
'tours.walk.ferry.accept': 'Przyjmij prom',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'Linia tej przeprawy jest zbyt długa, by zachować ją jako jeden odcinek. Dodaj przystanek po drodze lub przesuń któryś.',
|
||||
'tours.walk.ferry.show': 'Pokaż przeprawę',
|
||||
'tours.walk.ferry.selectStop': 'Wybierz przystanek {number}',
|
||||
'tours.walk.ferry.time': '{time} łodzią',
|
||||
@@ -789,7 +791,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'Prom',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'O czasie promu',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'Czas przepraw łodzią, tak jak podaje go wyznaczanie trasy. Jest oddzielony od czasu marszu i nie wchodzi do planowanej sumy.',
|
||||
'Czas przepraw łodzią, tak jak podaje go wyznaczanie trasy. Jest oddzielony od czasu marszu, ale wlicza się do planowanej sumy; bez niego suma jest wartością minimalną.',
|
||||
'tours.walk.ferry.leg': 'Przeprawa promem',
|
||||
'tours.walk.ferry.legInfo': 'Przepłynięte łodzią, nie przebyte pieszo. Jego czas nie jest w czasie marszu.',
|
||||
'tours.walk.ferry.release': 'Zaplanuj znów pieszo',
|
||||
|
||||
@@ -783,6 +783,8 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.accepted':
|
||||
'Паром от {from} до {to}, принят намеренно. Его время учитывается отдельно от времени ходьбы.',
|
||||
'tours.walk.ferry.accept': 'Принять паром',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'Линия этой переправы слишком длинная, чтобы сохранить её одним участком. Добавьте остановку по пути или переместите одну.',
|
||||
'tours.walk.ferry.show': 'Показать переправу',
|
||||
'tours.walk.ferry.selectStop': 'Выбрать остановку {number}',
|
||||
'tours.walk.ferry.time': '{time} на лодке',
|
||||
@@ -791,7 +793,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'Паром',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'О времени на пароме',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'Время переправ на лодке, как его даёт маршрутизатор. Учитывается отдельно от времени ходьбы и не входит в плановый итог.',
|
||||
'Время переправ на лодке, как его даёт маршрутизатор. Учитывается отдельно от времени ходьбы, но входит в плановый итог; без него итог является минимальным.',
|
||||
'tours.walk.ferry.leg': 'Переправа на пароме',
|
||||
'tours.walk.ferry.legInfo': 'Пересечено на лодке, не пешком. Его время не входит во время ходьбы.',
|
||||
'tours.walk.ferry.release': 'Снова спланировать пешком',
|
||||
|
||||
@@ -761,6 +761,8 @@ const tours: TranslationStrings = {
|
||||
'Prevoz sa nepočíta do času chôdze. Na uloženie prevezmi trajekt alebo presuň zastávku, aby ich spojila pešia cesta.',
|
||||
'tours.walk.ferry.accepted': 'Trajekt z {from} do {to}, prevzatý zámerne. Jeho čas je oddelený od času chôdze.',
|
||||
'tours.walk.ferry.accept': 'Prevziať trajekt',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'Trasa tohto prevozu je príliš dlhá na to, aby sa uložila ako jeden úsek. Pridaj zastávku po ceste alebo jednu presuň.',
|
||||
'tours.walk.ferry.show': 'Ukázať prevoz',
|
||||
'tours.walk.ferry.selectStop': 'Vybrať zastávku {number}',
|
||||
'tours.walk.ferry.time': '{time} loďou',
|
||||
@@ -769,7 +771,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'Trajekt',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'O čase trajektu',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'Čas prevozov loďou, ako ho uvádza plánovač. Je oddelený od času chôdze a nie je v plánovanom súčte.',
|
||||
'Čas prevozov loďou, ako ho uvádza plánovač. Je oddelený od času chôdze, ale započítava sa do plánovaného súčtu; bez neho je súčet len dolná hranica.',
|
||||
'tours.walk.ferry.leg': 'Prevoz trajektom',
|
||||
'tours.walk.ferry.legInfo': 'Preplávané loďou, nie prejdené. Jeho čas nie je v čase chôdze.',
|
||||
'tours.walk.ferry.release': 'Znova naplánovať pešo',
|
||||
|
||||
@@ -759,6 +759,8 @@ const tours: TranslationStrings = {
|
||||
'Överfarten räknas inte som gångtid. För att spara, ta färjan eller flytta ett stopp så att en gångväg förbinder dem.',
|
||||
'tours.walk.ferry.accepted': 'Färja från {from} till {to}, tagen med avsikt. Dess tid hålls skild från gångtiden.',
|
||||
'tours.walk.ferry.accept': 'Ta färjan',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'Linjen för den här överfarten är för lång för att sparas som en sträcka. Lägg till ett stopp på vägen eller flytta ett.',
|
||||
'tours.walk.ferry.show': 'Visa överfarten',
|
||||
'tours.walk.ferry.selectStop': 'Välj stopp {number}',
|
||||
'tours.walk.ferry.time': '{time} med båt',
|
||||
@@ -767,7 +769,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'Färja',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'Om färjetiden',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'Tiden som överfarterna med båt tar, som ruttplaneraren anger den. Den hålls skild från gångtiden och ingår inte i den planerade summan.',
|
||||
'Tiden som överfarterna med båt tar, som ruttplaneraren anger den. Den hålls skild från gångtiden men räknas in i den planerade summan; utan den är summan ett minimum.',
|
||||
'tours.walk.ferry.leg': 'Överfart med färja',
|
||||
'tours.walk.ferry.legInfo': 'Korsat med båt, inte gånget. Tiden ingår inte i gångtiden.',
|
||||
'tours.walk.ferry.release': 'Planera till fots igen',
|
||||
|
||||
@@ -732,6 +732,8 @@ const tours: TranslationStrings = {
|
||||
'การข้ามฟากไม่นับเป็นเวลาเดิน หากจะบันทึก ให้รับเรือข้ามฟากนี้ หรือย้ายจุดแวะให้มีทางเดินเท้าเชื่อมกัน',
|
||||
'tours.walk.ferry.accepted': 'เรือข้ามฟากจาก {from} ไป {to} รับไว้โดยตั้งใจ เวลาของเรือแยกจากเวลาเดิน',
|
||||
'tours.walk.ferry.accept': 'รับเรือข้ามฟาก',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'เส้นทางข้ามฟากนี้ยาวเกินกว่าจะเก็บเป็นช่วงเดียว เพิ่มจุดแวะระหว่างทางหรือย้ายจุดหนึ่ง',
|
||||
'tours.walk.ferry.show': 'แสดงการข้ามฟาก',
|
||||
'tours.walk.ferry.selectStop': 'เลือกจุดแวะ {number}',
|
||||
'tours.walk.ferry.time': 'ทางเรือ {time}',
|
||||
@@ -740,7 +742,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'เรือข้ามฟาก',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'เกี่ยวกับเวลาเรือข้ามฟาก',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'เวลาที่ใช้ข้ามฟากทางเรือตามที่ตัวหาเส้นทางให้ไว้ แยกจากเวลาเดินและไม่รวมในเวลารวมที่วางแผน',
|
||||
'เวลาที่ใช้ข้ามฟากทางเรือตามที่ตัวหาเส้นทางให้ไว้ แยกจากเวลาเดินแต่รวมอยู่ในเวลารวมที่วางแผน หากไม่ทราบเวลา เวลารวมจะเป็นค่าต่ำสุด',
|
||||
'tours.walk.ferry.leg': 'ข้ามฟากด้วยเรือ',
|
||||
'tours.walk.ferry.legInfo': 'ข้ามด้วยเรือ ไม่ได้เดิน เวลาของมันไม่รวมในเวลาเดิน',
|
||||
'tours.walk.ferry.release': 'วางแผนเดินเท้าอีกครั้ง',
|
||||
|
||||
@@ -20,7 +20,7 @@ const toursModules = import.meta.glob<{ default: TranslationStrings }>('./*/tour
|
||||
const TOUR_DOMAINS: { file: string; generalKeyCount: number; modules: DomainModules }[] = [
|
||||
{
|
||||
file: 'tours',
|
||||
generalKeyCount: 1335,
|
||||
generalKeyCount: 1336,
|
||||
modules: toursModules,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -763,6 +763,8 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.accepted':
|
||||
'{from} noktasından {to} noktasına feribot, bilerek kabul edildi. Süresi yürüyüş süresinden ayrı tutulur.',
|
||||
'tours.walk.ferry.accept': 'Feribotu kabul et',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'Bu geçişin çizgisi tek bir bölüm olarak saklanamayacak kadar uzun. Yol üzerine bir durak ekle veya birini taşı.',
|
||||
'tours.walk.ferry.show': 'Geçişi göster',
|
||||
'tours.walk.ferry.selectStop': '{number}. durağı seç',
|
||||
'tours.walk.ferry.time': 'Tekneyle {time}',
|
||||
@@ -771,7 +773,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'Feribot',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'Feribot süresi hakkında',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'Tekneyle geçişlerin süresi, yönlendiricinin verdiği gibi. Yürüyüş süresinden ayrı tutulur ve planlanan toplamda yer almaz.',
|
||||
'Tekneyle geçişlerin süresi, yönlendiricinin verdiği gibi. Yürüyüş süresinden ayrı tutulur ama planlanan toplama dahildir; o olmadan toplam bir alt sınırdır.',
|
||||
'tours.walk.ferry.leg': 'Feribotla geçiş',
|
||||
'tours.walk.ferry.legInfo': 'Yürünmedi, tekneyle geçildi. Süresi yürüyüş süresinde yok.',
|
||||
'tours.walk.ferry.release': 'Yeniden yürüyerek planla',
|
||||
|
||||
@@ -777,6 +777,8 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.accepted':
|
||||
'Пором від {from} до {to}, прийнятий навмисно. Його час рахується окремо від часу ходьби.',
|
||||
'tours.walk.ferry.accept': 'Прийняти пором',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'Лінія цієї переправи задовга, щоб зберегти її одним відрізком. Додайте зупинку дорогою або перемістіть одну.',
|
||||
'tours.walk.ferry.show': 'Показати переправу',
|
||||
'tours.walk.ferry.selectStop': 'Вибрати зупинку {number}',
|
||||
'tours.walk.ferry.time': '{time} човном',
|
||||
@@ -785,7 +787,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'Пором',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'Про час на поромі',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'Час переправ човном, як його дає маршрутизатор. Рахується окремо від часу ходьби і не входить до планового підсумку.',
|
||||
'Час переправ човном, як його дає маршрутизатор. Рахується окремо від часу ходьби, але входить до планового підсумку; без нього підсумок є мінімальним.',
|
||||
'tours.walk.ferry.leg': 'Переправа поромом',
|
||||
'tours.walk.ferry.legInfo': 'Перетнуто човном, не пішки. Його час не входить у час ходьби.',
|
||||
'tours.walk.ferry.release': 'Знову спланувати пішки',
|
||||
|
||||
@@ -761,6 +761,8 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.accepted':
|
||||
'Phà từ {from} đến {to}, đã nhận có chủ ý. Thời gian của nó được tách khỏi thời gian đi bộ.',
|
||||
'tours.walk.ferry.accept': 'Nhận phà',
|
||||
'tours.walk.ferry.acceptTooLong':
|
||||
'Đường của chuyến qua này quá dài để giữ thành một chặng. Hãy thêm một điểm dừng trên đường hoặc di chuyển một điểm.',
|
||||
'tours.walk.ferry.show': 'Hiện chuyến qua',
|
||||
'tours.walk.ferry.selectStop': 'Chọn điểm dừng {number}',
|
||||
'tours.walk.ferry.time': '{time} bằng thuyền',
|
||||
@@ -769,7 +771,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.field': 'Phà',
|
||||
'tours.walk.ferry.fieldInfoLabel': 'Về thời gian đi phà',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'Thời gian các chuyến qua bằng thuyền, như bộ tìm đường đưa ra. Được tách khỏi thời gian đi bộ và không nằm trong tổng đã lập.',
|
||||
'Thời gian các chuyến qua bằng thuyền, như bộ tìm đường đưa ra. Được tách khỏi thời gian đi bộ nhưng vẫn tính vào tổng đã lập; nếu thiếu, tổng chỉ là mức tối thiểu.',
|
||||
'tours.walk.ferry.leg': 'Qua bằng phà',
|
||||
'tours.walk.ferry.legInfo': 'Qua bằng thuyền, không đi bộ. Thời gian không nằm trong thời gian đi bộ.',
|
||||
'tours.walk.ferry.release': 'Lập lại theo đi bộ',
|
||||
|
||||
@@ -706,6 +706,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.pendingHint': '渡船不計入步行時間。要儲存,請採用渡輪,或移動一個站點,讓步行道路連通它們。',
|
||||
'tours.walk.ferry.accepted': '從 {from} 到 {to} 的渡輪,已有意採用。其時間與步行時間分開。',
|
||||
'tours.walk.ferry.accept': '採用渡輪',
|
||||
'tours.walk.ferry.acceptTooLong': '這段渡船的路線太長,無法作為一段保存。請在途中新增一個站點,或移動一個站點。',
|
||||
'tours.walk.ferry.show': '顯示渡船',
|
||||
'tours.walk.ferry.selectStop': '選擇站點 {number}',
|
||||
'tours.walk.ferry.time': '搭船 {time}',
|
||||
@@ -713,7 +714,8 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.timeHint': '為路線規劃給出的渡船時間。不屬於步行時間。',
|
||||
'tours.walk.ferry.field': '渡輪',
|
||||
'tours.walk.ferry.fieldInfoLabel': '關於渡輪時間',
|
||||
'tours.walk.ferry.fieldInfo': '搭船過水所需的時間,由路線規劃給出。與步行時間分開,也不計入計畫總時長。',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'搭船過水所需的時間,由路線規劃給出。與步行時間分開,但計入計畫總時長;時間未知時,總時長為最少值。',
|
||||
'tours.walk.ferry.leg': '渡輪過水',
|
||||
'tours.walk.ferry.legInfo': '搭船而過,並非步行。其時間不計入步行時間。',
|
||||
'tours.walk.ferry.release': '重新按步行規劃',
|
||||
|
||||
@@ -707,6 +707,7 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.pendingHint': '渡船不计入步行时间。要保存,请采用渡轮,或移动一个站点,让步行道路连通它们。',
|
||||
'tours.walk.ferry.accepted': '从 {from} 到 {to} 的渡轮,已有意采用。其时间与步行时间分开。',
|
||||
'tours.walk.ferry.accept': '采用渡轮',
|
||||
'tours.walk.ferry.acceptTooLong': '这段渡船的线路太长,无法作为一段保存。请在途中添加一个站点,或移动一个站点。',
|
||||
'tours.walk.ferry.show': '显示渡船',
|
||||
'tours.walk.ferry.selectStop': '选择站点 {number}',
|
||||
'tours.walk.ferry.time': '乘船 {time}',
|
||||
@@ -714,7 +715,8 @@ const tours: TranslationStrings = {
|
||||
'tours.walk.ferry.timeHint': '为路线规划给出的渡船时间。不属于步行时间。',
|
||||
'tours.walk.ferry.field': '渡轮',
|
||||
'tours.walk.ferry.fieldInfoLabel': '关于渡轮时间',
|
||||
'tours.walk.ferry.fieldInfo': '乘船过水所需的时间,由路线规划给出。与步行时间分开,也不计入计划总时长。',
|
||||
'tours.walk.ferry.fieldInfo':
|
||||
'乘船过水所需的时间,由路线规划给出。与步行时间分开,但计入计划总时长;时间未知时,总时长为最少值。',
|
||||
'tours.walk.ferry.leg': '渡轮过水',
|
||||
'tours.walk.ferry.legInfo': '乘船而过,并非步行。其时间不计入步行时间。',
|
||||
'tours.walk.ferry.release': '重新按步行规划',
|
||||
|
||||
@@ -60,6 +60,31 @@ describe('walkStationFacts (CW-02, CW-03)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('sums the minutes its ferry legs take by boat apart, unknown while one has no time (CW-12)', () => {
|
||||
const ferry = (minutes: number | null) => ({
|
||||
kind: 'ferry' as const,
|
||||
geometry: [
|
||||
[48.1, 11.5],
|
||||
[48.105, 11.505],
|
||||
[48.11, 11.51],
|
||||
] as [number, number][],
|
||||
crossings: [[0, 1]] as [number, number][],
|
||||
minutes,
|
||||
walk_minutes: 3,
|
||||
});
|
||||
expect(
|
||||
walkStationFacts('walk', [{ ...cathedral, fixed_leg: ferry(12) }, { ...market, fixed_leg: ferry(5) }, park]),
|
||||
).toMatchObject({
|
||||
walk_ferry_minutes: 17,
|
||||
});
|
||||
expect(
|
||||
walkStationFacts('walk', [{ ...cathedral, fixed_leg: ferry(12) }, { ...market, fixed_leg: ferry(null) }, park]),
|
||||
).toMatchObject({
|
||||
walk_ferry_minutes: null,
|
||||
});
|
||||
expect(walkStationFacts('walk', [cathedral, market])).not.toHaveProperty('walk_ferry_minutes');
|
||||
});
|
||||
|
||||
it('says nothing of the stations of any other type', () => {
|
||||
expect(walkStationFacts('hike', [cathedral, { ...market, stay_minutes: 30 }])).toEqual({
|
||||
station_count: null,
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import type { TourFixedLeg } from './tours.schema';
|
||||
import { walkFerryMinutesOf } from './walk-ferry';
|
||||
|
||||
/** Closer than this, in degrees, two points of a tour stand on the same spot (about a centimetre). */
|
||||
const SAME_SPOT_DEG = 1e-7;
|
||||
|
||||
@@ -32,11 +35,16 @@ export function walkStationsOf<T extends Spot & { shaping?: boolean | null }>(po
|
||||
return route.filter((point) => !point.shaping);
|
||||
}
|
||||
|
||||
/** What a list says of a city walk's stations: how many, their stays as far as entered, and how many have none. */
|
||||
/**
|
||||
* What a list says of a city walk's stations: how many, their stays as far as
|
||||
* entered, and how many have none; with the minutes of its ferry legs by boat
|
||||
* where it takes any (CW-12).
|
||||
*/
|
||||
interface WalkStationFacts {
|
||||
station_count: number | null;
|
||||
station_stay_minutes: number | null;
|
||||
station_stays_unknown: number | null;
|
||||
walk_ferry_minutes?: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -48,13 +56,19 @@ interface WalkStationFacts {
|
||||
*/
|
||||
export function walkStationFacts(
|
||||
tourType: string,
|
||||
points: readonly (Spot & { shaping?: boolean | null; stay_minutes?: number | null })[],
|
||||
points: readonly (Spot & {
|
||||
shaping?: boolean | null;
|
||||
stay_minutes?: number | null;
|
||||
fixed_leg?: TourFixedLeg | null;
|
||||
})[],
|
||||
): WalkStationFacts {
|
||||
if (tourType !== 'walk') return { station_count: null, station_stay_minutes: null, station_stays_unknown: null };
|
||||
const stations = walkStationsOf(points);
|
||||
const ferryMinutes = walkFerryMinutesOf(points);
|
||||
return {
|
||||
station_count: stations.length,
|
||||
station_stay_minutes: stations.reduce((sum, station) => sum + (station.stay_minutes ?? 0), 0),
|
||||
station_stays_unknown: stations.filter((station) => station.stay_minutes == null).length,
|
||||
...(ferryMinutes !== undefined ? { walk_ferry_minutes: ferryMinutes } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -203,7 +203,7 @@ describe('Tours fixed legs', () => {
|
||||
});
|
||||
|
||||
describe('Tours ferry legs (CW-12)', () => {
|
||||
const ferry = (crossing: [number, number], minutes: number | null = 7) => ({
|
||||
const ferry = (crossings: Array<[number, number]>, minutes: number | null = 7) => ({
|
||||
kind: 'ferry' as const,
|
||||
geometry: [
|
||||
[48, 11],
|
||||
@@ -211,7 +211,7 @@ describe('Tours ferry legs (CW-12)', () => {
|
||||
[48.006, 11.012],
|
||||
[48.01, 11.02],
|
||||
] as [number, number][],
|
||||
crossing,
|
||||
crossings,
|
||||
minutes,
|
||||
walk_minutes: 2,
|
||||
});
|
||||
@@ -226,20 +226,34 @@ describe('Tours ferry legs (CW-12)', () => {
|
||||
});
|
||||
|
||||
it('takes a crossing by boat on a city walk, with where on its leg the boat runs and its minutes apart', () => {
|
||||
expect(tourCreateRequestSchema.parse(withLeg(ferry([1, 2]), 'walk')).waypoints[0]?.fixed_leg).toEqual(
|
||||
ferry([1, 2]),
|
||||
expect(tourCreateRequestSchema.parse(withLeg(ferry([[1, 2]]), 'walk')).waypoints[0]?.fixed_leg).toEqual(
|
||||
ferry([[1, 2]]),
|
||||
);
|
||||
expect(tourCreateRequestSchema.parse(withLeg(ferry([1, 2], null), 'walk')).waypoints[0]?.fixed_leg).toMatchObject({
|
||||
minutes: null,
|
||||
});
|
||||
expect(tourCreateRequestSchema.parse(withLeg(ferry([[1, 2]], null), 'walk')).waypoints[0]?.fixed_leg).toMatchObject(
|
||||
{
|
||||
minutes: null,
|
||||
},
|
||||
);
|
||||
// Two boats on one leg with a walk between them: each stretch is kept on its own.
|
||||
const twice = ferry([
|
||||
[0, 1],
|
||||
[2, 3],
|
||||
]);
|
||||
expect(tourCreateRequestSchema.parse(withLeg(twice, 'walk')).waypoints[0]?.fixed_leg).toEqual(twice);
|
||||
});
|
||||
|
||||
it('refuses a crossing on any other type, or one that does not run forwards between two points of its leg', () => {
|
||||
expect(() => tourCreateRequestSchema.parse(withLeg(ferry([1, 2]), 'hike'))).toThrow(
|
||||
expect(() => tourCreateRequestSchema.parse(withLeg(ferry([[1, 2]]), 'hike'))).toThrow(
|
||||
/ferry leg belongs to a city walk/,
|
||||
);
|
||||
expect(() => tourCreateRequestSchema.parse(withLeg(ferry([2, 1]), 'walk'))).toThrow(/crossing runs between/);
|
||||
expect(() => tourCreateRequestSchema.parse(withLeg(ferry([1, 4]), 'walk'))).toThrow(/crossing runs between/);
|
||||
expect(() => tourCreateRequestSchema.parse(withLeg(ferry([[2, 1]]), 'walk'))).toThrow(/crossing runs between/);
|
||||
expect(() => tourCreateRequestSchema.parse(withLeg(ferry([[1, 4]]), 'walk'))).toThrow(/crossing runs between/);
|
||||
const overlapping = ferry([
|
||||
[0, 2],
|
||||
[1, 3],
|
||||
]);
|
||||
expect(() => tourCreateRequestSchema.parse(withLeg(overlapping, 'walk'))).toThrow(/crossing runs between/);
|
||||
expect(() => tourCreateRequestSchema.parse(withLeg(ferry([]), 'walk'))).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -307,6 +307,12 @@ export const tourListItemSchema = tourSchema.extend({
|
||||
station_stay_minutes: z.number().int().nonnegative().nullable().optional(),
|
||||
/** CW-02: how many of a city walk's stations have no stay entered yet; null for any other type. */
|
||||
station_stays_unknown: z.number().int().nonnegative().nullable().optional(),
|
||||
/**
|
||||
* CW-12: the minutes a city walk's ferry legs take by boat, never part of
|
||||
* its walking time; null while the router gave one of them no time, absent
|
||||
* for a walk without any.
|
||||
*/
|
||||
walk_ferry_minutes: z.number().int().nonnegative().nullable().optional(),
|
||||
/**
|
||||
* CW-11: a tour saved with its points only, its way not planned yet (a city
|
||||
* walk an assistant created). The planner plans the way when the tour is
|
||||
@@ -368,6 +374,8 @@ export const TOUR_WRITE_MAX_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
/** The longest a ferry leg's crossing or its walk may take, a whole day. */
|
||||
const FERRY_LEG_MAX_MINUTES = 24 * 60;
|
||||
/** The most stretches by boat one ferry leg keeps; a leg between two stations rarely boards more than twice. */
|
||||
const FERRY_LEG_MAX_CROSSINGS = 20;
|
||||
|
||||
const fixedLegGeometrySchema = z
|
||||
.array(z.tuple([z.number().finite().min(-90).max(90), z.number().finite().min(-180).max(180)]))
|
||||
@@ -425,9 +433,15 @@ export const tourFixedLegSchema = z.discriminatedUnion('kind', [
|
||||
z.object({
|
||||
kind: z.literal('ferry'),
|
||||
geometry: fixedLegGeometrySchema,
|
||||
/** The points of the line the boat leaves from and lands at, by their index. */
|
||||
crossing: z.tuple([z.number().int().nonnegative(), z.number().int().nonnegative()]),
|
||||
/** The crossing's time as the router gave it; null when it gave none. */
|
||||
/**
|
||||
* Each stretch of the line by boat, as the indices of the points the boat
|
||||
* leaves from and lands at, in order; the walk between two of them stays walking.
|
||||
*/
|
||||
crossings: z
|
||||
.array(z.tuple([z.number().int().nonnegative(), z.number().int().nonnegative()]))
|
||||
.min(1)
|
||||
.max(FERRY_LEG_MAX_CROSSINGS),
|
||||
/** The time of all its crossings as the router gave it; null when it gave none for one of them. */
|
||||
minutes: z.number().int().min(0).max(FERRY_LEG_MAX_MINUTES).nullable(),
|
||||
/** The walk to the boat and on from it along this leg, by the router. */
|
||||
walk_minutes: z.number().int().min(0).max(FERRY_LEG_MAX_MINUTES),
|
||||
@@ -605,11 +619,12 @@ export const tourCreateRequestSchema = z
|
||||
message: `Waypoint ${index}'s fixed leg must run from it to the next waypoint`,
|
||||
});
|
||||
}
|
||||
if (leg.kind === 'ferry' && !(leg.crossing[0] < leg.crossing[1] && leg.crossing[1] < leg.geometry.length)) {
|
||||
if (leg.kind === 'ferry' && !crossingsInOrder(leg.crossings, leg.geometry.length)) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['waypoints', index, 'fixed_leg', 'crossing'],
|
||||
message: 'a crossing runs between two points of its leg, the first before the second',
|
||||
path: ['waypoints', index, 'fixed_leg', 'crossings'],
|
||||
message:
|
||||
'a crossing runs between two points of its leg, the first before the second, after the one before it',
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -635,6 +650,16 @@ export type TourCreateInput = z.input<typeof tourCreateRequestSchema>;
|
||||
|
||||
type Issue = { path: Array<string | number>; message: string };
|
||||
|
||||
function crossingsInOrder(crossings: ReadonlyArray<readonly unknown[]>, points: number): boolean {
|
||||
let after = 0;
|
||||
for (const crossing of crossings) {
|
||||
const [from, to] = [Number(crossing[0]), Number(crossing[1])];
|
||||
if (!(from >= after && from < to && to < points)) return false;
|
||||
after = to;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** How a refusal names each type. */
|
||||
const TYPE_NAMED: Record<PlannableTourType, string> = {
|
||||
kayak: 'a paddle tour',
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { boatSpansOf, ferryCrossingsOf } from './walk-ferry';
|
||||
import { stationShares } from './walk-hours';
|
||||
import { boatSpansOf, boatsAlong, ferryCrossingsOf, ferryLegsOf, walkFerryMinutesOf } from './walk-ferry';
|
||||
import { stationArrivals, stationShares } from './walk-hours';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
@@ -27,7 +27,7 @@ describe('ferry legs of a city walk (CW-12)', () => {
|
||||
fixed_leg: {
|
||||
kind: 'ferry',
|
||||
geometry: line.map(([lat, lng]): [number, number] => [lat, lng]),
|
||||
crossing: [1, 2],
|
||||
crossings: [[1, 2]],
|
||||
minutes: 7,
|
||||
walk_minutes: 2,
|
||||
},
|
||||
@@ -58,6 +58,50 @@ describe('ferry legs of a city walk (CW-12)', () => {
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps two stretches by boat of one leg apart, the walk between them walking', () => {
|
||||
const points = [
|
||||
{
|
||||
fixed_leg: {
|
||||
kind: 'ferry' as const,
|
||||
geometry: line.map(([lat, lng]): [number, number] => [lat, lng]),
|
||||
crossings: [
|
||||
[0, 1],
|
||||
[2, 3],
|
||||
] as [number, number][],
|
||||
minutes: 9,
|
||||
walk_minutes: 2,
|
||||
},
|
||||
},
|
||||
];
|
||||
expect(ferryCrossingsOf(points)).toHaveLength(2);
|
||||
expect(ferryLegsOf(points)[0]?.minutes).toBe(9);
|
||||
expect(walkFerryMinutesOf(points)).toBe(9);
|
||||
expect(walkFerryMinutesOf([{}])).toBeUndefined();
|
||||
expect(boatsAlong(line, ferryLegsOf(points))).toEqual({
|
||||
spans: [
|
||||
[0, 1],
|
||||
[2, 3],
|
||||
],
|
||||
landings: [{ at: 3, minutes: 9 }],
|
||||
});
|
||||
});
|
||||
|
||||
it('reaches a stop after the boat lands that many minutes later, and only as a lower bound without its time', () => {
|
||||
const stops = [
|
||||
{ lat: 45.4296, lng: 12.3264, stayMinutes: 0 },
|
||||
{ lat: 45.4275, lng: 12.3282, stayMinutes: 0 },
|
||||
{ lat: 45.4268, lng: 12.33, stayMinutes: 0 },
|
||||
];
|
||||
const boats = { spans: [[1, 2]] as Array<[number, number]>, landings: [{ at: 2, minutes: 12 }] };
|
||||
const walked = stationArrivals(stops, line, 600, 20, { ...boats, landings: [] }) ?? [];
|
||||
const crossed = stationArrivals(stops, line, 600, 20, boats) ?? [];
|
||||
expect(crossed[0]).toEqual(walked[0]);
|
||||
expect(crossed[1]?.arrival).toBe((walked[1]?.arrival ?? 0) + 12);
|
||||
expect(crossed[2]?.arrival).toBe((walked[2]?.arrival ?? 0) + 12);
|
||||
const unknown = stationArrivals(stops, line, 600, 20, { ...boats, landings: [{ at: 2, minutes: null }] }) ?? [];
|
||||
expect(unknown.map((arrival) => arrival.atLeast)).toEqual([false, true, true]);
|
||||
});
|
||||
|
||||
it('counts no distance along a stretch crossed by boat when sharing a walk out', () => {
|
||||
const stops = [
|
||||
{ lat: 45.4296, lng: 12.3264 },
|
||||
|
||||
@@ -1,19 +1,50 @@
|
||||
import type { TourFixedLeg } from './tours.schema';
|
||||
import type { WalkBoats } from './walk-hours';
|
||||
|
||||
type LinePoint = readonly [number, number, ...number[]];
|
||||
type FerryLeg = Extract<TourFixedLeg, { kind: 'ferry' }>;
|
||||
|
||||
/** Closer than this, in degrees, a point of the saved line is the point of a leg it was built from. */
|
||||
const SAME_POINT_DEG = 1e-6;
|
||||
|
||||
/** CW-12: the boat part of each ferry leg of a city walk, in the order of the legs. */
|
||||
/** CW-12: a ferry leg of a city walk as its times read it: the boat parts of its line in order, and their minutes. */
|
||||
export interface WalkFerryLeg {
|
||||
crossings: Array<Array<[number, number]>>;
|
||||
/** Null where the router gave the boat no time. */
|
||||
minutes: number | null;
|
||||
}
|
||||
|
||||
function crossingLines(leg: FerryLeg): Array<Array<[number, number]>> {
|
||||
return leg.crossings.map(([from, to]) =>
|
||||
leg.geometry.slice(from, to + 1).map(([lat, lng]): [number, number] => [lat, lng]),
|
||||
);
|
||||
}
|
||||
|
||||
/** CW-12: the ferry legs of a city walk, in the order of its legs. */
|
||||
export function ferryLegsOf(points: ReadonlyArray<{ fixed_leg?: TourFixedLeg | null }>): WalkFerryLeg[] {
|
||||
return points.flatMap((point) => {
|
||||
const leg = point.fixed_leg;
|
||||
return leg?.kind === 'ferry' ? [{ crossings: crossingLines(leg), minutes: leg.minutes }] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/** CW-12: the boat part of each ferry leg of a city walk, each stretch by boat on its own, in the order of the legs. */
|
||||
export function ferryCrossingsOf(
|
||||
points: ReadonlyArray<{ fixed_leg?: TourFixedLeg | null }>,
|
||||
): Array<Array<[number, number]>> {
|
||||
return points.flatMap((point) => {
|
||||
const leg = point.fixed_leg;
|
||||
if (leg?.kind !== 'ferry') return [];
|
||||
return [leg.geometry.slice(leg.crossing[0], leg.crossing[1] + 1).map(([lat, lng]): [number, number] => [lat, lng])];
|
||||
});
|
||||
return ferryLegsOf(points).flatMap((leg) => leg.crossings);
|
||||
}
|
||||
|
||||
/**
|
||||
* CW-12: the minutes a city walk spends on the boat: the sum over its ferry
|
||||
* legs, null while one of them has no time, undefined for a walk without any.
|
||||
*/
|
||||
export function walkFerryMinutesOf(
|
||||
points: ReadonlyArray<{ fixed_leg?: TourFixedLeg | null }>,
|
||||
): number | null | undefined {
|
||||
const legs = ferryLegsOf(points);
|
||||
if (legs.length === 0) return undefined;
|
||||
return legs.every((leg) => leg.minutes !== null) ? legs.reduce((sum, leg) => sum + (leg.minutes ?? 0), 0) : null;
|
||||
}
|
||||
|
||||
function indexOfPoint(line: ReadonlyArray<LinePoint>, point: readonly [number, number], from: number): number {
|
||||
@@ -24,6 +55,20 @@ function indexOfPoint(line: ReadonlyArray<LinePoint>, point: readonly [number, n
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** One crossing's span on the line, searched from `from` on; null where its points are not found in turn. */
|
||||
function spanOf(
|
||||
line: ReadonlyArray<LinePoint>,
|
||||
crossing: ReadonlyArray<readonly [number, number]>,
|
||||
from: number,
|
||||
): [number, number] | null {
|
||||
const first = crossing[0];
|
||||
const last = crossing[crossing.length - 1];
|
||||
if (!first || !last || crossing.length < 2) return null;
|
||||
const start = indexOfPoint(line, first, from);
|
||||
const end = start < 0 ? -1 : indexOfPoint(line, last, start + 1);
|
||||
return end < 0 ? null : [start, end];
|
||||
}
|
||||
|
||||
/**
|
||||
* Where on a walk's saved line its crossings by boat run, as the indices of the
|
||||
* points the boat leaves from and lands at. The line was put together from the
|
||||
@@ -34,17 +79,36 @@ export function boatSpansOf(
|
||||
line: ReadonlyArray<LinePoint>,
|
||||
crossings: ReadonlyArray<ReadonlyArray<readonly [number, number]>>,
|
||||
): Array<[number, number]> {
|
||||
const spans: Array<[number, number]> = [];
|
||||
let from = 0;
|
||||
for (const crossing of crossings) {
|
||||
const first = crossing[0];
|
||||
const last = crossing[crossing.length - 1];
|
||||
if (!first || !last || crossing.length < 2) continue;
|
||||
const start = indexOfPoint(line, first, from);
|
||||
const end = start < 0 ? -1 : indexOfPoint(line, last, start + 1);
|
||||
if (end < 0) continue;
|
||||
spans.push([start, end]);
|
||||
from = end;
|
||||
}
|
||||
return spans;
|
||||
return boatsAlong(
|
||||
line,
|
||||
crossings.map((crossing) => ({ crossings: [crossing], minutes: null })),
|
||||
).spans;
|
||||
}
|
||||
|
||||
/**
|
||||
* CW-12: a walk's ferry legs found on its saved line: the spans by boat, and
|
||||
* for each leg the point its last boat lands at with the minutes of its boats,
|
||||
* so a stop after it is reached that much later. A leg none of whose
|
||||
* crossings is found adds no time rather than a guessed one.
|
||||
*/
|
||||
export function boatsAlong(
|
||||
line: ReadonlyArray<LinePoint>,
|
||||
legs: ReadonlyArray<
|
||||
Pick<WalkFerryLeg, 'minutes'> & { crossings: ReadonlyArray<ReadonlyArray<readonly [number, number]>> }
|
||||
>,
|
||||
): WalkBoats {
|
||||
const boats: WalkBoats = { spans: [], landings: [] };
|
||||
let from = 0;
|
||||
for (const leg of legs) {
|
||||
let landed = -1;
|
||||
for (const crossing of leg.crossings) {
|
||||
const span = spanOf(line, crossing, from);
|
||||
if (!span) continue;
|
||||
boats.spans.push(span);
|
||||
landed = span[1];
|
||||
from = span[1];
|
||||
}
|
||||
if (landed >= 0) boats.landings.push({ at: landed, minutes: leg.minutes });
|
||||
}
|
||||
return boats;
|
||||
}
|
||||
|
||||
@@ -322,6 +322,36 @@ function passedAt(stops: readonly WalkStop[], flat: ReadonlyArray<[number, numbe
|
||||
return indices;
|
||||
}
|
||||
|
||||
/**
|
||||
* CW-12: a walk's crossings by boat along its route: the spans the boat runs,
|
||||
* from the index it leaves at to the one it lands at, and for each ferry leg
|
||||
* the index its last boat lands at with the minutes of its boats (null where
|
||||
* the router gave none).
|
||||
*/
|
||||
export interface WalkBoats {
|
||||
spans: Array<[number, number]>;
|
||||
landings: Array<{ at: number; minutes: number | null }>;
|
||||
}
|
||||
|
||||
/** Each stop's share of the walk with the index of the route's point it is passed at. */
|
||||
function walkedAlong(
|
||||
stops: readonly WalkStop[],
|
||||
route: readonly RoutePoint[],
|
||||
boatSpans: ReadonlyArray<readonly [number, number]>,
|
||||
): { shares: number[]; indices: number[] } | null {
|
||||
if (route.length < 2) return null;
|
||||
const flat = flatRoute(route);
|
||||
const byBoat = (i: number) => boatSpans.some(([from, to]) => i > from && i <= to);
|
||||
const along = [0];
|
||||
for (let i = 1; i < flat.length; i += 1) {
|
||||
const step = byBoat(i) ? 0 : Math.sqrt(flatGap(flat[i] ?? [0, 0], flat[i - 1] ?? [0, 0]));
|
||||
along.push((along[i - 1] ?? 0) + step);
|
||||
}
|
||||
const total = along[along.length - 1] || 1;
|
||||
const indices = passedAt(stops, flat, Math.cos((route[0]?.[0] ?? 0) * RAD));
|
||||
return { shares: indices.map((index) => (along[index] ?? 0) / total), indices };
|
||||
}
|
||||
|
||||
/**
|
||||
* How far along the route each stop is passed, from 0 at its start to 1 at its
|
||||
* end, by distance, the stops matched in their order as `passedAt` does. Null
|
||||
@@ -334,39 +364,38 @@ export function stationShares(
|
||||
route: readonly RoutePoint[],
|
||||
boatSpans: ReadonlyArray<readonly [number, number]> = [],
|
||||
): number[] | null {
|
||||
if (route.length < 2) return null;
|
||||
const flat = flatRoute(route);
|
||||
const byBoat = (i: number) => boatSpans.some(([from, to]) => i > from && i <= to);
|
||||
const along = [0];
|
||||
for (let i = 1; i < flat.length; i += 1) {
|
||||
const step = byBoat(i) ? 0 : Math.sqrt(flatGap(flat[i] ?? [0, 0], flat[i - 1] ?? [0, 0]));
|
||||
along.push((along[i - 1] ?? 0) + step);
|
||||
}
|
||||
const total = along[along.length - 1] || 1;
|
||||
const indices = passedAt(stops, flat, Math.cos((route[0]?.[0] ?? 0) * RAD));
|
||||
return indices.map((index) => (along[index] ?? 0) / total);
|
||||
return walkedAlong(stops, route, boatSpans)?.shares ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The estimated arrival at each stop, in minutes after midnight and whole: the
|
||||
* start, the walking time shared out by how far along the route the stop is
|
||||
* passed, and the stays before it. A stay not known counts as nothing and
|
||||
* makes every later arrival a lower bound; a stay of 0 is known. Null when the
|
||||
* start, the walking time or the route is not known.
|
||||
* makes every later arrival a lower bound; a stay of 0 is known. A crossing by
|
||||
* boat (CW-12) takes no share of the walking time; a stop after it lands is
|
||||
* reached its minutes later, a lower bound where the boat's time is not known.
|
||||
* Null when the start, the walking time or the route is not known.
|
||||
*/
|
||||
export function stationArrivals(
|
||||
stops: readonly WalkStop[],
|
||||
route: readonly RoutePoint[],
|
||||
start: number | null,
|
||||
walkingMinutes: number | null,
|
||||
boats: Readonly<WalkBoats> = { spans: [], landings: [] },
|
||||
): WalkArrival[] | null {
|
||||
if (start === null || walkingMinutes === null) return null;
|
||||
const shares = stationShares(stops, route);
|
||||
if (!shares) return null;
|
||||
const walked = walkedAlong(stops, route, boats.spans);
|
||||
if (!walked) return null;
|
||||
let stays = 0;
|
||||
let unknown = false;
|
||||
return stops.map((stop, index) => {
|
||||
const arrival = { arrival: Math.round(start + walkingMinutes * (shares[index] ?? 0) + stays), atLeast: unknown };
|
||||
const at = walked.indices[index] ?? 0;
|
||||
const landed = boats.landings.filter((landing) => landing.at <= at);
|
||||
const boat = landed.reduce((sum, landing) => sum + (landing.minutes ?? 0), 0);
|
||||
const arrival = {
|
||||
arrival: Math.round(start + walkingMinutes * (walked.shares[index] ?? 0) + boat + stays),
|
||||
atLeast: unknown || landed.some((landing) => landing.minutes === null),
|
||||
};
|
||||
if (stop.stayMinutes == null) unknown = true;
|
||||
else stays += stop.stayMinutes;
|
||||
return arrival;
|
||||
|
||||
Reference in New Issue
Block a user