From 8e2a2725f0081f7f126ac80971c5ab44618dac61 Mon Sep 17 00:00:00 2001 From: Maurice Date: Thu, 8 Oct 2026 01:56:32 +0000 Subject: [PATCH] refactor(client): the stop rows move to RoadtripSidebarStopRows and share one badge row ServiceStop, RouteViaStop and Stop leave RoadtripSidebar.tsx for their own module and are imported back by name; effectiveFill goes with them unexported, and the imports only they used leave the sidebar. The badge row under a stop's name was written out twice, once in each stop shape. It is now the local StopBadgeRow, which both render in its place. It returns the same span with nothing around it, so the markup is unchanged, and it reads the fill setting and the vehicle the two shapes used to read themselves. Those are plain store reads, so moving them one component down changes nothing either. The code moves as it was otherwise. The note on the stop kind table now sits at the lookup it describes, the comment on the two settings says where they are read now, and the dashes in the moved comments become colons, commas and full stops; each theme-lint-disable stays on the line of its style. Nothing renders differently. New tests render the rows on their own: a plugin halt with and without its name and stay, the kind picker on a pause and on a numbered stop by click, Enter and Space, the drive findings and the walk from the road on both shapes, including the range and unknown findings the rail never draws, and the fill badge with the traveller's default. --- .../components/Roadtrip/RoadtripSidebar.tsx | 327 +----------------- .../Roadtrip/RoadtripSidebarStopRows.test.tsx | 250 +++++++++++++ .../Roadtrip/RoadtripSidebarStopRows.tsx | 325 +++++++++++++++++ client/tests/helpers/roadtripRail.ts | 28 ++ 4 files changed, 609 insertions(+), 321 deletions(-) create mode 100644 client/src/components/Roadtrip/RoadtripSidebarStopRows.test.tsx create mode 100644 client/src/components/Roadtrip/RoadtripSidebarStopRows.tsx diff --git a/client/src/components/Roadtrip/RoadtripSidebar.tsx b/client/src/components/Roadtrip/RoadtripSidebar.tsx index 57354d1d5..b7d893733 100644 --- a/client/src/components/Roadtrip/RoadtripSidebar.tsx +++ b/client/src/components/Roadtrip/RoadtripSidebar.tsx @@ -1,10 +1,9 @@ -import ChargingInfo from './ChargingInfo' import { useRoadtripSettings } from '../../hooks/useRoadtripSettings' import { useElementSize } from '../../hooks/useElementSize' import React, { useMemo, useState } from 'react' import { - Zap, AlertTriangle, - ParkingSquare, Spline, Ban, + AlertTriangle, + Spline, Ban, } from 'lucide-react' import type { RefuelSearch } from './useRefuelSearch' import type { RefuelCandidate } from './refuelSuggestion' @@ -14,21 +13,17 @@ import { Tooltip } from '../shared/Tooltip' import { useSettingsStore } from '../../store/settingsStore' import { formatDistance } from '../../utils/units' import { formatDate } from '../../utils/formatters' -import { formatDurationShort, isServiceStopType, serviceColor, type ScheduleEntry, type ScheduleWarning, refuelsRange } from './roadtripModel' -import { STOP_KIND_BY_KEY } from './stopKinds' +import { formatDurationShort, isServiceStopType, type ScheduleWarning } from './roadtripModel' import { arrivingReroutable, bookendReading, destinationCount, legReroutable, movableWithin, resumeFoldsIntoBookend } from './roadtripRowModel' import { bookendBooking } from './nightBookend' -import { spurWorthLabelling } from './accessSpur' import StopKindPicker from './StopKindPicker' import StopFillPicker from './StopFillPicker' -import { useVehicleRange } from './useVehicleRange' import { MAX_TRIP_DAYS, type RoadtripStopType } from '@trek/shared' import { isStoredStop, undatedRides } from '@trek/shared/roadtrip' import type { QuietDay, RoadtripDay, RoadtripRoutes, RoadtripStop } from './useRoadtripRoutes' import type { SpillMark } from './nightSpill' import { ARRIVING_DRIVE, openOn, type LegAlternatives, type RailDrive } from './useRouteAlternatives' import { dayColor } from './dayColors' -import type { RouteVia } from '../../types' import { FS } from './typeScale' import EmptyState from '../shared/EmptyState' import AutomaticDayStop from './AutomaticDayStop' @@ -36,12 +31,12 @@ import { missedRide } from './carrierRide' import { dayBookings } from './stopBookings' import type { Reservation } from '../../types' import type { StayDraft } from './RoadtripStayModal' -import { missedLeaveOf, readStay, stayDraftOf } from './stayReading' -import { DAY_BADGE, DISC, RAIL_DASH, RAIL_GRID, STAT_LABEL } from './RoadtripSidebar.constants' -import { Arrival, DriveFindingBadge, FillBadge, LateBadge, NightCheckIn, OffRoadBadge, StayBadge } from './RoadtripSidebarBadges' +import { missedLeaveOf, stayDraftOf } from './stayReading' +import { DAY_BADGE, RAIL_GRID, STAT_LABEL } from './RoadtripSidebar.constants' import { RefuelBand } from './RoadtripSidebarRefuelBand' import { DriveBand, SpillBlock } from './RoadtripSidebarDriveBands' import { BookendStop, BookingChips, RideBlock, TerminalStop, UndatedRides } from './RoadtripSidebarBookingRows' +import { RouteViaStop, ServiceStop, Stop } from './RoadtripSidebarStopRows' interface RoadtripSidebarProps { onFocusPoint?: (lat: number, lng: number) => void @@ -133,29 +128,12 @@ interface RoadtripSidebarProps { canEditBookings?: boolean } -// Icon and name both come from the one stop-kind table now. This file used to keep its -// own copy of each, and its rest_area icon had drifted away from the popup's. - - /** * Below this width the rail stops counting stops: the trip head drops its third figure and * the day headers their count, rather than squeezing every badge onto a line too short. */ const RAIL_NARROW_PX = 330 -/** - * What a stop will actually fill to: its own figure, else the traveller's default. - * - * Null means nothing worth saying — no per-stop figure and a default that fills right up, - * which is what the budget did before any of this existed. An explicit 100 on the stop is - * NOT null: on a trip whose default is 80 %, "this one goes right up" is a decision, and - * hiding it would leave the traveller reading 80 on a stop that fills to 100. - */ -function effectiveFill(own: number | null | undefined, setting: number | undefined): number | null { - if (own !== null && own !== undefined) return own - return setting && setting > 0 && setting < 100 ? setting : null -} - /** The quiet half of a measurement — the unit, and anything after the decimal point. */ function Unit({ children }: { children: React.ReactNode }): React.ReactElement { return {children} @@ -236,299 +214,6 @@ function TripSummary({ routes, narrow }: { routes: RoadtripRoutes; narrow: boole ) } -/** - * A charger, a filling station or a rest stop — a stop that interrupts the drive. - * - * It sits inside the leg with the dashed line running through it, carries no number and - * is left out of every count, because that is the difference between it and the places - * the trip is actually for. Its own icon on one flat disc: three kinds of pause that all - * mean "we are still driving", and the icon is what tells them apart. - */ -function ServiceStop({ stop, entry, late, driveFindings, selected, onSelect, onEditStay, onPickKind, onPickFill }: { - stop: RoadtripStop - entry: ScheduleEntry | undefined - /** How late the drive reaches a time pinned on this pause, or the time it was set to - * be left at: the same findings a numbered stop shows. A fuel or charging halt can - * carry a pinned time like anything else. */ - late: ScheduleWarning[] - /** Findings about the drive that ARRIVES here. A charging halt is a stop like any other - * as far as the tank is concerned, so it carries them the same way a numbered one does. */ - driveFindings?: ScheduleWarning[] - /** Opens the kind picker on the disc. Absent leaves the rail read-only. */ - onPickKind?: (anchor: HTMLElement) => void - /** Opens the panel that sets how full THIS stop fills, hung under the badge. */ - onPickFill?: (anchor: HTMLElement) => void - selected: boolean - onSelect?: () => void - /** Opens the dialog for how long this pause takes. Absent means the rail is read-only. */ - onEditStay?: () => void -}): React.ReactElement { - const { t } = useTranslation() - // Read here rather than threaded down: both stop shapes need the same two, and the - // badge is the only thing in the rail that depends on them. - const fillPercent = useRoadtripSettings(s => s.roadtrip_fill_percent) - const { vehicleKind } = useVehicleRange() - const kind = STOP_KIND_BY_KEY[stop.stopType ?? ''] - const Icon = kind?.Icon ?? ParkingSquare - const label = t(kind?.labelKey ?? 'roadtrip.poi.rest') - return ( -
- - - {onPickKind ? ( - // The same control the other way round: the disc says what this is, and it is - // also where it stops being that. - - { e.stopPropagation(); onPickKind(e.currentTarget as HTMLElement) }} - onKeyDown={e => { - if (e.key !== 'Enter' && e.key !== ' ') return - e.preventDefault() - e.stopPropagation() - onPickKind(e.currentTarget as HTMLElement) - }} - className={`${DISC} cursor-pointer transition-transform hover:scale-110 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2`} - // theme-lint-disable — the road-signage palette in `roadtripModel`, shared - // with the corridor list and the map pin so one kind of stop looks like - // itself wherever it turns up. - style={{ background: serviceColor(stop.stopType), color: '#fff' }} // theme-lint-disable — road-signage palette - > - - - - ) : ( - - - - )} - - - -
- ) -} - -/** - * A halt a routing plugin put on this leg, such as a charge on the way. - * - * Read-only, and that is the point rather than a shortcut. The halt belongs to the - * provider, not to the traveller: it is not a place in the database, it has no number, no - * editable stay and no arrival time. Writing it back would send it out as a waypoint on - * the next run, and the plugin would then plan around its own charging stop. - * - * No clock on purpose. The stay is already inside the leg duration the plugin reported, - * so the arrivals in the rail already account for it; printing a time here would mean - * guessing how the plugin split the driving, and driving time is not linear in distance. - */ -function RouteViaStop({ via }: { via: RouteVia }): React.ReactElement { - const { t } = useTranslation() - return ( -
- - - {/* Hollow rather than filled: everything filled on this rail is something the - traveller put there. */} - - - - - - - - - {via.label || t('roadtrip.via.plugin')} - - {via.dwellSeconds != null ? ( - - {formatDurationShort(via.dwellSeconds)} - - ) : null} - - -
- ) -} - -function Stop({ stop, number, entry, late, driveFindings, selected, continues, starts, onSelect, onMove, canMove, onEditStay, onPickKind, onPickFill }: { - stop: RoadtripStop - /** Position within the day — the same count the map badges its markers with. */ - number: number - entry: ScheduleEntry | undefined - /** Arriving after a pinned time, or after the time this stop was set to be left at. */ - late: ScheduleWarning[] - /** Findings about the drive LEAVING this stop, when the limits are set and it goes over. */ - driveFindings?: ScheduleWarning[] - selected: boolean - /** Whether the chain goes on below, so the marker keeps hold of the line. */ - continues: boolean - /** First row of the day: no line above it, because the chain starts here. */ - starts?: boolean - /** Opens the kind picker on the number. Absent leaves the rail read-only. */ - onPickKind?: (anchor: HTMLElement) => void - /** Opens the panel that sets how full THIS stop fills, hung under the badge. */ - onPickFill?: (anchor: HTMLElement) => void - onSelect?: () => void - /** Moves this stop by one place. Absent means the chain is read-only. */ - onMove?: (delta: number) => void - /** Whether there is anywhere to move in each direction, so the ends say so. */ - canMove?: { up: boolean; down: boolean } - /** Opens the dialog for how long this stop takes. Absent means the rail is read-only. */ - onEditStay?: () => void -}): React.ReactElement { - const { t } = useTranslation() - // Read here rather than threaded down: both stop shapes need the same two, and the - // badge is the only thing in the rail that depends on them. - const fillPercent = useRoadtripSettings(s => s.roadtrip_fill_percent) - const { vehicleKind } = useVehicleRange() - return ( - - ) -} - /** * One day, one card: its own numbers in its own head, its stops chained below. * diff --git a/client/src/components/Roadtrip/RoadtripSidebarStopRows.test.tsx b/client/src/components/Roadtrip/RoadtripSidebarStopRows.test.tsx new file mode 100644 index 000000000..f451bf151 --- /dev/null +++ b/client/src/components/Roadtrip/RoadtripSidebarStopRows.test.tsx @@ -0,0 +1,250 @@ +import React from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { fireEvent, render, screen } from '@testing-library/react' +import { TranslationProvider } from '../../i18n' +import type { RoadtripStop } from './useRoadtripRoutes' +import type { ScheduleEntry, ScheduleWarning } from './roadtripModel' +import type { RouteVia } from '../../types' +import { RouteViaStop, ServiceStop, Stop } from './RoadtripSidebarStopRows' +import { preferences, resetRailStores, seedRailSettings, tooltipOf } from '../../../tests/helpers/roadtripRail' + +const wrap = (ui: React.ReactElement) => render({ui}) + +beforeEach(() => seedRailSettings()) +afterEach(() => resetRailStores()) + +function stop(over: Partial = {}): RoadtripStop { + return { + assignmentId: 1, ownerDayId: 1, ownerIndex: 0, placeId: 10, name: 'Lüneburg', lat: 53.2, lng: 10.4, + time: null, dwellMinutes: null, legMode: null, incomingLegMode: null, stopType: null, + ...over, + } +} + +const entry = (over: Partial = {}): ScheduleEntry => + ({ arrival: '11:20', departure: null, anchored: false, dayOffset: 0, ...over }) + +const warning = (over: Partial & Pick): ScheduleWarning => ({ index: 0, ...over }) + +const fuelStop = (over: Partial = {}): RoadtripStop => stop({ name: 'Aral Autohof', stopType: 'fuel', ...over }) + +/** The badge row under a stop's name: the second line of the name column. */ +const badgeRowOf = (name: string): Element => screen.getByText(name).closest('.flex-col')!.children[1] + +describe('RouteViaStop', () => { + it('FE-ROADTRIP-STOPROWS-001: a plugin halt reads its own name and the time it takes, on a hollow disc', () => { + const via = { lat: 52.1, lng: 10.1, label: 'Ionity Allertal', dwellSeconds: 1200 } as RouteVia + const { container } = wrap() + expect(screen.getByText('Ionity Allertal')).toBeInTheDocument() + expect(screen.getByText('20 min')).toBeInTheDocument() + expect(container.querySelector('svg.lucide-zap')!.parentElement).toHaveClass('border-dashed') + expect(screen.queryByRole('button')).toBeNull() + }) + + it('FE-ROADTRIP-STOPROWS-002: without a name it is a stop on the way, and without a stay it says no time', () => { + const { container } = wrap() + expect(screen.getByText('Stop on the way')).toBeInTheDocument() + // The name alone in its column: no second line for a stay the plugin gave none of. + expect(screen.getByText('Stop on the way').parentElement!.children).toHaveLength(1) + expect(container.textContent).not.toMatch(/\d/) + }) +}) + +describe('ServiceStop', () => { + it('FE-ROADTRIP-STOPROWS-003: the disc opens the kind picker on a click, Enter or Space, and never selects the row', () => { + const onPickKind = vi.fn() + const onSelect = vi.fn() + wrap() + const disc = screen.getByRole('button', { name: 'Change what kind of stop this is' }) + expect(disc).toHaveStyle({ background: '#E8590C', color: '#fff' }) + expect(disc.querySelector('svg.lucide-fuel')).not.toBeNull() + + fireEvent.click(disc) + expect(onPickKind).toHaveBeenLastCalledWith(disc) + fireEvent.keyDown(disc, { key: 'Enter' }) + fireEvent.keyDown(disc, { key: ' ' }) + expect(onPickKind).toHaveBeenCalledTimes(3) + fireEvent.keyDown(disc, { key: 'a' }) + expect(onPickKind).toHaveBeenCalledTimes(3) + expect(onSelect).not.toHaveBeenCalled() + expect(tooltipOf(disc)).toBe('Change what kind of stop this is') + }) + + it('FE-ROADTRIP-STOPROWS-004: read-only, the disc names the kind, and a kind the table does not know is a rest area', () => { + const fuel = wrap() + expect(screen.getByLabelText('Fuel')).toBeInTheDocument() + expect(screen.queryByRole('button', { name: 'Change what kind of stop this is' })).toBeNull() + fuel.unmount() + + const { container } = wrap( + , + ) + expect(screen.getByLabelText('Rest area')).toBeInTheDocument() + expect(container.querySelector('svg.lucide-square-parking, svg.lucide-parking-square')).not.toBeNull() + expect(screen.getByLabelText('Rest area').parentElement).toHaveStyle({ background: '#64748B' }) + }) + + it('FE-ROADTRIP-STOPROWS-005: a pause with no kind at all reads as a rest area too', () => { + wrap() + expect(screen.getByLabelText('Rest area')).toBeInTheDocument() + }) + + it('FE-ROADTRIP-STOPROWS-006: the row selects the pause, says when it is selected and reads its arrival', () => { + const onSelect = vi.fn() + const { rerender } = wrap() + const row = screen.getByText('Aral Autohof').closest('button')! + expect(row).not.toHaveAttribute('aria-current') + expect(screen.getByText('11:20')).toBeInTheDocument() + fireEvent.click(row) + expect(onSelect).toHaveBeenCalledTimes(1) + + rerender() + expect(row).toHaveAttribute('aria-current', 'true') + expect(row).toHaveClass('bg-surface-selected') + }) +}) + +describe('Stop', () => { + it('FE-ROADTRIP-STOPROWS-007: the number opens the kind picker on a click, Enter or Space, without selecting the stop', () => { + const onPickKind = vi.fn() + const onSelect = vi.fn() + wrap() + const number = screen.getByRole('button', { name: 'Make it a stop on the way' }) + expect(number).toHaveTextContent('3') + + fireEvent.click(number) + expect(onPickKind).toHaveBeenLastCalledWith(number) + fireEvent.keyDown(number, { key: 'Enter' }) + fireEvent.keyDown(number, { key: ' ' }) + expect(onPickKind).toHaveBeenCalledTimes(3) + fireEvent.keyDown(number, { key: 'Escape' }) + expect(onPickKind).toHaveBeenCalledTimes(3) + expect(onSelect).not.toHaveBeenCalled() + expect(tooltipOf(number)).toBe('Make it a stop on the way') + + // The stop itself still selects from anywhere else on the row. + fireEvent.click(screen.getByText('Lüneburg')) + expect(onSelect).toHaveBeenCalledTimes(1) + }) + + it('FE-ROADTRIP-STOPROWS-008: read-only, the number is a plain marker, and the line runs only where the chain does', () => { + const { container } = wrap() + expect(screen.queryByRole('button', { name: 'Make it a stop on the way' })).toBeNull() + const marker = screen.getByText('1') + expect(marker.tagName).toBe('SPAN') + expect(marker.parentElement!.children).toHaveLength(1) + expect(container.querySelector('button')).toHaveAttribute('aria-current', 'true') + }) + + it('FE-ROADTRIP-STOPROWS-009: a charger keeps its name to one line, leaving room for the charging panel beside it', () => { + const charger = wrap() + expect(screen.getByText('Ionity Allertal')).toHaveClass('min-w-0', 'truncate') + expect(screen.getByText('Ionity Allertal').nextElementSibling).not.toBeNull() + charger.unmount() + + wrap() + expect(screen.getByText('Lüneburg')).toHaveClass('min-w-0', 'break-words') + expect(screen.getByText('Lüneburg').nextElementSibling).toBeNull() + }) + + it('FE-ROADTRIP-STOPROWS-010: Alt and an arrow move the stop where there is room, and nothing else does', () => { + const onMove = vi.fn() + wrap() + const row = screen.getByText('Lüneburg').closest('button')! + fireEvent.keyDown(row, { key: 'ArrowUp' }) + fireEvent.keyDown(row, { key: 'ArrowDown', altKey: true }) + expect(onMove).not.toHaveBeenCalled() + fireEvent.keyDown(row, { key: 'ArrowUp', altKey: true }) + expect(onMove).toHaveBeenCalledWith(-1) + }) +}) + +describe('the badge row both stop shapes share', () => { + const findings = [ + warning({ code: 'leg', overMinutes: 30 }), + // The rail hands range findings to the refuel band and never draws them on a row, + // and a code the row has no words for draws nothing: only a direct render reaches + // either arm. + warning({ code: 'range', sinceKm: 612 }), + warning({ code: 'overnight' }), + ] + + it('FE-ROADTRIP-STOPROWS-011: a numbered stop carries the findings about its drive and its lateness, each with its own figure', () => { + const { container } = wrap( + , + ) + expect(screen.getByText('+30 min')).toBeInTheDocument() + expect(screen.getByText('612 km')).toBeInTheDocument() + expect(container.querySelector('svg.lucide-fuel')).not.toBeNull() + expect(screen.getByLabelText('Arrives 15 min after the time you set')).toBeInTheDocument() + // The two drive findings and the lateness; the overnight code adds nothing. + expect(badgeRowOf('Lüneburg').children).toHaveLength(3) + }) + + it('FE-ROADTRIP-STOPROWS-012: a pause carries the same findings the same way', () => { + wrap() + expect(screen.getByText('+30 min')).toBeInTheDocument() + expect(screen.getByText('612 km')).toBeInTheDocument() + expect(tooltipOf(screen.getByText('612 km').parentElement!)).toBe('612 km since the last fill-up') + }) + + it('FE-ROADTRIP-STOPROWS-013: the walk from the road shows once it is far enough to change the plan', () => { + const far = wrap() + expect(screen.getByText('400 m')).toBeInTheDocument() + expect(far.container.querySelector('svg.lucide-footprints')).not.toBeNull() + far.unmount() + + const pause = wrap() + expect(screen.getByText('400 m')).toBeInTheDocument() + pause.unmount() + + const near = wrap() + expect(near.container.querySelector('svg.lucide-footprints')).toBeNull() + }) + + it('FE-ROADTRIP-STOPROWS-014: a stop that fills up reads its own figure, or the traveller\'s default faintly, and opens the fill panel', () => { + preferences({ roadtrip_fill_percent: 80 }) + const onPickFill = vi.fn() + const inherited = wrap() + const badge = screen.getByRole('button', { name: '80 %' }) + expect(screen.getByText('80 %')).toHaveClass('text-content-faint') + fireEvent.click(badge) + expect(onPickFill).toHaveBeenCalledWith(badge) + inherited.unmount() + + wrap() + expect(screen.getByText('60 %')).not.toHaveClass('text-content-faint') + }) + + it('FE-ROADTRIP-STOPROWS-015: a full tank by default is nothing to say, and only a stop that refuels this vehicle carries the badge', () => { + preferences({ roadtrip_fill_percent: 100 }) + const full = wrap() + expect(screen.queryByText(/%/)).toBeNull() + full.unmount() + + // An electric car does not fill up at a pump, and a place the trip is for fills no tank. + preferences({ roadtrip_vehicle: 'electric', roadtrip_fill_percent: 80 }) + const pump = wrap() + expect(screen.queryByText(/%|\+/)).toBeNull() + pump.unmount() + + wrap() + expect(screen.queryByText(/%|\+/)).toBeNull() + }) + + it('FE-ROADTRIP-STOPROWS-016: the row is the bare wrapping line straight under the name, with the stay that opens its dialog', () => { + const onEditStay = vi.fn() + const numbered = wrap() + const row = badgeRowOf('Lüneburg') + expect(row.tagName).toBe('SPAN') + expect(row).toHaveClass('flex', 'flex-wrap', 'items-center', 'gap-1') + fireEvent.click(screen.getByRole('button', { name: 'Add a stay' })) + expect(onEditStay).toHaveBeenCalledTimes(1) + numbered.unmount() + + wrap() + const pauseRow = badgeRowOf('Aral Autohof') + expect(pauseRow).toHaveClass('flex-wrap') + expect(pauseRow.firstElementChild).toHaveTextContent('Check-in15:00') + }) +}) diff --git a/client/src/components/Roadtrip/RoadtripSidebarStopRows.tsx b/client/src/components/Roadtrip/RoadtripSidebarStopRows.tsx new file mode 100644 index 000000000..6d050ee2d --- /dev/null +++ b/client/src/components/Roadtrip/RoadtripSidebarStopRows.tsx @@ -0,0 +1,325 @@ +import React from 'react' +import { ParkingSquare, Zap } from 'lucide-react' +import ChargingInfo from './ChargingInfo' +import { useRoadtripSettings } from '../../hooks/useRoadtripSettings' +import { useTranslation } from '../../i18n/TranslationContext' +import { Tooltip } from '../shared/Tooltip' +import { formatDurationShort, refuelsRange, serviceColor, type ScheduleEntry, type ScheduleWarning } from './roadtripModel' +import { STOP_KIND_BY_KEY } from './stopKinds' +import { spurWorthLabelling } from './accessSpur' +import { useVehicleRange } from './useVehicleRange' +import type { RoadtripStop } from './useRoadtripRoutes' +import type { RouteVia } from '../../types' +import { readStay } from './stayReading' +import { FS } from './typeScale' +import { DISC, RAIL_DASH, RAIL_GRID } from './RoadtripSidebar.constants' +import { Arrival, DriveFindingBadge, FillBadge, LateBadge, NightCheckIn, OffRoadBadge, StayBadge } from './RoadtripSidebarBadges' + +/** + * What a stop will actually fill to: its own figure, else the traveller's default. + * + * Null means nothing worth saying: no per-stop figure and a default that fills right up, + * which is what the budget did before any of this existed. An explicit 100 on the stop is + * NOT null: on a trip whose default is 80 %, "this one goes right up" is a decision, and + * hiding it would leave the traveller reading 80 on a stop that fills to 100. + */ +function effectiveFill(own: number | null | undefined, setting: number | undefined): number | null { + if (own !== null && own !== undefined) return own + return setting && setting > 0 && setting < 100 ? setting : null +} + +/** + * The badges under a stop's name, shared by both stop shapes so the two cannot drift + * apart. It renders the bare span and nothing around it, so a stop's markup is exactly + * what it was when each shape drew the row itself. + */ +function StopBadgeRow({ stop, entry, late, driveFindings, onEditStay, onPickFill }: Readonly<{ + stop: RoadtripStop + entry: ScheduleEntry | undefined + late: ScheduleWarning[] + driveFindings?: ScheduleWarning[] + onEditStay?: () => void + onPickFill?: (anchor: HTMLElement) => void +}>): React.ReactElement { + // Read here rather than threaded down from the rail: the fill badge is the only thing in + // it that depends on them. + const fillPercent = useRoadtripSettings(s => s.roadtrip_fill_percent) + const { vehicleKind } = useVehicleRange() + return ( + + + + {refuelsRange(stop.stopType, vehicleKind) ? ( + + ) : null} + {spurWorthLabelling(stop.offRoadMeters) ? : null} + {(driveFindings ?? []).map(w => )} + {late.map(w => )} + + ) +} + +/** + * A charger, a filling station or a rest stop: a stop that interrupts the drive. + * + * It sits inside the leg with the dashed line running through it, carries no number and + * is left out of every count, because that is the difference between it and the places + * the trip is actually for. Its own icon on one flat disc: three kinds of pause that all + * mean "we are still driving", and the icon is what tells them apart. + */ +export function ServiceStop({ stop, entry, late, driveFindings, selected, onSelect, onEditStay, onPickKind, onPickFill }: { + stop: RoadtripStop + entry: ScheduleEntry | undefined + /** How late the drive reaches a time pinned on this pause, or the time it was set to + * be left at: the same findings a numbered stop shows. A fuel or charging halt can + * carry a pinned time like anything else. */ + late: ScheduleWarning[] + /** Findings about the drive that ARRIVES here. A charging halt is a stop like any other + * as far as the tank is concerned, so it carries them the same way a numbered one does. */ + driveFindings?: ScheduleWarning[] + /** Opens the kind picker on the disc. Absent leaves the rail read-only. */ + onPickKind?: (anchor: HTMLElement) => void + /** Opens the panel that sets how full THIS stop fills, hung under the badge. */ + onPickFill?: (anchor: HTMLElement) => void + selected: boolean + onSelect?: () => void + /** Opens the dialog for how long this pause takes. Absent means the rail is read-only. */ + onEditStay?: () => void +}): React.ReactElement { + const { t } = useTranslation() + // Icon and name both come from the one stop-kind table. The rail used to keep its own + // copy of each, and its rest_area icon had drifted away from the popup's. + const kind = STOP_KIND_BY_KEY[stop.stopType ?? ''] + const Icon = kind?.Icon ?? ParkingSquare + const label = t(kind?.labelKey ?? 'roadtrip.poi.rest') + return ( +
+ + + {onPickKind ? ( + // The same control the other way round: the disc says what this is, and it is + // also where it stops being that. + + { e.stopPropagation(); onPickKind(e.currentTarget as HTMLElement) }} + onKeyDown={e => { + if (e.key !== 'Enter' && e.key !== ' ') return + e.preventDefault() + e.stopPropagation() + onPickKind(e.currentTarget as HTMLElement) + }} + className={`${DISC} cursor-pointer transition-transform hover:scale-110 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2`} + // theme-lint-disable: the road-signage palette in `roadtripModel`, shared + // with the corridor list and the map pin so one kind of stop looks like + // itself wherever it turns up. + style={{ background: serviceColor(stop.stopType), color: '#fff' }} // theme-lint-disable: road-signage palette + > + + + + ) : ( + + + + )} + + + +
+ ) +} + +/** + * A halt a routing plugin put on this leg, such as a charge on the way. + * + * Read-only, and that is the point rather than a shortcut. The halt belongs to the + * provider, not to the traveller: it is not a place in the database, it has no number, no + * editable stay and no arrival time. Writing it back would send it out as a waypoint on + * the next run, and the plugin would then plan around its own charging stop. + * + * No clock on purpose. The stay is already inside the leg duration the plugin reported, + * so the arrivals in the rail already account for it; printing a time here would mean + * guessing how the plugin split the driving, and driving time is not linear in distance. + */ +export function RouteViaStop({ via }: { via: RouteVia }): React.ReactElement { + const { t } = useTranslation() + return ( +
+ + + {/* Hollow rather than filled: everything filled on this rail is something the + traveller put there. */} + + + + + + + + + {via.label || t('roadtrip.via.plugin')} + + {via.dwellSeconds != null ? ( + + {formatDurationShort(via.dwellSeconds)} + + ) : null} + + +
+ ) +} + +export function Stop({ stop, number, entry, late, driveFindings, selected, continues, starts, onSelect, onMove, canMove, onEditStay, onPickKind, onPickFill }: { + stop: RoadtripStop + /** Position within the day: the same count the map badges its markers with. */ + number: number + entry: ScheduleEntry | undefined + /** Arriving after a pinned time, or after the time this stop was set to be left at. */ + late: ScheduleWarning[] + /** Findings about the drive LEAVING this stop, when the limits are set and it goes over. */ + driveFindings?: ScheduleWarning[] + selected: boolean + /** Whether the chain goes on below, so the marker keeps hold of the line. */ + continues: boolean + /** First row of the day: no line above it, because the chain starts here. */ + starts?: boolean + /** Opens the kind picker on the number. Absent leaves the rail read-only. */ + onPickKind?: (anchor: HTMLElement) => void + /** Opens the panel that sets how full THIS stop fills, hung under the badge. */ + onPickFill?: (anchor: HTMLElement) => void + onSelect?: () => void + /** Moves this stop by one place. Absent means the chain is read-only. */ + onMove?: (delta: number) => void + /** Whether there is anywhere to move in each direction, so the ends say so. */ + canMove?: { up: boolean; down: boolean } + /** Opens the dialog for how long this stop takes. Absent means the rail is read-only. */ + onEditStay?: () => void +}): React.ReactElement { + const { t } = useTranslation() + return ( + + ) +} diff --git a/client/tests/helpers/roadtripRail.ts b/client/tests/helpers/roadtripRail.ts index 2b394e653..adfa95ae7 100644 --- a/client/tests/helpers/roadtripRail.ts +++ b/client/tests/helpers/roadtripRail.ts @@ -1,5 +1,10 @@ import { act, fireEvent, screen } from '@testing-library/react' import { vi } from 'vitest' +import type { RoadtripPreferences } from '@trek/shared' +import { useAuthStore } from '../../src/store/authStore' +import { useRoadtripPreferencesStore } from '../../src/store/roadtripPreferencesStore' +import { useSettingsStore } from '../../src/store/settingsStore' +import { useTripStore } from '../../src/store/tripStore' /** Scaffolding for the tests of the road trip rail's parts, each rendered on its own. */ @@ -18,3 +23,26 @@ export function tooltipOf(el: Element): string { vi.useRealTimers() return text } + +const USER_ID = 7 +const TRIP_ID = 4 + +/** The traveller's road trip settings for the trip on screen. */ +export function preferences(p: RoadtripPreferences): void { + useAuthStore.setState({ user: { id: USER_ID } } as never) + useTripStore.setState({ trip: { id: TRIP_ID } } as never) + useRoadtripPreferencesStore.setState({ byTrip: { [`${USER_ID}:${TRIP_ID}`]: p } }) +} + +/** Metric distances on a 24-hour clock, the settings each case starts from. */ +export function seedRailSettings(): void { + useSettingsStore.setState({ settings: { distance_unit: 'metric', time_format: '24h' } as never }) +} + +/** The real clock, and no road trip settings, trip or user, once a case is done. */ +export function resetRailStores(): void { + vi.useRealTimers() + useRoadtripPreferencesStore.setState({ byTrip: {} }) + useTripStore.setState({ trip: null } as never) + useAuthStore.setState({ user: null } as never) +}