mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-06 02:34:21 +00:00
Merge pull request #2384 from liketrek/feat/roadtrip-mobile
feat(roadtrip): bring the road trip addon to the phone
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
// FE-COMP-MBADGE-001 to FE-COMP-MBADGE-006
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { Route } from 'lucide-react'
|
||||
import MBadge from './MBadge'
|
||||
|
||||
describe('MBadge', () => {
|
||||
it('FE-COMP-MBADGE-001: renders its label in a span and is no control', () => {
|
||||
render(<MBadge>3 stops</MBadge>)
|
||||
|
||||
const badge = screen.getByText('3 stops')
|
||||
expect(badge.tagName).toBe('SPAN')
|
||||
// It sits inside buttons, and a button inside a button is invalid markup.
|
||||
expect(screen.queryByRole('button')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-COMP-MBADGE-002: is neutral by default on the resting chip tokens, and strong on the active ones', () => {
|
||||
render(<MBadge>neutral</MBadge>)
|
||||
const neutral = screen.getByText('neutral')
|
||||
expect(neutral.className).toContain('bg-[color:var(--m-ic)]')
|
||||
expect(neutral.className).toContain('border-[color:var(--m-rowbr)]')
|
||||
expect(neutral.className).not.toContain('bg-m-act')
|
||||
|
||||
render(<MBadge tone="strong">strong</MBadge>)
|
||||
const strong = screen.getByText('strong')
|
||||
expect(strong.className).toContain('bg-m-act')
|
||||
expect(strong.className).toContain('text-m-actfg')
|
||||
expect(strong.className).not.toContain('bg-[color:var(--m-ic)]')
|
||||
})
|
||||
|
||||
it('FE-COMP-MBADGE-003: sets words in caps by default and leaves a unit symbol alone when asked', () => {
|
||||
render(<MBadge>Sat 2</MBadge>)
|
||||
expect(screen.getByText('Sat 2').className).toContain('uppercase')
|
||||
|
||||
render(<MBadge caps={false}>300 m</MBadge>)
|
||||
// Uppercase would turn metres into megametres.
|
||||
expect(screen.getByText('300 m').className).not.toContain('uppercase')
|
||||
})
|
||||
|
||||
it('FE-COMP-MBADGE-004: is 18px at xs, the default, and 22px at sm', () => {
|
||||
render(<MBadge>small</MBadge>)
|
||||
expect(screen.getByText('small').className).toContain('h-[18px]')
|
||||
|
||||
render(<MBadge size="sm" className="ms-auto">larger</MBadge>)
|
||||
const larger = screen.getByText('larger')
|
||||
expect(larger.className).toContain('h-[22px]')
|
||||
expect(larger.className).toContain('ms-auto')
|
||||
})
|
||||
|
||||
it('FE-COMP-MBADGE-005: draws an icon before the label, inside the same pill and out of its name', () => {
|
||||
render(<MBadge icon={<Route size={10} />}>412 km</MBadge>)
|
||||
|
||||
const badge = screen.getByText('412 km')
|
||||
const icon = badge.firstElementChild as HTMLElement
|
||||
expect(icon.querySelector('svg')).not.toBeNull()
|
||||
expect(icon).toHaveAttribute('aria-hidden', 'true')
|
||||
expect(badge.lastChild?.textContent).toBe('412 km')
|
||||
})
|
||||
|
||||
it('FE-COMP-MBADGE-006: keeps a figure on one line, and lets a sentence wrap inside the width it is given', () => {
|
||||
render(<MBadge>412 km</MBadge>)
|
||||
const figure = screen.getByText('412 km')
|
||||
expect(figure.className).toContain('whitespace-nowrap')
|
||||
expect(figure.className).toContain('h-[18px]')
|
||||
|
||||
render(<MBadge wrap size="sm">Still working out the rest of the drive</MBadge>)
|
||||
const sentence = screen.getByText('Still working out the rest of the drive')
|
||||
expect(sentence.className).toContain('whitespace-normal')
|
||||
expect(sentence.className).toContain('max-w-full')
|
||||
expect(sentence.className).toContain('min-h-[22px]')
|
||||
expect(sentence.className).not.toContain('whitespace-nowrap')
|
||||
expect(sentence.className).not.toMatch(/(^|\s)h-\[22px\]/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
interface MBadgeProps {
|
||||
/**
|
||||
* `neutral` is MChip's resting look and the one to reach for. `strong` is MChip's active
|
||||
* look, for the single figure a surface is about, and never inside something tappable:
|
||||
* a filled pill in a button reads as a second control sitting in the first.
|
||||
*/
|
||||
tone?: 'neutral' | 'strong'
|
||||
/** `xs` is 18px, for a second line under a title. `sm` is 22px, for a 34px pill. */
|
||||
size?: 'xs' | 'sm'
|
||||
/**
|
||||
* Caps with tracking by default, for words. A figure with a unit symbol passes false,
|
||||
* because m and M are different units, and so does a clock, which has no case to change.
|
||||
*/
|
||||
caps?: boolean
|
||||
/**
|
||||
* Lets a long sentence break inside the pill instead of running past its container. A
|
||||
* figure keeps to one line, which is why this is off by default: the pill then stops at
|
||||
* the width it is given and grows in height with the text.
|
||||
*/
|
||||
wrap?: boolean
|
||||
icon?: ReactNode
|
||||
className?: string
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* The non-interactive sibling of MChip: a fact, not a control.
|
||||
*
|
||||
* A span, because every place a badge sits in the road trip chrome is itself a button, and
|
||||
* a button inside a button is markup that no browser and no screen reader agree on. Caps
|
||||
* with tracking are the desktop day card's DAY_BADGE, set for a phone.
|
||||
*
|
||||
* Pills side by side lose the space between them when a screen reader builds a name out of
|
||||
* them, so a button made of badges carries its own aria-label (see stageBadges.badgeLabel).
|
||||
*/
|
||||
export default function MBadge({
|
||||
tone = 'neutral',
|
||||
size = 'xs',
|
||||
caps = true,
|
||||
wrap = false,
|
||||
icon,
|
||||
className = '',
|
||||
children,
|
||||
}: MBadgeProps) {
|
||||
return (
|
||||
<span
|
||||
className={`inline-flex flex-none items-center gap-[3px] rounded-full font-geist font-medium tabular-nums ${
|
||||
size === 'sm' ? 'px-[9px] text-[0.65625rem]' : 'px-[7px] text-[0.59375rem]'
|
||||
} ${
|
||||
wrap
|
||||
? `max-w-full whitespace-normal py-[2px] leading-[1.15] ${size === 'sm' ? 'min-h-[22px]' : 'min-h-[18px]'}`
|
||||
: `whitespace-nowrap leading-none ${size === 'sm' ? 'h-[22px]' : 'h-[18px]'}`
|
||||
} ${caps ? 'uppercase tracking-[.07em]' : ''} ${
|
||||
tone === 'strong'
|
||||
? 'bg-m-act text-m-actfg'
|
||||
: 'border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] text-m-ink'
|
||||
} ${className}`}
|
||||
>
|
||||
{/* The icon only repeats what the label says, so it stays out of the name. */}
|
||||
{icon && <span aria-hidden="true" className="flex flex-none">{icon}</span>}
|
||||
{children}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -3,17 +3,26 @@ import { ReactNode } from 'react'
|
||||
interface MChipProps {
|
||||
active?: boolean
|
||||
onClick?: () => void
|
||||
/**
|
||||
* `sm` is the 30px chip a form sheet packs six of into a row; `tap` is 38px, for a
|
||||
* chip that IS the control rather than a setting beside one. Apple's own floor is
|
||||
* 44px and a chip cannot be that and still fit a row of categories, so `tap` buys
|
||||
* back what it can: the chips that start a search are the ones worth the height.
|
||||
*/
|
||||
size?: 'sm' | 'tap'
|
||||
className?: string
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
/** Small pill chip: --m-act when active, neutral --m-ic surface otherwise. */
|
||||
export default function MChip({ active = false, onClick, className = '', children }: MChipProps) {
|
||||
export default function MChip({ active = false, onClick, size = 'sm', className = '', children }: MChipProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className={`inline-flex flex-none items-center gap-[6px] rounded-full px-3 py-[7px] text-[0.75rem] font-semibold ${
|
||||
className={`inline-flex flex-none items-center gap-[6px] rounded-full font-semibold ${
|
||||
size === 'tap' ? 'px-[13px] py-[10px] text-[0.8125rem]' : 'px-3 py-[7px] text-[0.75rem]'
|
||||
} ${
|
||||
active
|
||||
? 'bg-m-act text-m-actfg'
|
||||
: 'border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] text-m-ink'
|
||||
|
||||
@@ -334,17 +334,27 @@
|
||||
.trek-z { opacity: 1; }
|
||||
}
|
||||
|
||||
/* Map attribution clears the dock.
|
||||
/* The phone map carries no visible credit.
|
||||
*
|
||||
* Both engines park their attribution at the bottom of the map, and on a phone
|
||||
* the map is the whole screen — so the credit line lands under the floating nav
|
||||
* and reads as a broken bar (#2022's screenshots show it over the dock). Lift it
|
||||
* by the same variable everything else clears the dock with. Leaflet and
|
||||
* MapLibre both, because a phone meets either depending on the screen. */
|
||||
* Both engines park a credit at the bottom of the map, and on a phone the map is the
|
||||
* whole screen, so whatever is put there sits in the middle of the picture. It has been
|
||||
* a band across the bottom (#2022) and then a round (i) beside the locate button, and
|
||||
* neither reads as part of this shell: a lone control under the locate button is the
|
||||
* first thing the eye lands on over a full-bleed map.
|
||||
*
|
||||
* So on the phone it is off. The desktop map is untouched and still shows the full
|
||||
* credit with its links, which is where this belongs; `.m-root` is the phone shell only.
|
||||
* Both engines and both corners, because a phone meets either depending on the screen,
|
||||
* and the GL containers hold nothing else — MapViewGL adds no control of its own, so
|
||||
* hiding the corner hides the credit and the wordmark and nothing besides.
|
||||
*
|
||||
* Owner's call, made knowingly: OSM and the tile vendors ask for a visible credit. */
|
||||
.m-root .leaflet-control-attribution,
|
||||
.m-root .maplibregl-ctrl-bottom-left,
|
||||
.m-root .maplibregl-ctrl-bottom-right {
|
||||
bottom: var(--bottom-nav-h);
|
||||
.m-root .mapboxgl-ctrl-bottom-left,
|
||||
.m-root .maplibregl-ctrl-bottom-right,
|
||||
.m-root .mapboxgl-ctrl-bottom-right {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Text fields carry the row's background, not their own.
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
// FE-MOB-CREDITCSS-001 to FE-MOB-CREDITCSS-003
|
||||
//
|
||||
// The phone map carries no visible credit: that is a decision, and the only thing holding
|
||||
// it is a rule in mobile.css against the vendor control containers. jsdom applies no
|
||||
// stylesheet, so these read the real file. Written as tests because the rule is easy to
|
||||
// lose: it names vendor class names nothing else in the codebase refers to, and a credit
|
||||
// creeping back is a change to the map's face that no component test would catch.
|
||||
describe('phone map credit css', () => {
|
||||
// Vitest runs with the client package as its root, so cwd is stable here.
|
||||
const css = readFileSync(resolve(process.cwd(), 'src/mobile/mobile.css'), 'utf8')
|
||||
|
||||
/**
|
||||
* Every rule in the sheet as its selector list and its declarations, comments dropped.
|
||||
* Parsed rather than found by substring, because a vendor class name also appears in the
|
||||
* prose above the rules.
|
||||
*/
|
||||
const rules = css
|
||||
.replace(/\/\*[\s\S]*?\*\//g, '')
|
||||
.split('}')
|
||||
.filter(chunk => chunk.includes('{'))
|
||||
.map(chunk => {
|
||||
const open = chunk.lastIndexOf('{')
|
||||
const head = chunk.slice(0, open)
|
||||
return {
|
||||
selectors: head.slice(head.lastIndexOf('{') + 1).split(',').map(s => s.trim()),
|
||||
body: chunk.slice(open + 1),
|
||||
}
|
||||
})
|
||||
/** The rules whose selector list names this selector. */
|
||||
const rulesFor = (selector: string) => rules.filter(rule => rule.selectors.includes(selector))
|
||||
|
||||
it('FE-MOB-CREDITCSS-001: both engines and both corners are hidden by one rule', () => {
|
||||
const hidden = rulesFor('.m-root .leaflet-control-attribution')
|
||||
|
||||
expect(hidden).toHaveLength(1)
|
||||
expect(hidden[0].body).toMatch(/display:\s*none;/)
|
||||
// One rule for all of them, so Leaflet, MapLibre and Mapbox cannot drift apart, and so
|
||||
// the credit cannot come back on the one engine nobody happened to open.
|
||||
for (const selector of [
|
||||
'.m-root .maplibregl-ctrl-bottom-left',
|
||||
'.m-root .mapboxgl-ctrl-bottom-left',
|
||||
'.m-root .maplibregl-ctrl-bottom-right',
|
||||
'.m-root .mapboxgl-ctrl-bottom-right',
|
||||
]) {
|
||||
expect(hidden[0].selectors).toContain(selector)
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-MOB-CREDITCSS-002: nothing else in the sheet places a credit', () => {
|
||||
// The hiding rule is the last word only while no later rule moves one of these
|
||||
// containers back into view. Both corners, because the GL wordmark sits in the left one.
|
||||
const placed = rules.filter(rule => rule.selectors.some(s => /ctrl-bottom-(left|right)|leaflet-control-attribution/.test(s)))
|
||||
|
||||
expect(placed).toHaveLength(1)
|
||||
expect(placed[0].body).toMatch(/display:\s*none;/)
|
||||
})
|
||||
|
||||
it('FE-MOB-CREDITCSS-003: the credit corner and its variables are gone with it', () => {
|
||||
// `m-credit-corner` was the trip map's own credit slot, `m-attrib-open` the class the
|
||||
// Leaflet (i) toggled. Both are dead now; a leftover rule would place an element that
|
||||
// no longer exists and read as if the credit were still somewhere on screen.
|
||||
expect(css).not.toContain('m-credit-corner')
|
||||
expect(css).not.toContain('m-attrib-open')
|
||||
expect(css).not.toContain('--m-credit')
|
||||
})
|
||||
|
||||
it('FE-MOB-CREDITCSS-004: the phone map is the only thing this touches', () => {
|
||||
// Every selector is under `.m-root`, the phone shell. The desktop map keeps its full
|
||||
// credit with its links, which is where it belongs.
|
||||
const hidden = rulesFor('.m-root .leaflet-control-attribution')
|
||||
|
||||
for (const selector of hidden[0].selectors) expect(selector.startsWith('.m-root ')).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -204,8 +204,31 @@ export default function MJourneyDetail() {
|
||||
const [pickerProvider, setPickerProvider] = useState<string | null>(null)
|
||||
const dawarichEnabled = useAddonStore(state => state.isEnabled)('dawarich')
|
||||
const [dawarichOpen, setDawarichOpen] = useState(false)
|
||||
/**
|
||||
* How tall the card rail over the dock currently is.
|
||||
*
|
||||
* Measured rather than written down: the rail is a day scrubber over a row of covers,
|
||||
* and a cover grows from 152 to 180px when it becomes the active one. The Dawarich
|
||||
* button above it used to clear a hard-coded 128px, which was short of the rail on any
|
||||
* screen and left the button sitting over the cards. Zero while there is no rail, which
|
||||
* is also the empty-journal case, and the button then sits straight above the dock.
|
||||
*/
|
||||
const [railHeight, setRailHeight] = useState(0)
|
||||
const railRef = useRef<HTMLDivElement>(null)
|
||||
const [uploading, setUploading] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
const node = railRef.current
|
||||
if (!node) { setRailHeight(0); return }
|
||||
// Observed rather than read once: the rail changes height when the active card grows,
|
||||
// and a height read at mount would be the wrong one from the first swipe onwards.
|
||||
if (typeof ResizeObserver === 'undefined') { setRailHeight(node.offsetHeight); return }
|
||||
const observer = new ResizeObserver(() => setRailHeight(node.offsetHeight))
|
||||
observer.observe(node)
|
||||
setRailHeight(node.offsetHeight)
|
||||
return () => observer.disconnect()
|
||||
}, [view, entries.length])
|
||||
|
||||
const openUpload = useCallback(() => {
|
||||
if (availableProviders.length > 0) setShowUploadMenu(true)
|
||||
else galleryFileRef.current?.click()
|
||||
@@ -450,7 +473,10 @@ export default function MJourneyDetail() {
|
||||
type="button"
|
||||
onClick={() => setDawarichOpen(true)}
|
||||
aria-label={t('dawarich.suggestions.title')}
|
||||
className="absolute right-4 z-[9] flex h-[46px] w-[46px] items-center justify-center overflow-hidden rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-sheet)] shadow-[0_6px_18px_-8px_rgba(0,0,0,.35)] bottom-[calc(var(--bottom-nav-h,84px)+16px+128px)]"
|
||||
className="absolute right-4 z-[9] flex h-[46px] w-[46px] items-center justify-center overflow-hidden rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-sheet)] shadow-[0_6px_18px_-8px_rgba(0,0,0,.35)]"
|
||||
// The rail's own offset over the dock, its measured height, then a gap. The 128px
|
||||
// this used to guess at was short of the rail, so the button lay on the cards.
|
||||
style={{ bottom: `calc(var(--bottom-nav-h, 84px) + 2px + ${railHeight}px + 12px)` }}
|
||||
>
|
||||
<DawarichIcon size={46} />
|
||||
</button>
|
||||
@@ -487,7 +513,7 @@ export default function MJourneyDetail() {
|
||||
nothing between the cards and it; two pixels keeps a hair of daylight and
|
||||
gives the strip the rest. */}
|
||||
{view === 'timeline' && entries.length > 0 && (
|
||||
<div className="absolute left-0 right-0 z-[8] bottom-[calc(var(--bottom-nav-h,84px)+2px)]">
|
||||
<div ref={railRef} className="absolute left-0 right-0 z-[8] bottom-[calc(var(--bottom-nav-h,84px)+2px)]">
|
||||
<JourneyDayScrubber
|
||||
days={scrubberDays}
|
||||
activeDate={entries[activeIndex]?.entry_date ?? null}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { useEffect, useRef, useState, type ComponentType, type ReactNode } from 'react'
|
||||
import { findFocusDayId } from '../../../components/Planner/today'
|
||||
import {
|
||||
CalendarDays, ChevronDown, ChevronLeft, Download, FileDown, List, Map as MapIcon, MoreHorizontal, PackageCheck,
|
||||
Plane, Plus, Rows3, Ticket, TrainFront, Trash2, Upload, Wallet,
|
||||
CalendarDays, ChevronDown, ChevronLeft, Download, FileDown, List, Map as MapIcon, MoreHorizontal,
|
||||
Plane, Plus, Rows3, Route, SlidersHorizontal, Trash2, Upload,
|
||||
} from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { useTripPlanner } from '../../../pages/tripPlanner/useTripPlanner'
|
||||
import { pickDockTabs } from './dockTabs'
|
||||
import MBadge from '../../components/MBadge'
|
||||
import MIconBtn from '../../components/MIconBtn'
|
||||
import MPlanTimeline from './plan/MPlanTimeline'
|
||||
import MMapArea from './map/MMapArea'
|
||||
@@ -14,6 +15,10 @@ import MTripTabPanel from './tabs/MTripTabPanel'
|
||||
import MTripSheets from './sheets/MTripSheets'
|
||||
import MTripLoadingSplash from './MTripLoadingSplash'
|
||||
import { usePluginDayTints, dayTintBackground } from '../../../components/Plugins/PluginDaySchedule'
|
||||
import { stageOf } from '../../../components/Roadtrip/roadtripRowModel'
|
||||
import { badgeLabel, distanceBadge } from './roadtrip/stageBadges'
|
||||
import type { CorridorReach } from '../../../components/Roadtrip/corridorSearchModel'
|
||||
import { useSettingsStore } from '../../../store/settingsStore'
|
||||
import type { Day } from '../../../types'
|
||||
|
||||
/**
|
||||
@@ -34,6 +39,8 @@ export type TripPlanner = ReturnType<typeof useTripPlanner>
|
||||
|
||||
export type MTripView = 'plan' | 'map'
|
||||
export type MTripMode = 'go' | 'edit' | 'browse'
|
||||
/** The road trip tab's own two halves: the chain, or the same map showing the stage. */
|
||||
export type MRtView = 'list' | 'map'
|
||||
export type MTripListsTab = 'packing' | 'todo'
|
||||
export type MTripCollabTab = 'chat' | 'notes' | 'links' | 'polls'
|
||||
|
||||
@@ -60,6 +67,27 @@ export interface MTripSheetState {
|
||||
export interface MTripShellApi {
|
||||
/** 'plan' = list chrome, 'map' = fullscreen map. Plan tab only. */
|
||||
view: MTripView
|
||||
/** The road trip tab's own list ⇄ map switch, independent of `view`. */
|
||||
rtView: MRtView
|
||||
/**
|
||||
* True whenever the map is the front layer, in either tab.
|
||||
*
|
||||
* The map is one instance shared by the plan tab and the road trip tab, so
|
||||
* everything floating over it (POI pill, compass, pills) keys off this rather
|
||||
* than off `view`, which only ever meant the plan tab.
|
||||
*/
|
||||
mapFront: boolean
|
||||
/** Road trip tab: chain ⇄ map, on the same instance, without moving the camera. */
|
||||
toggleRtView: () => void
|
||||
/**
|
||||
* How much of the stage the corridor search asks about.
|
||||
*
|
||||
* Shell state rather than sheet state, because two surfaces ask the same question:
|
||||
* the bar over the stage says what the next search will cover, and the sheet is where
|
||||
* it is chosen. Kept here they cannot disagree, and it survives the sheet closing.
|
||||
*/
|
||||
rtReach: CorridorReach
|
||||
setRtReach: (value: CorridorReach) => void
|
||||
/** Travel/Plan/Places segment: go | edit | browse. */
|
||||
mode: MTripMode
|
||||
/** Legacy tab ids: plan · transports · buchungen · listen · finanzplan · dateien · collab · plugin:* */
|
||||
@@ -150,14 +178,8 @@ interface MTripShellProps {
|
||||
Sheets?: ComponentType<MTripSheetsProps>
|
||||
}
|
||||
|
||||
/** The 5 dock tabs in demo order; files/collab/plugins live in the Mehr sheet. */
|
||||
const DOCK_TABS: { id: string; icon: LucideIcon }[] = [
|
||||
{ id: 'plan', icon: MapIcon },
|
||||
{ id: 'transports', icon: TrainFront },
|
||||
{ id: 'buchungen', icon: Ticket },
|
||||
{ id: 'finanzplan', icon: Wallet },
|
||||
{ id: 'listen', icon: PackageCheck },
|
||||
]
|
||||
/** The two tabs that share the map instance. Everything else is a full overlay. */
|
||||
const MAP_TABS = new Set(['plan', 'roadtrip'])
|
||||
|
||||
function dayChipLabel(day: Day, language: string, fallback: string): string {
|
||||
if (day.date) {
|
||||
@@ -182,8 +204,14 @@ export default function MTripShell({
|
||||
// Per-day colours from the dayTintProvider plugin hook — the mobile counterpart
|
||||
// of the desktop day-card wash, carried on the day chips. Empty without a plugin.
|
||||
const dayTints = usePluginDayTints(tripId)
|
||||
const distanceUnit = useSettingsStore(s => s.settings.distance_unit)
|
||||
|
||||
const [view, setView] = useState<MTripView>('plan')
|
||||
// Its own state rather than a share of `view`: the two tabs carry different
|
||||
// things on the same map, and forcing one into the other's half is the kind of
|
||||
// coupling nobody can predict from the outside.
|
||||
const [rtView, setRtView] = useState<MRtView>('list')
|
||||
const [rtReach, setRtReach] = useState<CorridorReach>('ahead')
|
||||
const [mode, setMode] = useState<MTripMode>('go')
|
||||
const [browseFromEdit, setBrowseFromEdit] = useState(false)
|
||||
const [sheet, setSheet] = useState<MTripSheetState | null>(null)
|
||||
@@ -318,6 +346,24 @@ export default function MTripShell({
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The road trip tab's own list ⇄ map switch.
|
||||
*
|
||||
* Deliberately quieter than `toggleView`: no reframe on the way in and no day
|
||||
* restore on the way out. The stage is always one day, the chain and the map show
|
||||
* the same one, and the camera belongs to whoever looked at it last. What does
|
||||
* reframe is a stage change, through the day chips, which both halves share.
|
||||
*/
|
||||
const toggleRtView = () => {
|
||||
setRtView(prev => {
|
||||
const next = prev === 'list' ? 'map' : 'list'
|
||||
if (next === 'map') planner.autoShowRoute()
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const mapFront = (trTab === 'plan' && view === 'map') || (trTab === 'roadtrip' && rtView === 'map')
|
||||
|
||||
const setListsTab = (tab: MTripListsTab) => {
|
||||
setListsTabState(tab)
|
||||
sessionStorage.setItem(`trip-lists-subtab-${tripId}`, tab)
|
||||
@@ -327,7 +373,7 @@ export default function MTripShell({
|
||||
const closeSheet = () => setSheet(null)
|
||||
|
||||
const shell: MTripShellApi = {
|
||||
view, mode, trTab, setTrTab, setTravelMode, toggleView, browseFromEdit,
|
||||
view, rtView, mapFront, toggleRtView, rtReach, setRtReach, mode, trTab, setTrTab, setTravelMode, toggleView, browseFromEdit,
|
||||
sheet, openSheet, closeSheet,
|
||||
listsTab, setListsTab, collabTab, setCollabTab,
|
||||
transportsCompact, bookingsCompact,
|
||||
@@ -341,7 +387,7 @@ export default function MTripShell({
|
||||
if (!trip) return null
|
||||
|
||||
const enabledTabIds = new Set(planner.TRIP_TABS.map(tab => tab.id))
|
||||
const dockTabs = DOCK_TABS.filter(d => enabledTabIds.has(d.id))
|
||||
const dockTabs = pickDockTabs(enabledTabIds)
|
||||
const tabLabel = (id: string) => planner.TRIP_TABS.find(tab => tab.id === id)?.label ?? id
|
||||
|
||||
const onDayChipTap = (dayId: number) => {
|
||||
@@ -355,25 +401,62 @@ export default function MTripShell({
|
||||
const packedCount = packingItems.filter(i => i.checked).length
|
||||
const todoOpenCount = todoItems.filter(i => !i.checked).length
|
||||
|
||||
// The stage header: the day on screen and what it costs, or the whole drive while
|
||||
// the day filter is off. A figure nothing has measured yet is left out rather than
|
||||
// printed as 0 m, and with neither figure the pill falls back to the addon's own name,
|
||||
// so it never reads as an empty one.
|
||||
const rtStage = stageOf(planner.roadtripRoutes.days, planner.selectedDayId)
|
||||
const rtStageDay = rtStage ? days.find(d => d.id === rtStage.dayId) : undefined
|
||||
let rtHeaderDay: string | null = null
|
||||
if (rtStage) {
|
||||
const dayN = t('planner.dayN', { n: rtStage.dayNumber })
|
||||
rtHeaderDay = rtStageDay ? dayChipLabel(rtStageDay, language, dayN) : dayN
|
||||
}
|
||||
const rtHeaderDistance = distanceBadge(
|
||||
rtStage ? rtStage.distance : planner.roadtripRoutes.totalDistance,
|
||||
distanceUnit,
|
||||
)
|
||||
const rtHeaderLabel = badgeLabel([rtHeaderDay, rtHeaderDistance])
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 overflow-hidden bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] text-m-ink">
|
||||
{/* ── Content layers ─────────────────────────────────────────────── */}
|
||||
{trTab === 'plan' && (
|
||||
{/*
|
||||
One expression for both map tabs, and it has to stay one: written as two
|
||||
(`{trTab === 'plan' && <MapArea/>}{trTab === 'roadtrip' && <MapArea/>}`)
|
||||
React sees two positions and remounts the map on every tab switch, which
|
||||
tears down the WebGL context and reloads every tile. The symptom is a flash
|
||||
on the device, not a failing test.
|
||||
*/}
|
||||
{MAP_TABS.has(trTab) && (
|
||||
<div className="absolute inset-0">
|
||||
<MapArea planner={planner} shell={shell} />
|
||||
{view === 'plan' && mode !== 'browse' && (
|
||||
{trTab === 'plan' && view === 'plan' && mode !== 'browse' && (
|
||||
<div className="absolute inset-0 z-10 bg-[color:var(--m-bg)] bg-[image:var(--m-scr)]">
|
||||
<PlanTimeline planner={planner} shell={shell} />
|
||||
</div>
|
||||
)}
|
||||
{mode === 'browse' && (
|
||||
{trTab === 'plan' && mode === 'browse' && (
|
||||
<div className="absolute inset-0 z-30 bg-[color:var(--m-bg)] bg-[image:var(--m-scr)]">
|
||||
<PlacesBrowser planner={planner} shell={shell} />
|
||||
</div>
|
||||
)}
|
||||
{/*
|
||||
The stage lives at z-20, below the day chips at z-25, which is the whole
|
||||
of the stage picker: the chips belong to the shell and were only ever
|
||||
hidden because non-plan panels cover them at z-30.
|
||||
*/}
|
||||
{trTab === 'roadtrip' && rtView === 'list' && (
|
||||
<div className="absolute inset-0 z-20 bg-[color:var(--m-bg)] bg-[image:var(--m-scr)]">
|
||||
<TabPanel planner={planner} shell={shell} tab={trTab} />
|
||||
</div>
|
||||
)}
|
||||
{trTab === 'roadtrip' && rtView === 'map' && (
|
||||
<TabPanel planner={planner} shell={shell} tab={trTab} />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{trTab !== 'plan' && (
|
||||
{!MAP_TABS.has(trTab) && (
|
||||
<div className="absolute inset-0 z-30 bg-[color:var(--m-bg)] bg-[image:var(--m-scr)]">
|
||||
<TabPanel planner={planner} shell={shell} tab={trTab} />
|
||||
</div>
|
||||
@@ -411,10 +494,11 @@ export default function MTripShell({
|
||||
})}
|
||||
</div>
|
||||
{/* Drop the day filter and show the whole trip (#2257). Map only: the
|
||||
plan timeline is single-day, so there is nothing to widen there.
|
||||
Stays mounted while a day is active rather than appearing on
|
||||
selection, which would shove the rail sideways under the thumb. */}
|
||||
{view === 'map' && (
|
||||
plan timeline and the road trip chain are both single-day, so there is
|
||||
nothing to widen there. Stays mounted while a day is active rather than
|
||||
appearing on selection, which would shove the rail sideways under the
|
||||
thumb. On the road trip map it means the whole drive in its day colours. */}
|
||||
{mapFront && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleAllDays}
|
||||
@@ -554,6 +638,37 @@ export default function MTripShell({
|
||||
</GlassSegment>
|
||||
)}
|
||||
|
||||
{/* The stage's own header: the day it shows, and a way into the figures
|
||||
behind it. A button rather than the plugin tabs' inert pill, because it
|
||||
is the only entry to the driving settings, and the right slot belongs to
|
||||
the list ⇄ map switch, same as in the plan tab.
|
||||
|
||||
The day and the distance are badges rather than one line joined with a
|
||||
dot, so each reads as a figure of its own. Both stay neutral: the active
|
||||
day chip right below is already the filled pill with the same label, and
|
||||
a second one here would compete with it. The button names itself, because
|
||||
a screen reader runs the texts of pills side by side together. */}
|
||||
{trTab === 'roadtrip' && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => openSheet('rtinfo')}
|
||||
aria-label={rtHeaderLabel || undefined}
|
||||
className="absolute left-[52px] right-[52px] top-1/2 mx-auto flex h-[34px] w-fit max-w-full -translate-y-1/2 items-center gap-[5px] rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] px-[10px] backdrop-blur-[24px] backdrop-saturate-[1.7]"
|
||||
>
|
||||
<Route size={14} strokeWidth={2} className="flex-none text-m-muted" aria-hidden="true" />
|
||||
{rtHeaderLabel ? (
|
||||
<>
|
||||
{rtHeaderDay && <MBadge size="sm">{rtHeaderDay}</MBadge>}
|
||||
{/* Unit symbols keep their case: m and M are different units. */}
|
||||
{rtHeaderDistance && <MBadge size="sm" caps={false}>{rtHeaderDistance}</MBadge>}
|
||||
</>
|
||||
) : (
|
||||
<span className="min-w-0 truncate text-[0.8125rem] font-semibold text-m-ink">{t('roadtrip.title')}</span>
|
||||
)}
|
||||
<SlidersHorizontal size={13} strokeWidth={2} className="flex-none text-m-faint" aria-hidden="true" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
{trTab === 'dateien' && (
|
||||
<div className="absolute left-1/2 top-1/2 flex -translate-x-1/2 -translate-y-1/2 items-center gap-[7px]">
|
||||
<PrimaryPill icon={<Upload size={13} strokeWidth={2.2} />} label={t('common.upload')} onClick={() => setUploadFilesSignal(s => s + 1)} />
|
||||
@@ -581,13 +696,16 @@ export default function MTripShell({
|
||||
)
|
||||
})()}
|
||||
|
||||
{trTab === 'plan' ? (
|
||||
{/* Same slot, same markup, same icons in both map tabs, so the switch does
|
||||
not move or change shape when the tab does. The two views stay separate
|
||||
states: coupling them would drag one tab into the other's half. */}
|
||||
{MAP_TABS.has(trTab) ? (
|
||||
<MIconBtn
|
||||
ariaLabel={view === 'plan' ? t('mobileTrip.mapView') : t('mobileTrip.listView')}
|
||||
onClick={toggleView}
|
||||
ariaLabel={mapFront ? t('mobileTrip.listView') : t('mobileTrip.mapView')}
|
||||
onClick={trTab === 'roadtrip' ? toggleRtView : toggleView}
|
||||
className="backdrop-blur-[24px] backdrop-saturate-[1.7]"
|
||||
>
|
||||
{view === 'plan' ? <MapIcon size={18} strokeWidth={2} /> : <List size={18} strokeWidth={2} />}
|
||||
{mapFront ? <List size={18} strokeWidth={2} /> : <MapIcon size={18} strokeWidth={2} />}
|
||||
</MIconBtn>
|
||||
) : (
|
||||
<span className="w-[38px] flex-none" />
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { DOCK_CAP, DOCK_PRIORITY, dockTabIds, pickDockTabs } from './dockTabs'
|
||||
|
||||
// FE-MOB-DOCK-001 to FE-MOB-DOCK-008
|
||||
|
||||
/** Alles, was ein voll ausgestatteter Trip anbieten kann, in der Reihenfolge des Docks. */
|
||||
const ALL = ['plan', 'roadtrip', 'transports', 'buchungen', 'finanzplan', 'listen']
|
||||
|
||||
const ids = (enabled: string[]) => pickDockTabs(new Set(enabled)).map((tab) => tab.id)
|
||||
|
||||
describe('pickDockTabs', () => {
|
||||
it('FE-MOB-DOCK-001: five seats beside More, so the packing list gives way to the drive', () => {
|
||||
// Ein sechster Kreis laesst 3px Abstand, auf die kein Daumen zielt.
|
||||
expect(DOCK_CAP).toBe(5)
|
||||
expect(ids(ALL)).toEqual(['plan', 'roadtrip', 'transports', 'buchungen', 'finanzplan'])
|
||||
expect(ids(ALL)).not.toContain('listen')
|
||||
})
|
||||
|
||||
it('FE-MOB-DOCK-002: without the road trip the packing list has its seat back', () => {
|
||||
expect(ids(ALL.filter((id) => id !== 'roadtrip'))).toEqual([
|
||||
'plan',
|
||||
'transports',
|
||||
'buchungen',
|
||||
'finanzplan',
|
||||
'listen',
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-MOB-DOCK-003: priority decides who is cut, not the order the tabs were enabled', () => {
|
||||
const scrambled = ['listen', 'finanzplan', 'roadtrip', 'plan']
|
||||
expect(ids(scrambled)).toEqual(['plan', 'roadtrip', 'finanzplan', 'listen'])
|
||||
})
|
||||
|
||||
it('FE-MOB-DOCK-004: a trip with few sections gets few seats, never padded', () => {
|
||||
expect(ids(['plan', 'listen'])).toEqual(['plan', 'listen'])
|
||||
expect(ids([])).toEqual([])
|
||||
})
|
||||
|
||||
it('FE-MOB-DOCK-005: a plugin tab never takes a seat, it belongs in the More sheet', () => {
|
||||
expect(ids(['plugin:trip-todos', 'plan'])).toEqual(['plan'])
|
||||
expect(ids(['plugin:trip-todos', 'plugin:weather'])).toEqual([])
|
||||
})
|
||||
|
||||
it('FE-MOB-DOCK-006: a seat is the priority entry itself, icon and all', () => {
|
||||
// Das Dock zeichnet den Kreis aus tab.icon; eine umgebaute Kopie ohne Icon bliebe leer.
|
||||
expect(pickDockTabs(new Set(ALL))).toEqual(DOCK_PRIORITY.slice(0, DOCK_CAP))
|
||||
expect(pickDockTabs(new Set(ALL))[1]).toBe(DOCK_PRIORITY[1])
|
||||
})
|
||||
})
|
||||
|
||||
describe('dockTabIds', () => {
|
||||
it('FE-MOB-DOCK-007: names exactly the ids that got a seat, so the More sheet leaves them out', () => {
|
||||
const enabled = new Set(ALL)
|
||||
expect([...dockTabIds(enabled)]).toEqual(pickDockTabs(enabled).map((tab) => tab.id))
|
||||
expect(dockTabIds(enabled).has('listen')).toBe(false)
|
||||
expect(dockTabIds(enabled).has('roadtrip')).toBe(true)
|
||||
})
|
||||
|
||||
it('FE-MOB-DOCK-008: never names more than the dock can hold', () => {
|
||||
expect(dockTabIds(new Set([...ALL, 'plugin:trip-todos'])).size).toBe(DOCK_CAP)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Map as MapIcon, TrainFront, Ticket, Wallet, PackageCheck, Route } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
|
||||
/**
|
||||
* Which trip sections get a seat in the phone dock, and in which order.
|
||||
*
|
||||
* The dock is a fixed 62px pill with `justify-around` and no overflow, so seats are
|
||||
* a real budget, not a preference: at 375px it measures 343px, 315px of it usable,
|
||||
* and every circle is 42px. Five sections plus More leave 9px between them. A sixth
|
||||
* takes that down to 3px, which is not a gap any thumb can aim at.
|
||||
*
|
||||
* Hence DOCK_CAP. Everything past it surfaces as a tile in the More sheet, which is
|
||||
* where files, collaboration and plugin tabs have always lived.
|
||||
*
|
||||
* This list is the ONE source for both sides. It used to be two hand-kept copies
|
||||
* (one here, one in MMehrSheet), and extending only one of them showed the same tab
|
||||
* in the dock AND as a tile.
|
||||
*/
|
||||
export const DOCK_PRIORITY: { id: string; icon: LucideIcon }[] = [
|
||||
{ id: 'plan', icon: MapIcon },
|
||||
{ id: 'roadtrip', icon: Route },
|
||||
{ id: 'transports', icon: TrainFront },
|
||||
{ id: 'buchungen', icon: Ticket },
|
||||
{ id: 'finanzplan', icon: Wallet },
|
||||
{ id: 'listen', icon: PackageCheck },
|
||||
]
|
||||
|
||||
/** Seats beside the More button. */
|
||||
export const DOCK_CAP = 5
|
||||
|
||||
/**
|
||||
* The dock's seats for a trip, given the tabs that are actually enabled.
|
||||
*
|
||||
* Priority order decides who is cut, not enabled order: with the road trip addon on,
|
||||
* the packing list moves into the More sheet rather than the drive never getting a
|
||||
* seat. Turning the addon off puts it straight back.
|
||||
*/
|
||||
export function pickDockTabs(enabledTabIds: ReadonlySet<string>): { id: string; icon: LucideIcon }[] {
|
||||
return DOCK_PRIORITY.filter(tab => enabledTabIds.has(tab.id)).slice(0, DOCK_CAP)
|
||||
}
|
||||
|
||||
/** The ids that got a seat, for the More sheet to leave out. */
|
||||
export function dockTabIds(enabledTabIds: ReadonlySet<string>): Set<string> {
|
||||
return new Set(pickDockTabs(enabledTabIds).map(tab => tab.id))
|
||||
}
|
||||
@@ -1,12 +1,142 @@
|
||||
import { useState } from 'react'
|
||||
import { useCallback, useLayoutEffect, useMemo, useRef, useState, type RefObject } from 'react'
|
||||
import { MapViewAuto } from '../../../../components/Map/MapViewAuto'
|
||||
import { MapCompassPill, type CompassMap } from '../../../../components/Map/MapCompassPill'
|
||||
import { MAP_LAYER_SWITCHER_INSET, MAP_ROUND_CONTROL_SIZE } from '../../../../components/Map/MapLayerSwitcher'
|
||||
import { TripRouteOverviewPill, TripRouteOverviewPanel } from '../../../../components/Map/TripRouteOverview'
|
||||
import { DawarichTrailPill } from '../../../../components/Map/DawarichTrailPill'
|
||||
import PoiCategoryPill from '../../../../components/Map/PoiCategoryPill'
|
||||
import { usePoiExplore } from '../../../../components/Map/usePoiExplore'
|
||||
import { useMergedMapPois } from '../../../../components/Map/useMergedMapPois'
|
||||
import { firstStopOfPlace, stageOf } from '../../../../components/Roadtrip/roadtripRowModel'
|
||||
import { stageMapData } from '../../../../components/Roadtrip/stageMap'
|
||||
import { useRoadtripSettings } from '../../../../hooks/useRoadtripSettings'
|
||||
import { useSettingsStore } from '../../../../store/settingsStore'
|
||||
import { useTripStore } from '../../../../store/tripStore'
|
||||
import { RT_ALT_BAR_LIFT } from '../roadtrip/useMRtAlternatives'
|
||||
import type { MMapAreaProps } from '../MTripShell'
|
||||
import type { Poi } from '../../../../components/Map/poiCategories'
|
||||
import type { ViewportPadding } from '../../../../utils/mapViewport'
|
||||
|
||||
/** One array, so an explore set switched off does not move every pin on the stage. */
|
||||
const NO_POIS: Poi[] = []
|
||||
|
||||
/**
|
||||
* The compass stands one gap to the right of the base-layer switcher both engines draw
|
||||
* in the bottom left corner. Worked out from the switcher's own numbers rather than
|
||||
* written down as 70, so moving or resizing the switcher carries the compass along.
|
||||
*/
|
||||
const COMPASS_LEFT = MAP_LAYER_SWITCHER_INSET + MAP_ROUND_CONTROL_SIZE + 8
|
||||
|
||||
/** The safe-area insets at the top and the bottom of the screen, in pixels. */
|
||||
interface SafeInsets {
|
||||
top: number
|
||||
bottom: number
|
||||
}
|
||||
|
||||
const NO_INSETS: SafeInsets = { top: 0, bottom: 0 }
|
||||
|
||||
/**
|
||||
* The safe-area insets as numbers, read off a probe that is padded by them.
|
||||
*
|
||||
* The frame handed to the map engine is pixels, and `env()` only resolves inside CSS. On a
|
||||
* phone with a notch the chrome sits a status bar lower (and a home indicator higher) than
|
||||
* its classes spell out, so a frame worked out without the insets would put the far end of
|
||||
* a leg under the day chips. A computed padding is where the browser hands the resolved
|
||||
* inset back. Read on mount and again on a resize, which is what turning the phone does.
|
||||
*/
|
||||
function useSafeInsets(probe: RefObject<HTMLElement | null>): SafeInsets {
|
||||
const [insets, setInsets] = useState<SafeInsets>(NO_INSETS)
|
||||
useLayoutEffect(() => {
|
||||
const read = () => {
|
||||
const el = probe.current
|
||||
if (!el) return
|
||||
const style = window.getComputedStyle(el)
|
||||
const top = Number.parseFloat(style.paddingTop) || 0
|
||||
const bottom = Number.parseFloat(style.paddingBottom) || 0
|
||||
setInsets(prev => (prev.top === top && prev.bottom === bottom ? prev : { top, bottom }))
|
||||
}
|
||||
read()
|
||||
window.addEventListener('resize', read)
|
||||
return () => window.removeEventListener('resize', read)
|
||||
}, [probe])
|
||||
return insets
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the roads offered for a leg are framed: in the strip of map between the day chips
|
||||
* and the alternatives bar, rather than behind either of them.
|
||||
*
|
||||
* Both engines fit a phone with a flat margin that knows nothing of this shell's bars, and
|
||||
* with the picker open those cover most of the screen: that margin would leave the leg's
|
||||
* ends and their time pills under the chips and under a 174px bar. The numbers are the
|
||||
* ones the classes on this screen are built from, so a change there has to be carried here.
|
||||
*
|
||||
* Top: the safe area, then `--m-safe-top`'s own 12px, the chip rail's 50px offset under it
|
||||
* and its 42px height, then a 12px gap so a time pill at the far end is not flush against
|
||||
* the rail. The search bar that sits below the rail on the stage steps away while the
|
||||
* picker is open, so the rail is the lowest chrome up there.
|
||||
*
|
||||
* Bottom: the safe area, the dock's 74px (62px tall, 12px off the bottom) and the bar's
|
||||
* lift (its height and the 15px gap between the dock and its foot). That is the very line
|
||||
* `--bottom-nav-h` puts the round controls' band on, so the frame ends where they begin,
|
||||
* and they only take the two corners of it.
|
||||
*
|
||||
* The sides keep the 20px both engines already give a phone: nothing floats there.
|
||||
*/
|
||||
function alternativesFitPadding(insets: SafeInsets): ViewportPadding {
|
||||
return {
|
||||
top: insets.top + 12 + 50 + 42 + 12,
|
||||
right: 20,
|
||||
bottom: insets.bottom + 74 + RT_ALT_BAR_LIFT,
|
||||
left: 20,
|
||||
}
|
||||
}
|
||||
|
||||
type FocusPoints = readonly [number, number][]
|
||||
|
||||
/** A camera focus the planner is holding, and the day that was on screen when it arrived. */
|
||||
interface HeldFocus {
|
||||
points: FocusPoints
|
||||
dayId: number | null
|
||||
live: boolean
|
||||
/**
|
||||
* Every array held before this one. Weak, so the offers of a long session are not kept
|
||||
* alive by it. Only ever added to, and adding twice changes nothing, so a render React
|
||||
* runs twice or throws away leaves it saying the same thing.
|
||||
*/
|
||||
shown: WeakSet<FocusPoints>
|
||||
}
|
||||
|
||||
/**
|
||||
* Lets go of a pending focus once the day moves off the one it arrived with, and never
|
||||
* takes one back that the planner hands over a second time.
|
||||
*
|
||||
* The planner keeps a point it was asked to show until its next routing round, whatever
|
||||
* day is picked in the meantime, and a pending focus wins over the stage's own frame. So
|
||||
* after "show on map" every stage swiped to afterwards stayed on that one point instead of
|
||||
* framing its drive. Coming back to the day does not bring the point back either: the
|
||||
* traveller has moved on since, and the camera belongs to the stage they came back to.
|
||||
*
|
||||
* The same kept point is also what the planner falls back to once the fuel offers or the
|
||||
* other roads for a leg close, as the very array it handed over before. Read as a new
|
||||
* focus, closing either one flew the camera back to that old stop, on another day's stage
|
||||
* too. So only an array never held before is a new focus. The one exception is the open
|
||||
* picker's roads (`openRoads`): fuel offers asked for over an open picker take the camera
|
||||
* from it, and once they close the picker is still asking about its leg.
|
||||
*/
|
||||
function holdFocus(
|
||||
prev: HeldFocus,
|
||||
points: FocusPoints,
|
||||
dayId: number | null,
|
||||
openRoads: FocusPoints,
|
||||
): HeldFocus {
|
||||
if (prev.points !== points) {
|
||||
prev.shown.add(prev.points)
|
||||
return { points, dayId, live: points === openRoads || !prev.shown.has(points), shown: prev.shown }
|
||||
}
|
||||
if (prev.live && prev.dayId !== dayId) return { ...prev, dayId, live: false }
|
||||
return prev
|
||||
}
|
||||
|
||||
/**
|
||||
* Fullscreen map layer of the mobile trip screen (plan tab). Stays mounted for
|
||||
@@ -18,14 +148,17 @@ import type { MMapAreaProps } from '../MTripShell'
|
||||
* setting) with the full desktop feature set: clusters, photo/icon markers,
|
||||
* day-order badges, dashed day route, transport overlays per booking, POI
|
||||
* explore markers and long-press → add place. Only the floating chrome is
|
||||
* mobile: the POI bar spans the full width below the day-chip rail, and the two
|
||||
* round controls share the band just above the dock — the compass on the left,
|
||||
* the map's built-in three-state locate button on the right, both riding the
|
||||
* --bottom-nav-h contract the map already reads so they cannot drift apart.
|
||||
* mobile: the POI bar spans the full width below the day-chip rail, and the round
|
||||
* controls share one band above the dock: the map's own base-layer switcher
|
||||
* with the compass beside it on the left, the map's built-in three-state locate
|
||||
* button on the right, all riding the --bottom-nav-h contract the map already reads
|
||||
* so they cannot drift apart. The map credit sits under that band, alone in the
|
||||
* bottom right corner.
|
||||
*
|
||||
* Marker data honours the shared places category filter (#1541) because
|
||||
* planner.mapPlaces is derived from tripStore's placesCategoryFilter — the
|
||||
* same set the places browser renders, so the two can't desync.
|
||||
* On the plan tab, marker data honours the shared places category filter (#1541)
|
||||
* because planner.mapPlaces is derived from tripStore's placesCategoryFilter, the
|
||||
* same set the places browser renders, so the two can't desync. The road trip
|
||||
* stage draws the stops of its chain instead, see `stagePlaces`.
|
||||
*/
|
||||
export default function MMapArea({ planner, shell }: MMapAreaProps) {
|
||||
const poi = usePoiExplore()
|
||||
@@ -33,33 +166,209 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
|
||||
const poiPillEnabled = useSettingsStore(s => s.settings.map_poi_pill_enabled) !== false
|
||||
const distanceUnit = useSettingsStore(s => s.settings.distance_unit)
|
||||
|
||||
const mapActive = shell.view === 'map'
|
||||
const dayColorsOn = useRoadtripSettings(s => s.roadtrip_day_colors, planner.tripId)
|
||||
const tripPlaces = useTripStore(s => s.places)
|
||||
|
||||
// One instance, two tabs. `mapFront` is true whenever the map is the front layer
|
||||
// in either of them, so the floating chrome below keys off that rather than off
|
||||
// `view`, which only ever meant the plan tab.
|
||||
const mapActive = shell.mapFront
|
||||
const onStage = shell.trTab === 'roadtrip'
|
||||
|
||||
// The stage the road trip tab is looking at, and what the map draws for it. Passed
|
||||
// through unconditionally while that tab is open, list half included: `focusPoints`
|
||||
// going array → undefined → array is two dependency changes to React, and the
|
||||
// second one would throw away whatever the traveller had panned to.
|
||||
//
|
||||
// Memoised on what the stage is made of rather than rebuilt per render: the shell
|
||||
// re-renders on every store write, a settings toggle included, and a fresh
|
||||
// `focusPoints` array reframes the camera while fresh lines and places set their
|
||||
// GeoJSON sources again. On the stage that also kept the GL style busy, which is how
|
||||
// the satellite switch came to miss every tap there.
|
||||
const stage = useMemo(
|
||||
() => onStage ? stageOf(planner.roadtripRoutes.days, planner.selectedDayId) : null,
|
||||
[onStage, planner.roadtripRoutes.days, planner.selectedDayId],
|
||||
)
|
||||
const stageMap = useMemo(
|
||||
() => onStage ? stageMapData(planner.roadtripRoutes, stage, !!dayColorsOn) : null,
|
||||
[onStage, planner.roadtripRoutes, stage, dayColorsOn],
|
||||
)
|
||||
|
||||
// Only what the stage carries, so a trip's other 200 pins stay off a screen that
|
||||
// is answering one question. Without a stage (the all-days view) every place a stored
|
||||
// visit stops at comes back, which is what the drive looks like end to end.
|
||||
//
|
||||
// Out of the trip store rather than `planner.mapPlaces`, which is the plan tab's map.
|
||||
// That list drops the pins of every day its declutter has put away, and this tab moves
|
||||
// the day without touching the declutter (a swipe, or a chip tap while the plan tab sits
|
||||
// on its list): after the all days switch and back, the next stage picked came up with
|
||||
// most of its pins missing. It also runs the places browser's filters, where 'unplanned'
|
||||
// hides every stop a drive has, and it lacks the service stops hidden from the day lists
|
||||
// that the chain still draws. The category filter stays off the stage too, on purpose:
|
||||
// the stage is one day's chain on a map, and a stop the chain lists with no pin under its
|
||||
// line, hidden by a control on another tab, reads as a broken map rather than a filter.
|
||||
//
|
||||
// The all-days view reads the stored visits for the same reasons, not the planner's
|
||||
// planned list: that one is built from the day lists, which on a phone always leave out
|
||||
// a booked night and, with the setting off, the service stops, while the drive the routing
|
||||
// round draws still ends at that hotel and stops at that pump. Its pin is what opens the
|
||||
// stop, so a missing one left the stop out of reach from this view.
|
||||
const drivePlaceIds = useMemo(
|
||||
() => new Set(Object.values(planner.storedAssignments).flat().map(visit => visit.place_id)),
|
||||
[planner.storedAssignments],
|
||||
)
|
||||
const stagePlaces = useMemo(() => {
|
||||
const pinned = stageMap && stage ? stageMap.placeIds : drivePlaceIds
|
||||
return tripPlaces.filter(p => p.lat != null && p.lng != null && pinned.has(p.id))
|
||||
}, [stageMap, stage, tripPlaces, drivePlaceIds])
|
||||
|
||||
// Computed during render rather than in an effect, so the frame handed over below is
|
||||
// already the right one in the render a day change happens in. See holdFocus.
|
||||
const [heldFocus, setHeldFocus] = useState<HeldFocus>(
|
||||
() => ({ points: planner.mapFocusPoints, dayId: planner.selectedDayId, live: true, shown: new WeakSet() }),
|
||||
)
|
||||
const focus = holdFocus(heldFocus, planner.mapFocusPoints, planner.selectedDayId, planner.alternativeFocusPoints)
|
||||
if (focus !== heldFocus) setHeldFocus(focus)
|
||||
const focusPending = focus.live && planner.mapFocusPoints.length > 0
|
||||
|
||||
// Handed over only once there are roads to frame, not as soon as the picker opens: the
|
||||
// engines refit whatever they hold when this padding changes, and while the router is
|
||||
// still thinking that is the stage, which would be flown out to a smaller frame just
|
||||
// before the answer flies it to the leg. So the padding and the roads arrive in one
|
||||
// render and the camera moves once, and on close both go in one render as well.
|
||||
// Memoised for the reason the stage data is, the shell re-rendering on every store write.
|
||||
const insetProbe = useRef<HTMLSpanElement>(null)
|
||||
const insets = useSafeInsets(insetProbe)
|
||||
const framingOffers = onStage && planner.alternativeOverlays.length > 0
|
||||
const fitPadding = useMemo(
|
||||
() => (framingOffers ? alternativesFitPadding(insets) : undefined),
|
||||
[framingOffers, insets],
|
||||
)
|
||||
|
||||
/**
|
||||
* A pin on the road trip tab opens its stop: the sheet the chain row opens, not the
|
||||
* place inspector.
|
||||
*
|
||||
* The plan tab's marker click moves the planner's place selection, and the inspector
|
||||
* opens off that selection, so a tap on a stop of the drive came up with the plan tab's
|
||||
* card over the map and no word about the stop. Over a stage the stop is found on that
|
||||
* card, over the whole drive on the first routed day that stops there (firstStopOfPlace).
|
||||
* A pin no routed day stops at still gets the inspector: the road trip has nothing to
|
||||
* say about it, and the place does.
|
||||
*
|
||||
* One handler for the life of the map, reading the latest values through a ref. Leaflet
|
||||
* rebuilds every marker whenever this identity moves, and the shell re-renders on every
|
||||
* store write and on every sheet it opens, this handler's own included.
|
||||
*/
|
||||
const latest = useRef({ planner, shell, stage })
|
||||
latest.current = { planner, shell, stage }
|
||||
const openStagePin = useCallback((placeId?: number) => {
|
||||
const { planner: now, shell: chrome, stage: card } = latest.current
|
||||
const stop = placeId == null ? null : firstStopOfPlace(card ? [card] : now.roadtripRoutes.days, placeId)
|
||||
if (stop) chrome.openSheet('rtstop', { dayId: stop.ownerDayId, assignmentId: stop.assignmentId })
|
||||
else now.handleMarkerClick(placeId)
|
||||
}, [])
|
||||
|
||||
/**
|
||||
* The pins, and they are not the same question on the two tabs.
|
||||
*
|
||||
* On the stage: what the corridor search found and what the fuel search is offering,
|
||||
* both measured along the drive. The explore categories stay off it, and so does their
|
||||
* bar. "What is around this piece of map" has no relationship to a route, and two
|
||||
* search bars stacked over a 375px map is the clutter this tab exists to avoid. The
|
||||
* plan tab is one tap away and shows the same map.
|
||||
*
|
||||
* Merged through the planner's own hook rather than concatenated here, because the
|
||||
* sets overlap: the same petrol station found twice would be two pins on one roof.
|
||||
*/
|
||||
/**
|
||||
* The vias the phone map draws: on a stage, only the night that belongs to it.
|
||||
*
|
||||
* A night pause is a pill with a moon and a day number, drawn where one travel day
|
||||
* ends. The markers are built from the WHOLE drive (`automaticPoints`), which is right
|
||||
* for the desktop rail and for the all-days view here, but a stage shows one day: with
|
||||
* the unfiltered list, day 1 carried day 2's pill as well, in the middle of a map that
|
||||
* is otherwise entirely day 1. Two ends on a map that draws one is a question, not a
|
||||
* label.
|
||||
*
|
||||
* So on a stage the pill is kept only where its day is the day on screen, and off a
|
||||
* stage the list is left alone, because in the all-days view every night does belong to
|
||||
* a line that is drawn. `nightPause.day` is the day number the marker was built from
|
||||
* (see `useAutomaticDayPoints`), which is the same number the stage carries.
|
||||
*/
|
||||
const mapVias = useMemo(() => {
|
||||
const vias = onStage ? planner.roadtripMapVias : planner.routeVias
|
||||
if (!vias || !stage) return vias
|
||||
return vias.filter(v => !v.nightPause || v.nightPause.day === stage.dayNumber)
|
||||
}, [onStage, planner.roadtripMapVias, planner.routeVias, stage])
|
||||
|
||||
const pois = useMergedMapPois(
|
||||
onStage ? planner.roadtripCorridor.visible : null,
|
||||
onStage ? NO_POIS : poi.pois,
|
||||
planner.refuel.offered,
|
||||
)
|
||||
|
||||
return (
|
||||
// `isolate` keeps the map's internal z-indexes (Leaflet panes, the z-1000
|
||||
// locate button) inside this layer so they can never paint over the plan
|
||||
// timeline (z-10) or the browse/tab overlays (z-30) above it.
|
||||
// The dock is 62px tall at safe-bottom + 12, so a 74px --bottom-nav-h puts
|
||||
// the round controls (which add their own 12px) a dock's gap above it —
|
||||
// close enough to the thumb to reach one-handed, clear of the dock itself.
|
||||
<div className="absolute inset-0 isolate overflow-hidden bg-[color:var(--m-mapb)] [--bottom-nav-h:calc(env(safe-area-inset-bottom,0px)+74px)]">
|
||||
//
|
||||
// --m-map-floor is the top edge of whatever the map ends at: the dock, 62px tall at
|
||||
// safe-bottom + 12, or the alternatives bar when the picker puts one over it, which is
|
||||
// what --m-stage-lift adds. The round controls sit straight on that floor and add
|
||||
// their own 12px, close enough to the thumb to reach one-handed. Everything that reads
|
||||
// --bottom-nav-h (the compass, both engines' locate button and base-layer switcher,
|
||||
// the overview stack) follows on its own. The band used to float a further 38px up to
|
||||
// leave the corner under it to the map credit; the phone map carries no visible credit
|
||||
// any more (see mobile.css), so that row would now only be a gap over the dock.
|
||||
//
|
||||
// The metrics are classes rather than an inline --bottom-nav-h, and the lift is its
|
||||
// OWN variable folded into them: the compass band below is identified by being the
|
||||
// one element that sets that name inline, and a second one would make that ambiguous.
|
||||
<div
|
||||
className="absolute inset-0 isolate overflow-hidden bg-[color:var(--m-mapb)] [--m-map-floor:calc(env(safe-area-inset-bottom,0px)+74px+var(--m-stage-lift,0px))] [--bottom-nav-h:var(--m-map-floor)]"
|
||||
// A stage bar used to stand over the dock for the whole of the road trip tab, and the
|
||||
// floor cleared its 61px plus a gap the year round. It is gone, so the only thing
|
||||
// left in that slot is the bar the picker raises while other ways of driving a leg
|
||||
// are on offer, and the floor clears that one the same way: its height plus the gap
|
||||
// it keeps from the dock, so the round controls land above it rather than on its
|
||||
// top edge.
|
||||
style={{
|
||||
['--m-stage-lift' as string]: onStage && mapActive && planner.routeAlternatives.open
|
||||
? `${RT_ALT_BAR_LIFT}px`
|
||||
: '0px',
|
||||
}}
|
||||
>
|
||||
{/* Measures the safe area for the alternatives frame, see useSafeInsets. Out of the
|
||||
flow and invisible, so it takes no room and catches no tap. */}
|
||||
<span
|
||||
ref={insetProbe}
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none invisible absolute left-0 top-0 pb-[env(safe-area-inset-bottom,0px)] pt-[env(safe-area-inset-top,0px)]"
|
||||
/>
|
||||
<MapViewAuto
|
||||
tripId={planner.tripId}
|
||||
dawarichTrack={planner.dawarichTrail.track}
|
||||
places={planner.mapPlaces}
|
||||
dayPlaces={planner.dayPlaces}
|
||||
route={planner.overviewActive ? planner.tripOverview.lines : planner.route}
|
||||
routeColors={planner.overviewActive ? planner.tripOverview.lineColors : undefined}
|
||||
focusPoints={planner.overviewActive ? planner.tripOverview.focusPoints : undefined}
|
||||
routeVias={planner.routeVias}
|
||||
showTransitRoutes={planner.transitRoutesShown}
|
||||
places={stageMap ? stagePlaces : planner.mapPlaces}
|
||||
dayPlaces={onStage ? undefined : planner.dayPlaces}
|
||||
route={stageMap ? stageMap.lines : planner.overviewActive ? planner.tripOverview.lines : planner.route}
|
||||
routeColors={stageMap ? stageMap.lineColors : planner.overviewActive ? planner.tripOverview.lineColors : undefined}
|
||||
accessLines={stageMap ? stageMap.accessLines : undefined}
|
||||
// A hit somebody tapped in the search sheet, a stop shown from its sheet, or the
|
||||
// stations the fuel search is offering take the camera while their day is on
|
||||
// screen; with nothing pending the stage frames itself.
|
||||
focusPoints={stageMap
|
||||
? (focusPending ? planner.mapFocusPoints : stageMap.focusPoints)
|
||||
: planner.overviewActive ? planner.tripOverview.focusPoints : undefined}
|
||||
routeVias={mapVias}
|
||||
showTransitRoutes={onStage ? false : planner.transitRoutesShown}
|
||||
// The route toggle belongs to one day, so the map needs that day to know
|
||||
// which automated transports may ride it (#2019).
|
||||
days={planner.days}
|
||||
selectedDayId={planner.selectedDayId}
|
||||
routeSegments={planner.overviewActive ? planner.tripOverview.segments : planner.routeSegments}
|
||||
routeSegments={onStage ? undefined : planner.overviewActive ? planner.tripOverview.segments : planner.routeSegments}
|
||||
selectedPlaceId={planner.selectedPlaceId}
|
||||
onMarkerClick={planner.handleMarkerClick}
|
||||
onMarkerClick={onStage ? openStagePin : planner.handleMarkerClick}
|
||||
// Tap on empty map = deselect, same contract as desktop.
|
||||
onMapClick={planner.handleMapClick}
|
||||
// The chip rail names a day at all times on mobile, so a place dropped on
|
||||
@@ -76,17 +385,33 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
|
||||
// Transport overlay tap → the mobile transport detail sheet (desktop
|
||||
// routes this through mapTransportDetail into the day sidebar instead).
|
||||
onReservationClick={(rid: number) => shell.openSheet('transport', { reservationId: rid })}
|
||||
pois={poi.pois}
|
||||
onPoiClick={marker => planner.openAddPlaceFromPoi(marker, planner.selectedDayId)}
|
||||
pois={pois}
|
||||
// On the stage, through the road trip's own door: it recognises a corridor hit by
|
||||
// the distance it carries and sends it to the draft sheet with the stop kind, the
|
||||
// stay and the position in the chain already worked out. The plan tab has no
|
||||
// chain to place anything in, so there it stays the plain place form.
|
||||
onPoiClick={onStage
|
||||
? planner.handlePoiClick
|
||||
: marker => planner.openAddPlaceFromPoi(marker, planner.selectedDayId)}
|
||||
onViewportChange={poi.onViewportChange}
|
||||
onMapReady={setGlMap}
|
||||
// Other ways of driving the leg the stage asked about, and the one lit up.
|
||||
alternativeRoutes={onStage ? planner.alternativeOverlays : undefined}
|
||||
activeAlternative={onStage ? planner.highlightedAlternative : undefined}
|
||||
// A tap on a road or its time pill only lights it; the bar's confirm takes it. The
|
||||
// desk hands `chooseRouteAlternative` in here and previews on hover, but glass has
|
||||
// no hover, so the same wiring would save a via on the very first touch of a line.
|
||||
// No highlight handler either: a touch fires emulated mouse enter and leave events,
|
||||
// and the leave would put out the road the tap has just lit.
|
||||
onChooseAlternative={onStage ? planner.setHighlightedAlternative : undefined}
|
||||
fitPadding={fitPadding}
|
||||
/>
|
||||
|
||||
{/* Floating map chrome — only while the map view is front-most. The POI bar
|
||||
sits below the day-chip rail (safe-top + 50px + ~42px chip height) and
|
||||
takes the full width between the screen margins, so its segments are
|
||||
the same size as everything else the thumb aims at on this screen. */}
|
||||
{mapActive && poiPillEnabled && (
|
||||
{mapActive && !onStage && poiPillEnabled && (
|
||||
<div className="pointer-events-none absolute left-4 right-4 z-[25] flex flex-col items-center gap-2 top-[calc(var(--m-safe-top,12px)+96px)]">
|
||||
<PoiCategoryPill
|
||||
fullWidth
|
||||
@@ -100,24 +425,25 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Compass — GL maps only (Leaflet can't rotate). Bottom-left, mirroring
|
||||
the locate button's own `right: 12` off the same --bottom-nav-h, so the
|
||||
two round controls always sit on one line. Leaflet has no compass but
|
||||
puts its base-layer switcher in the same corner, so the band reads the
|
||||
same either way. */}
|
||||
{/* Compass, GL maps only (Leaflet cannot rotate). Both engines draw the base-layer
|
||||
switcher in the bottom left corner, so the compass sits beside it rather than in
|
||||
the corner: at `left-3` it started 8px left of the switcher and ran on under it,
|
||||
reading as a second button showing through the frosted shell. Same
|
||||
--bottom-nav-h band as the locate button's `right: 12`, so the round controls
|
||||
still share one line. The left offset is inline because it is computed from the
|
||||
switcher's own numbers. */}
|
||||
{mapActive && glMap && (
|
||||
<div className="pointer-events-none absolute left-3 z-[25]" style={{ bottom: 'calc(var(--bottom-nav-h, 84px) + 12px)' }}>
|
||||
<div className="pointer-events-none absolute z-[25]" style={{ left: COMPASS_LEFT, bottom: 'calc(var(--bottom-nav-h, 84px) + 12px)' }}>
|
||||
<MapCompassPill map={glMap} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Whole-trip overview (#1736): the stages stack above their toggle on the right,
|
||||
clear of the round-controls band below it and of the compass and Leaflet's
|
||||
base-layer switcher, which both sit in the bottom-LEFT corner. The offset is
|
||||
Tailwind rather than inline because the compass band is identified by being
|
||||
the one element with an inline --bottom-nav-h, and a second would make that
|
||||
ambiguous. */}
|
||||
{mapActive && (!planner.roadtripActive || planner.dawarichEnabled) && (
|
||||
clear of the round-controls band below it and of the base-layer switcher and
|
||||
the compass, which both sit bottom left. The offset is Tailwind rather than
|
||||
inline because the compass band is identified by being the one element with
|
||||
an inline --bottom-nav-h, and a second would make that ambiguous. */}
|
||||
{mapActive && !onStage && (!planner.roadtripActive || planner.dawarichEnabled) && (
|
||||
<div className="pointer-events-none absolute left-3 right-3 z-[25] flex flex-col items-end gap-2 bottom-[calc(var(--bottom-nav-h,84px)+58px)]">
|
||||
{!planner.roadtripActive && planner.overviewActive && (
|
||||
<TripRouteOverviewPanel
|
||||
|
||||
@@ -0,0 +1,514 @@
|
||||
import { AlertTriangle, Bike, CarFront, Footprints, Fuel, Hourglass, Moon, Pin, Plus, RotateCcw, Shuffle, Sunrise, X, Zap } from 'lucide-react'
|
||||
import type { CSSProperties, ReactNode } from 'react'
|
||||
import MDancingTrek from '../../../components/MDancingTrek'
|
||||
import MIconBtn from '../../../components/MIconBtn'
|
||||
import { formatDurationShort, serviceColor } from '../../../../components/Roadtrip/roadtripModel'
|
||||
import { STOP_KIND_BY_KEY } from '../../../../components/Roadtrip/stopKinds'
|
||||
import { formatDistance } from '../../../../utils/units'
|
||||
import type { StopRow } from '../../../../components/Roadtrip/roadtripRowModel'
|
||||
import type { RefuelSearch } from '../../../../components/Roadtrip/useRefuelSearch'
|
||||
import { REFUEL_EMPTY_KEY, REFUEL_WORDS, refuelBandState, type RefuelCandidate } from '../../../../components/Roadtrip/refuelSuggestion'
|
||||
import type { DistanceUnit, RouteSegment, ScheduleWarning } from '@trek/shared/roadtrip'
|
||||
import type { TranslationFn } from '../../../../types'
|
||||
|
||||
/**
|
||||
* The four row types of the mobile drive chain, plus the two bands that interrupt it.
|
||||
*
|
||||
* What the desktop rail does in five stacked 8px badges per stop, this does in at most
|
||||
* two 10.5px marks: on touch there is no hover, so a badge nobody can explain is worse
|
||||
* than no badge. The rest of a stop's findings live in its sheet, written out as full
|
||||
* sentences. Which mark survives is decided in `roadtripRowModel.pickWarning`, not here.
|
||||
*
|
||||
* Few things in the chain react to a tap, and each looks like the control it is. A
|
||||
* destination row is its own tap target, a leg has one round button that asks for other
|
||||
* ways of driving it, and the dry band has its reserve lamp and the offers it brings
|
||||
* back. The drive pill, discs, marks, the night block and the day-end point carry no role
|
||||
* and no chevron, so nothing looks like a button that isn't one.
|
||||
*/
|
||||
|
||||
export interface RowChrome {
|
||||
t: TranslationFn
|
||||
unit: DistanceUnit
|
||||
}
|
||||
|
||||
/**
|
||||
* 30px disc: a number for a destination, the kind's colour for a service stop.
|
||||
*
|
||||
* With `onPickKind` it is also the control that switches between the two, which is what
|
||||
* the desktop rail does with its own disc. The disc is what changes, so it is its own
|
||||
* preview: tap the 3, pick the pump, and the 3 becomes an orange disc while everything
|
||||
* below it renumbers. The tap is stopped here rather than allowed to reach the row, which
|
||||
* opens the stop, and the 34px column the row gives this disc is the whole target.
|
||||
*/
|
||||
function Disc({ row, t, onPickKind }: { row: StopRow; t: TranslationFn; onPickKind?: () => void }) {
|
||||
const kind = row.stop.stopType ? STOP_KIND_BY_KEY[row.stop.stopType] : undefined
|
||||
const face = row.service && kind
|
||||
? (
|
||||
<span
|
||||
className="grid h-[30px] w-[30px] shrink-0 place-items-center rounded-full text-white"
|
||||
// theme-lint-disable: the stop kinds share their colour with the map markers,
|
||||
// which sit on tiles rather than on one of the app's own surfaces.
|
||||
style={{ background: serviceColor(row.stop.stopType) }}
|
||||
>
|
||||
<kind.Icon size={15} strokeWidth={2.1} aria-hidden="true" />
|
||||
</span>
|
||||
)
|
||||
: (
|
||||
// Deliberately not font-geist: `.m-root .font-geist` caps the tier at Medium,
|
||||
// which would quietly undo the bold on a number that has to read at 12px.
|
||||
<span className="grid h-[30px] w-[30px] shrink-0 place-items-center rounded-full bg-[color:var(--m-ic)] text-[0.75rem] font-bold tabular-nums text-m-ink">
|
||||
{row.number}
|
||||
</span>
|
||||
)
|
||||
|
||||
if (!onPickKind) return face
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={row.service ? t('roadtrip.stop.kind') : t('roadtrip.stop.makeService')}
|
||||
onClick={e => { e.stopPropagation(); onPickKind() }}
|
||||
onKeyDown={e => { e.stopPropagation() }}
|
||||
className="grid place-items-center rounded-full"
|
||||
>
|
||||
{face}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
function Mark({ icon, children, tone }: { icon: ReactNode; children: ReactNode; tone?: 'warn' }) {
|
||||
return (
|
||||
<span
|
||||
className="inline-flex h-[22px] items-center gap-[4px] rounded-full px-[8px] font-geist text-[0.65625rem] font-semibold"
|
||||
style={tone === 'warn'
|
||||
? { background: 'color-mix(in srgb, var(--m-st-pending) 14%, transparent)', color: 'var(--m-st-pending)' }
|
||||
: { background: 'var(--m-ic)', color: 'var(--m-muted)' }}
|
||||
>
|
||||
{icon}
|
||||
{children}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** The short form of a finding: the number only, the sentence waits in the sheet. */
|
||||
function warningMark(warning: ScheduleWarning, chrome: RowChrome): ReactNode {
|
||||
const { t, unit } = chrome
|
||||
if (warning.code === 'late') {
|
||||
return <Mark tone="warn" icon={<AlertTriangle size={10} strokeWidth={2} />}>{`+${warning.minutes ?? 0} min`}</Mark>
|
||||
}
|
||||
if (warning.code === 'range') {
|
||||
return <Mark tone="warn" icon={<Fuel size={10} strokeWidth={2} />}>{formatDistance(warning.sinceKm ?? 0, unit)}</Mark>
|
||||
}
|
||||
if (warning.code === 'leg') {
|
||||
return <Mark tone="warn" icon={<Hourglass size={10} strokeWidth={2} />}>{formatDurationShort((warning.overMinutes ?? 0) * 60)}</Mark>
|
||||
}
|
||||
return <Mark tone="warn" icon={<Moon size={10} strokeWidth={2} />}>{t('roadtrip.warn.overnight')}</Mark>
|
||||
}
|
||||
|
||||
/**
|
||||
* A stop of the stage. The whole row is the tap target, at least 46px tall, which is
|
||||
* why it is a div with role rather than a button: the desktop needs controls nested
|
||||
* inside its row, and a button inside a button is not markup.
|
||||
*/
|
||||
export function RtStopRow({ row, chrome, onOpen, onPickKind }: {
|
||||
row: StopRow
|
||||
chrome: RowChrome
|
||||
onOpen: () => void
|
||||
/** Absent for a traveller who may not edit places: the disc is then not a control. */
|
||||
onPickKind?: () => void
|
||||
}) {
|
||||
const { t, unit } = chrome
|
||||
const marks: ReactNode[] = []
|
||||
if (row.dwellMinutes) {
|
||||
marks.push(
|
||||
<Mark key="dwell" icon={<Hourglass size={10} strokeWidth={2} />}>{formatDurationShort(row.dwellMinutes * 60)}</Mark>,
|
||||
)
|
||||
}
|
||||
if (row.warning) marks.push(<span key="warn">{warningMark(row.warning, chrome)}</span>)
|
||||
if (!marks.length && row.offRoadMeters) {
|
||||
marks.push(
|
||||
<Mark key="off" icon={<Footprints size={10} strokeWidth={2} />}>
|
||||
{formatDistance(row.offRoadMeters / 1000, unit)}
|
||||
</Mark>,
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={onOpen}
|
||||
onKeyDown={e => { if (e.target === e.currentTarget && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); onOpen() } }}
|
||||
className="grid cursor-pointer items-center gap-x-[10px] py-1" style={{ gridTemplateColumns: '34px 1fr auto' }}
|
||||
>
|
||||
<span className="flex justify-center"><Disc row={row} t={t} onPickKind={onPickKind} /></span>
|
||||
<span className="min-w-0 py-2">
|
||||
<span className={`block text-[0.875rem] leading-[1.25] ${row.service ? 'truncate font-medium text-m-muted' : 'line-clamp-2 font-semibold text-m-ink'}`}>
|
||||
{row.stop.name}
|
||||
</span>
|
||||
{marks.length > 0 && <span className="mt-[4px] flex flex-wrap items-center gap-[5px]">{marks}</span>}
|
||||
</span>
|
||||
{row.time && (
|
||||
// dir=ltr so a clock reads the same way round in an RTL locale.
|
||||
<span dir="ltr" className={`flex items-center gap-[3px] whitespace-nowrap text-[0.8125rem] tabular-nums ${row.pinned ? 'font-semibold text-m-ink' : 'font-medium text-m-faint'}`}>
|
||||
{row.pinned && <Pin size={9} strokeWidth={2.4} className="flex-none text-m-faint" aria-label={t('roadtrip.stop.pinned')} />}
|
||||
{row.time}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const LEG_ICONS: Record<string, typeof CarFront> = {
|
||||
walking: Footprints,
|
||||
cycling: Bike,
|
||||
}
|
||||
|
||||
/**
|
||||
* What a leg pill says: how far and how long, or that it is not routed yet.
|
||||
*
|
||||
* A segment carries both a pre-formatted text and the raw metres and seconds, and the two
|
||||
* do not always arrive together: a segment that reaches the chain before its routing round
|
||||
* has landed has the numbers at zero and the texts empty. Reading only the texts printed
|
||||
* the template with nothing in its slots, so a leg showed as a bare " in " (the
|
||||
* separator of `roadtrip.leg.driveText` with both values missing) — the screenshot is a
|
||||
* hotel followed by a pill saying nothing.
|
||||
*
|
||||
* So the text is used when there is one and the numbers are formatted when there is not,
|
||||
* which is what the desktop rail does with the same segment. With neither, the leg says
|
||||
* it is pending, the honest answer and the one the missing-segment case already gave.
|
||||
*/
|
||||
function legText(seg: RouteSegment | undefined, { t, unit }: RowChrome): string {
|
||||
if (!seg) return t('roadtrip.leg.pending')
|
||||
const metres = Number.isFinite(seg.distance) ? seg.distance : 0
|
||||
const seconds = Number.isFinite(seg.duration) ? seg.duration : 0
|
||||
const distance = seg.distanceText || (metres > 0 ? formatDistance(metres / 1000, unit) : '')
|
||||
const time = seg.durationText || seg.drivingText || (seconds > 0 ? formatDurationShort(seconds) : '')
|
||||
if (!distance || !time) return t('roadtrip.leg.pending')
|
||||
return t('roadtrip.leg.driveText', { distance, time })
|
||||
}
|
||||
|
||||
/**
|
||||
* The drive between two stops. 12px rather than the desktop's 10: a four-hour leg
|
||||
* deserves the space it takes.
|
||||
*
|
||||
* Other ways of driving it are asked for with one 40px round button at the end of the
|
||||
* row, never with the whole band as on the desktop rail. The chain scrolls under a thumb,
|
||||
* and with a band-wide target the tap that only meant to stop that scroll, landing on a
|
||||
* leg, would cost up to five routing requests and a jump to the map. So the pill stays a
|
||||
* line of text, and the button is the one thing on the row that acts: a small, separate
|
||||
* target that keeps that cost behind a gesture nobody makes by accident.
|
||||
*
|
||||
* Open, the button takes the inner surface and the full ink rather than filling with the
|
||||
* action colour, for the reason the rail gives: a filled chip in a column of quiet rows
|
||||
* reads as a button that was pressed and stuck. Offline it keeps its place but dims,
|
||||
* because a choice is saved as a via and vias are online only. Without `onAlternatives`
|
||||
* (no permission, or a leg that cannot be rerouted) the column stays empty.
|
||||
*/
|
||||
export function RtLegRow({ seg, mode, chrome, onAlternatives, alternativesOpen = false, alternativesDisabled = false }: {
|
||||
seg: RouteSegment | undefined
|
||||
mode: string | null
|
||||
chrome: RowChrome
|
||||
/** Asks for other ways of driving this leg. Absent means the leg offers none. */
|
||||
onAlternatives?: () => void
|
||||
/** True while the picker is open on this leg. */
|
||||
alternativesOpen?: boolean
|
||||
alternativesDisabled?: boolean
|
||||
}) {
|
||||
const { t } = chrome
|
||||
const Icon = mode && LEG_ICONS[mode] ? LEG_ICONS[mode] : mode?.startsWith('plugin:') ? Zap : CarFront
|
||||
const text = legText(seg, chrome)
|
||||
return (
|
||||
<div className="grid items-center gap-x-[10px]" style={{ gridTemplateColumns: '34px 1fr auto' }}>
|
||||
{/* flex-col, not flex: in a row the dashes would stretch sideways and read as
|
||||
a barcode. --m-conn rather than --m-rowbr, because the row hairline is 4.5%
|
||||
alpha and disappears in sunlight, and this line is what says "you drive here". */}
|
||||
<span className="flex min-h-[40px] flex-col items-center" aria-hidden="true">
|
||||
<span className="w-[2px] flex-1" style={{ backgroundImage: 'repeating-linear-gradient(var(--m-conn) 0 4px, transparent 4px 8px)' }} />
|
||||
</span>
|
||||
<span className="my-1.5 flex min-w-0 items-center gap-[7px] rounded-[13px] bg-[color:var(--m-ic)] px-[11px] py-[7px]">
|
||||
<Icon size={14} strokeWidth={2} className="flex-none text-m-muted" aria-hidden="true" />
|
||||
<span className="truncate text-[0.75rem] font-semibold tabular-nums text-m-ink">{text}</span>
|
||||
</span>
|
||||
{onAlternatives ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onAlternatives}
|
||||
disabled={alternativesDisabled}
|
||||
aria-pressed={alternativesOpen}
|
||||
aria-label={t('roadtrip.alt.ask')}
|
||||
className={`grid h-10 w-10 flex-none place-items-center rounded-full border disabled:opacity-35 ${
|
||||
alternativesOpen
|
||||
? 'border-[color:var(--m-inbr)] bg-[color:var(--m-inner)] text-m-ink'
|
||||
: 'border-transparent bg-[color:var(--m-ic)] text-m-muted'
|
||||
}`}
|
||||
>
|
||||
<Shuffle size={16} strokeWidth={2} aria-hidden="true" />
|
||||
</button>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The ground the dry band stands on, where the mascot is.
|
||||
*
|
||||
* Opaque on purpose: the mascot cuts its eyes and wheel hubs out in `--m-bg`, and
|
||||
* `--m-card` is 55% alpha in both themes, so on the card's own ground the red body would
|
||||
* show through the eyes. `--m-sheetop` is the phone's opaque surface. Mixed against that
|
||||
* rather than against `--m-bg`, because the mascot's span renames `--m-bg` to this value
|
||||
* and a variable defined in terms of itself is invalid, which would drop the cutouts.
|
||||
*/
|
||||
const DRY_GROUND = 'color-mix(in srgb, var(--m-st-danger) 11%, var(--m-sheetop))'
|
||||
|
||||
/**
|
||||
* The lamp's circle: a soft wash of the band's own colour rather than the black action
|
||||
* fill. The lamp is a warning light that happens to be pressable, and the 44px circle is
|
||||
* what tells a thumb so without turning it into the loudest thing on the screen.
|
||||
*/
|
||||
const DANGER_SOFT: CSSProperties = {
|
||||
background: 'color-mix(in srgb, var(--m-st-danger) 14%, transparent)',
|
||||
color: 'var(--m-st-danger)',
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the tank runs out on this leg, and the reserve lamp that goes looking.
|
||||
*
|
||||
* The desktop band's design, sized for a thumb: the mascot on its skateboard and not
|
||||
* enjoying it, a small uppercase warning, and the lamp itself as the button. Not a pill
|
||||
* with the words on it, because a labelled pill beside a mascot and a title leaves the
|
||||
* title almost no room: the band's content box is only about
|
||||
* 299px wide at 375px and 284px at 360px, and a label like "Cerca un punt de recàrrega"
|
||||
* is a long way into that. So the lamp is the button, as on the desktop, and its words
|
||||
* live in the label a screen reader announces.
|
||||
*
|
||||
* 44px where the desktop lamp is 22px, because it is aimed with a thumb. The title clamps
|
||||
* to two lines instead of truncating, because a warning that loses its end says nothing
|
||||
* ("Qui il serbatoio si esaurisce" does not fit on one). Offline the lamp stops glowing,
|
||||
* because a lamp that glows invites a press that cannot work. Somebody who may not edit
|
||||
* the day still sees the lamp, as a plain mark: the empty tank is information, not an
|
||||
* action.
|
||||
*
|
||||
* While a search runs or its offers show, the lamp steps aside for a close, and an empty
|
||||
* answer leaves a retry in its place. The close matters because the map draws the offers,
|
||||
* and without it nothing in the band could clear those pins short of accepting one. It
|
||||
* stays while offline too, and the offline sentence stands down with it: closing is local,
|
||||
* so there is no dead control left to explain. Which control shows, which offers and which
|
||||
* empty sentence is decided in `refuelBandState`, the same place the desktop band reads
|
||||
* it from.
|
||||
*/
|
||||
export function RtDryRow({ intoLegKm, chrome, electric, onSearch, offline, refuel, dayId, legIndex, onAccept }: {
|
||||
intoLegKm: number
|
||||
chrome: RowChrome
|
||||
electric: boolean
|
||||
onSearch?: () => void
|
||||
offline: boolean
|
||||
refuel: RefuelSearch
|
||||
dayId: number
|
||||
legIndex: number
|
||||
/** Takes one of the offers onto the trip. Absent for somebody who may not edit days. */
|
||||
onAccept?: (poi: RefuelCandidate) => void
|
||||
}) {
|
||||
const { t, unit } = chrome
|
||||
const band = refuelBandState(refuel, dayId, legIndex)
|
||||
const words = REFUEL_WORDS[electric ? 'electric' : 'fuel']
|
||||
const Lamp = electric ? Zap : Fuel
|
||||
return (
|
||||
<div
|
||||
className="-mx-1 my-2 flex flex-col gap-2 rounded-[16px] border px-3 py-2.5"
|
||||
style={{
|
||||
borderColor: 'color-mix(in srgb, var(--m-st-danger) 22%, transparent)',
|
||||
// Flat through the padding and the 44px header row, so the ground behind the
|
||||
// mascot's eyes is the one they are cut in, and only the answers below fade out.
|
||||
backgroundImage: `linear-gradient(180deg, ${DRY_GROUND} 0px, ${DRY_GROUND} 54px, var(--m-card) 100%)`,
|
||||
boxShadow: 'inset 0 1px 0 color-mix(in srgb, var(--m-st-danger) 20%, transparent)',
|
||||
}}
|
||||
>
|
||||
<div className="flex min-h-[44px] items-center gap-2.5">
|
||||
{/* Renamed on this span only, never on the band: the offers below are drawn in
|
||||
--m-ink too, and they have to stay ink. Not a tap target either: the lamp at
|
||||
the end of this line is its one control, and a mascot that reacted too would
|
||||
be a second one that looks like none. */}
|
||||
<span
|
||||
className="pointer-events-none flex flex-none"
|
||||
style={{ '--m-ink': 'var(--m-st-danger)', '--m-bg': DRY_GROUND } as CSSProperties}
|
||||
>
|
||||
{/* Out of fuel is a thing that happens to the drive, so it is the mascot with
|
||||
the vehicle, and it is not enjoying it. */}
|
||||
<MDancingTrek scene="transport" mood="sad" size={34} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="line-clamp-2 font-geist text-[0.625rem] font-bold uppercase leading-[1.35] tracking-[.09em] text-[color:var(--m-st-danger)]">
|
||||
{t(words.dry)}
|
||||
</span>
|
||||
<span className="mt-[2px] block font-geist text-[0.71875rem] tabular-nums text-m-muted">
|
||||
{t('roadtrip.refuel.after', { distance: formatDistance(Math.round(intoLegKm), unit) })}
|
||||
</span>
|
||||
</span>
|
||||
{band.control === 'close' ? (
|
||||
<MIconBtn variant="neutral" size={44} onClick={refuel.close} ariaLabel={t('common.close')}>
|
||||
<X size={16} strokeWidth={2.2} aria-hidden="true" />
|
||||
</MIconBtn>
|
||||
) : onSearch ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onSearch}
|
||||
disabled={offline}
|
||||
aria-label={t(band.control === 'again' ? 'roadtrip.refuel.again' : words.find)}
|
||||
style={offline ? undefined : DANGER_SOFT}
|
||||
className={`grid h-11 w-11 flex-none place-items-center rounded-full ${offline ? 'bg-[color:var(--m-ic)] text-m-faint' : ''}`}
|
||||
>
|
||||
{band.control === 'again'
|
||||
? <RotateCcw size={17} strokeWidth={2.2} aria-hidden="true" />
|
||||
: <Lamp size={18} strokeWidth={2} className={offline ? undefined : 'trek-lowfuel'} aria-hidden="true" />}
|
||||
</button>
|
||||
) : (
|
||||
<span className="grid h-11 w-11 flex-none place-items-center text-[color:var(--m-st-danger)]" aria-hidden="true">
|
||||
<Lamp size={18} strokeWidth={2} className="trek-lowfuel" />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Blunt rather than silent: the lamp keeps its place and this says why it is out. */}
|
||||
{onSearch && offline && band.control !== 'close' && (
|
||||
<span className="font-geist text-[0.6875rem] leading-[1.4] text-m-faint">{t('mobileTrip.rtSearchOffline')}</span>
|
||||
)}
|
||||
|
||||
{band.loading && (
|
||||
<span className="font-geist text-[0.71875rem] text-m-muted">{t('roadtrip.refuel.looking')}</span>
|
||||
)}
|
||||
|
||||
{/* The answer, in the band that asked. The desktop puts it in the rail row for the
|
||||
same reason: a station offered somewhere other than where the tank runs out is
|
||||
an offer somebody has to go and find. */}
|
||||
{band.offers.length > 0 && (
|
||||
<ul className="flex flex-col gap-[6px]">
|
||||
{band.offers.map(poi => (
|
||||
<RefuelOffer
|
||||
key={poi.osm_id}
|
||||
poi={poi}
|
||||
chrome={chrome}
|
||||
electric={electric}
|
||||
onAccept={onAccept ? () => onAccept(poi) : undefined}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{/* Three sentences for three different facts. "Nothing on this stretch" after a
|
||||
request that failed states something that was never checked. */}
|
||||
{band.empty && (
|
||||
<span className="font-geist text-[0.71875rem] leading-[1.4] text-m-muted">{t(REFUEL_EMPTY_KEY[band.empty])}</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* One station on offer: what it is, the two figures that decide it, and a 38px plus.
|
||||
*
|
||||
* The detour is what the list is sorted by, because everything in it is reachable
|
||||
* already and what separates them is what the stop costs. What is left in the tank when
|
||||
* the car draws level comes second, with that detour counted in. Both as plain labelled
|
||||
* figures rather than the desktop's icon badges: a tooltip is the desktop's way of
|
||||
* saying which number is which, and there is no hover here to carry it.
|
||||
*/
|
||||
function RefuelOffer({ poi, chrome, electric, onAccept }: {
|
||||
poi: RefuelCandidate
|
||||
chrome: RowChrome
|
||||
electric: boolean
|
||||
onAccept?: () => void
|
||||
}) {
|
||||
const { t, unit } = chrome
|
||||
const kind = STOP_KIND_BY_KEY[poi.category]
|
||||
const KindIcon = kind?.Icon ?? Fuel
|
||||
return (
|
||||
<li className="flex items-center gap-2.5 rounded-[14px] bg-[color:var(--m-card)] py-1.5 pe-1.5 ps-2.5">
|
||||
<span
|
||||
className="grid h-[26px] w-[26px] flex-none place-items-center rounded-full text-white"
|
||||
// theme-lint-disable: the stop kinds share their colour with the map markers.
|
||||
style={{ background: serviceColor(poi.category) }}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<KindIcon size={13} strokeWidth={2.1} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-[0.78125rem] font-semibold text-m-ink">{poi.name}</span>
|
||||
<span className="mt-px block truncate font-geist text-[0.6875rem] tabular-nums text-m-muted">
|
||||
{[
|
||||
t('roadtrip.poi.offRoute', { distance: formatDistance(poi.offRouteKm, unit) }),
|
||||
t('roadtrip.refuel.spare', { distance: formatDistance(Math.round(poi.spareKm), unit) }),
|
||||
].join(' · ')}
|
||||
</span>
|
||||
</span>
|
||||
{onAccept && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onAccept}
|
||||
aria-label={t(REFUEL_WORDS[electric ? 'electric' : 'fuel'].add, { name: poi.name })}
|
||||
className="grid h-[38px] w-[38px] flex-none place-items-center rounded-full bg-[color:var(--m-ic)] text-m-ink"
|
||||
>
|
||||
<Plus size={16} strokeWidth={2.2} aria-hidden="true" />
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
/** Where a day ended for the night, or picked back up. Information, not a control. */
|
||||
export function RtAutoRow({ phase, time, chrome }: {
|
||||
phase: 'end' | 'resume'
|
||||
time: string | null
|
||||
chrome: RowChrome
|
||||
}) {
|
||||
const { t } = chrome
|
||||
const Icon = phase === 'end' ? Moon : Sunrise
|
||||
return (
|
||||
<div className="my-1.5 flex min-h-[38px] items-center gap-2 rounded-[13px] bg-[color:var(--m-ic)] px-[11px] py-[7px]">
|
||||
<Icon size={14} strokeWidth={2} className="flex-none text-m-muted" aria-hidden="true" />
|
||||
<span className="text-[0.75rem] font-semibold text-m-muted">
|
||||
{phase === 'end' ? t('roadtrip.window.stop') : t('roadtrip.window.resume')}
|
||||
</span>
|
||||
{time && <span className="ms-auto text-[0.8125rem] font-semibold tabular-nums text-m-ink">{time}</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A night drive crossing into this card.
|
||||
*
|
||||
* The only place a stage shows stops that belong to another day. Without it the
|
||||
* traveller counts wrong at a night crossing, because the card opens with stops it
|
||||
* does not own.
|
||||
*/
|
||||
export function RtSpillRow({ fromDayNumber, departs, chrome, children }: {
|
||||
fromDayNumber: number
|
||||
departs: string | null
|
||||
chrome: RowChrome
|
||||
children?: ReactNode
|
||||
}) {
|
||||
const { t } = chrome
|
||||
return (
|
||||
<div
|
||||
className="-mx-1 mb-2 mt-1 overflow-hidden rounded-[16px] border px-3 py-2.5"
|
||||
style={{
|
||||
borderColor: 'color-mix(in srgb, var(--m-st-info) 26%, transparent)',
|
||||
background: 'linear-gradient(180deg, color-mix(in srgb, var(--m-st-info) 11%, var(--m-card)) 0%, var(--m-card) 100%)',
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-[6px]">
|
||||
<Moon size={13} strokeWidth={2} style={{ color: 'var(--m-st-info)' }} aria-hidden="true" />
|
||||
<span className="font-geist text-[0.625rem] font-bold uppercase tracking-[.09em] text-m-muted">
|
||||
{t('roadtrip.spill.title', { number: fromDayNumber })}
|
||||
</span>
|
||||
{departs && (
|
||||
<span className="ms-auto text-[0.71875rem] font-semibold tabular-nums text-m-ink">
|
||||
{t('roadtrip.spill.departs', { time: departs })}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{children && <div className="mt-1 px-[7px]">{children}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
import { useRef } from 'react'
|
||||
import { AlertTriangle, MapPin, Navigation } from 'lucide-react'
|
||||
import { useMPlanDaySwipe } from '../plan/useMPlanDaySwipe'
|
||||
import { showStopOnMap, useMRoadtrip } from './useMRoadtrip'
|
||||
import { useMRtCorridor } from './useMRtCorridor'
|
||||
import { useMRtAlternatives } from './useMRtAlternatives'
|
||||
import MRtCorridorBar from './MRtCorridorBar'
|
||||
import MRtAlternativesBar from './MRtAlternativesBar'
|
||||
import { RtAutoRow, RtDryRow, RtLegRow, RtSpillRow, RtStopRow, type RowChrome } from './MRoadtripRows'
|
||||
import MBadge from '../../../components/MBadge'
|
||||
import MDancingTrek from '../../../components/MDancingTrek'
|
||||
import { formatDurationShort } from '../../../../components/Roadtrip/roadtripModel'
|
||||
import { getNavigationTargets } from '../../../../components/Planner/placeNavigation'
|
||||
import { useSettingsStore } from '../../../../store/settingsStore'
|
||||
import { formatDistance } from '../../../../utils/units'
|
||||
import { isRtlLanguage } from '../../../../i18n'
|
||||
import type { MTripTabPanelProps } from '../MTripShell'
|
||||
import { legReroutable, type StopRow } from '../../../../components/Roadtrip/roadtripRowModel'
|
||||
|
||||
/**
|
||||
* The road trip tab: one day of the drive, as a chain or on the map.
|
||||
*
|
||||
* Both halves are this one component because they share a stage, and the switch
|
||||
* between them must not lose it. The map itself is not here: it is the shell's single
|
||||
* instance, shared with the plan tab and lying underneath, so the map half of this
|
||||
* screen is nothing but the stage bar floating over it.
|
||||
*
|
||||
* The stage picker is the shell's day-chip rail. This panel renders at z-20, below the
|
||||
* chips at z-25, which is the whole of that: the chips were always mounted and only
|
||||
* ever hidden because the other tabs cover them at z-30. With them come the auto
|
||||
* scroll, the day tints, the label format and the second tap that opens the day sheet.
|
||||
*/
|
||||
export default function MRoadtripTab({ planner, shell }: MTripTabPanelProps) {
|
||||
const { t, days } = planner
|
||||
const panelRef = useRef<HTMLDivElement>(null)
|
||||
const cardRef = useRef<HTMLDivElement>(null)
|
||||
const rt = useMRoadtrip(planner)
|
||||
const corridor = useMRtCorridor(planner, shell)
|
||||
// Called once here and handed down, like `rt`: the chain's leg buttons and the bar over
|
||||
// the map read one controller, so a leg shows pressed for exactly the picker on the map.
|
||||
const alts = useMRtAlternatives(planner, shell)
|
||||
const unit = useSettingsStore(s => s.settings.distance_unit)
|
||||
const chrome: RowChrome = { t, unit }
|
||||
|
||||
// The same gesture the day timeline uses, called rather than rebuilt: 370 lines of
|
||||
// worked-out conflict avoidance, down to the dead 24px gutter that stops iOS from
|
||||
// reading a swipe as its own back gesture.
|
||||
const daySwipe = useMPlanDaySwipe({
|
||||
days,
|
||||
selectedDayId: planner.selectedDayId,
|
||||
// skipFit: the map underneath stays mounted, and the stage's own focus points
|
||||
// frame it as soon as the selection moves.
|
||||
onSelectDay: dayId => planner.handleSelectDay(dayId, true),
|
||||
panelRef,
|
||||
cardRef,
|
||||
editing: false,
|
||||
dragging: false,
|
||||
menuOpen: !!shell.sheet,
|
||||
rtl: isRtlLanguage(planner.language),
|
||||
describeDay: (i, n) => t('mobileTrip.dayAnnounce', { current: i + 1, total: n }),
|
||||
})
|
||||
|
||||
const stage = rt.stage
|
||||
|
||||
// The disc is only a control for somebody who may change a place. Read here rather than
|
||||
// inside the row so the whole chain asks once, the way `rt` and `chrome` are handled.
|
||||
const canEditPlaces = planner.can('place_edit', planner.trip)
|
||||
|
||||
const openStop = (row: StopRow) => {
|
||||
shell.openSheet('rtstop', { dayId: row.stop.ownerDayId, assignmentId: row.stop.assignmentId })
|
||||
}
|
||||
|
||||
// The search bar sits in the same band on both halves, at the same offset, so the
|
||||
// list/map switch never moves it: it is one stage seen two ways, and a control that
|
||||
// jumps between them is a control you have to find twice. The band and the margins
|
||||
// are the plan tab's POI bar, for the same reason.
|
||||
//
|
||||
// Only over a stage. Without one there is no drive to search along: the corridor would
|
||||
// fall back to the trip's first routed day, which is not the one on screen, and every
|
||||
// distance it answered with would be measured against a road nobody is looking at.
|
||||
const searchBar = stage && (
|
||||
<div className="pointer-events-auto absolute left-4 right-4 top-[calc(var(--m-safe-top,12px)+96px)] z-[26]">
|
||||
<MRtCorridorBar planner={planner} corridor={corridor} onOpen={() => shell.openSheet('rtsearch')} />
|
||||
</div>
|
||||
)
|
||||
|
||||
// ── Map half: the search bar, and the picker's bar while it is open. Everything
|
||||
// between them belongs to the map instance the shell keeps mounted, so this layer must
|
||||
// not swallow taps.
|
||||
//
|
||||
// A stage bar used to stand over the dock whenever the map was up: the day's
|
||||
// destination with its picture, its stop count, its arrival and its distance. It went
|
||||
// because the day and the distance are already in the shell's stage header, and on a
|
||||
// map that fills the screen a permanent card over the bottom edge costs more than the
|
||||
// three facts it added.
|
||||
//
|
||||
// While other ways of driving a leg are on offer, their bar stands in that now empty
|
||||
// slot and the search bar steps away. The picker is modal on the map: its lines are the
|
||||
// question on screen, a corridor search started under it would draw its pins over
|
||||
// them, and the band it frees at the top is room the leg is framed into.
|
||||
if (shell.rtView === 'map') {
|
||||
return (
|
||||
<div className="pointer-events-none absolute inset-0 z-20">
|
||||
{!alts.open && searchBar}
|
||||
{/* Just above the dock, the same gap everything else on this shell keeps from it.
|
||||
Mounted only while the picker is open, so nothing invisible lies over the map's
|
||||
own buttons the rest of the time. */}
|
||||
{alts.open && (
|
||||
<div className="pointer-events-auto absolute left-4 right-4 bottom-[calc(var(--bottom-nav-h,84px)+4px)]">
|
||||
<MRtAlternativesBar planner={planner} alts={alts} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── List half ────────────────────────────────────────────────────────────────
|
||||
return (
|
||||
<div ref={panelRef} className="absolute inset-0" {...daySwipe.handlers}>
|
||||
<span className="sr-only" role="status" aria-live="polite" aria-atomic="true">{daySwipe.announcement}</span>
|
||||
{searchBar}
|
||||
<div
|
||||
ref={cardRef}
|
||||
className={`absolute inset-0 overflow-y-auto overscroll-contain px-4 pb-[calc(var(--bottom-nav-h,84px)+22px)] ${
|
||||
searchBar ? 'pt-[calc(var(--m-safe-top,12px)+150px)]' : 'pt-[calc(var(--m-safe-top,12px)+102px)]'
|
||||
}`}
|
||||
>
|
||||
{rt.empty || !stage ? (
|
||||
<EmptyStage planner={planner} loading={rt.loading} />
|
||||
) : (
|
||||
<>
|
||||
{/* Head card: a header over the chain rather than a third of it. The day's
|
||||
facts ride on the date line as badges instead of in a band of their own
|
||||
under the clocks, and they move under the date together when a long
|
||||
locale or the sentence for a partial total does not fit beside it.
|
||||
|
||||
The two clocks stay the largest figures on the screen: when the stage
|
||||
starts and when it reaches its last place. Both are ones the chain below
|
||||
repeats, read off the same arrival column (see stageClocks), so a first
|
||||
stop pinned at 10:00 heads the card at 10:00 and not at the end of its
|
||||
stay. They carry dir=ltr for the same reason the rows do: a clock reads
|
||||
the same way round in an RTL locale.
|
||||
|
||||
No day colour here. It keys the day's line on the map, and on this half
|
||||
the map lies under the list, so a dot in the card had nothing on screen
|
||||
to explain it and read as a status light. The stage bar's picture ring
|
||||
carries the colour on the half where the line is visible. */}
|
||||
<section className="rounded-[22px] border border-[color:var(--m-cbr)] bg-[color:var(--m-card)] px-4 py-3">
|
||||
<div className="flex flex-wrap items-center gap-x-1.5 gap-y-1">
|
||||
<span className="me-auto whitespace-nowrap font-geist text-[0.625rem] font-bold uppercase tracking-[.09em] text-m-muted">
|
||||
{stageDateLabel(planner, stage.dayId) ?? t('roadtrip.day', { number: stage.dayNumber })}
|
||||
</span>
|
||||
{/* The two badges wrap as a pair. Loose in the line, a long drive would keep
|
||||
the date and the drive on one line and drop the count alone onto the next,
|
||||
at the opposite edge from the badge it belongs with. */}
|
||||
<span className="flex max-w-full flex-wrap items-center gap-x-1.5 gap-y-1">
|
||||
{/* The drive badge alone may break inside itself. A badge keeps its text on
|
||||
one line, which is right for a figure, but the partial sentence runs to
|
||||
nearly fifty characters in some locales and would push past the card on
|
||||
a narrow phone, so this one stops at the row's width and lets its height
|
||||
follow the text. The stop count is a figure and keeps to one line. */}
|
||||
<MBadge caps={false} wrap>
|
||||
{stage.distance > 0
|
||||
? t('roadtrip.leg.driveText', {
|
||||
distance: formatDistance(stage.distance / 1000, unit),
|
||||
time: formatDurationShort(stage.duration),
|
||||
})
|
||||
: t('roadtrip.summary.partial')}
|
||||
</MBadge>
|
||||
<MBadge>{t('roadtrip.day.stopCount', { count: rt.stops })}</MBadge>
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-2 flex items-end justify-between gap-3">
|
||||
<span className="min-w-0">
|
||||
<span className="block font-geist text-[0.5625rem] font-bold uppercase tracking-[.08em] text-m-faint">
|
||||
{t('mobileTrip.rtStart')}
|
||||
</span>
|
||||
<span dir="ltr" className="mt-0.5 block text-[1.5rem] font-extrabold leading-none tabular-nums text-m-ink">
|
||||
{rt.clocks.start ?? '-'}
|
||||
</span>
|
||||
</span>
|
||||
<span className="min-w-0 text-right">
|
||||
<span className="block font-geist text-[0.5625rem] font-bold uppercase tracking-[.08em] text-m-faint">
|
||||
{t('roadtrip.stay.arrive')}
|
||||
</span>
|
||||
<span dir="ltr" className="mt-0.5 block text-[1.5rem] font-extrabold leading-none tabular-nums text-m-ink">
|
||||
{rt.clocks.arrive ?? '-'}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
{stage.dayWarning && (
|
||||
<div
|
||||
className="mt-2 rounded-[13px] px-[11px] py-[7px]"
|
||||
style={{ background: 'color-mix(in srgb, var(--m-st-pending) 12%, transparent)', color: 'var(--m-st-pending)' }}
|
||||
>
|
||||
<span className="flex items-center gap-[6px] text-[0.71875rem] font-semibold">
|
||||
<AlertTriangle size={13} strokeWidth={2} aria-hidden="true" />
|
||||
{t('roadtrip.limit.dayOver', {
|
||||
time: formatDurationShort((stage.dayWarning.minutes - stage.dayWarning.limitMinutes) * 60),
|
||||
})}
|
||||
</span>
|
||||
{/* The sentence the desktop hides in a title attribute. */}
|
||||
<span className="mt-[3px] block font-geist text-[0.65625rem] text-m-muted">
|
||||
{t('roadtrip.limit.hint')}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{rt.upNext && <UpNext planner={planner} shell={shell} rt={rt} stageDayId={stage.dayId} onOpen={openStop} />}
|
||||
|
||||
<section className="mt-2.5 overflow-hidden rounded-[22px] border border-[color:var(--m-cbr)] bg-[color:var(--m-card)] px-3.5 pb-3 pt-1">
|
||||
{rt.rows.map((row, i) => {
|
||||
if (row.kind === 'stop') {
|
||||
return (
|
||||
<RtStopRow
|
||||
key={`s${i}`}
|
||||
row={row}
|
||||
chrome={chrome}
|
||||
onOpen={() => openStop(row)}
|
||||
onPickKind={canEditPlaces
|
||||
? () => shell.openSheet('rtkind', {
|
||||
placeId: row.stop.placeId,
|
||||
stopType: row.stop.stopType ?? null,
|
||||
name: row.stop.name,
|
||||
})
|
||||
: undefined}
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (row.kind === 'leg') {
|
||||
// Only where the desk rail offers it too (legReroutable), and with the
|
||||
// card's day id, the one the desk passes: the planner finds the day each
|
||||
// stop is stored on by itself.
|
||||
return (
|
||||
<RtLegRow
|
||||
key={`l${i}`}
|
||||
seg={row.seg}
|
||||
mode={row.mode}
|
||||
chrome={chrome}
|
||||
onAlternatives={alts.canAsk && legReroutable(stage, row.index) ? () => alts.ask(stage.dayId, row.index) : undefined}
|
||||
alternativesOpen={alts.isOpenFor(stage.dayId, row.index)}
|
||||
alternativesDisabled={!alts.editable}
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (row.kind === 'auto') return <RtAutoRow key={`a${i}`} phase={row.phase} time={row.time} chrome={chrome} />
|
||||
if (row.kind === 'spill') {
|
||||
return <RtSpillRow key={`p${i}`} fromDayNumber={row.fromDayNumber} departs={row.departs} chrome={chrome} />
|
||||
}
|
||||
return (
|
||||
<RtDryRow
|
||||
key={`d${i}`}
|
||||
intoLegKm={row.intoLegKm}
|
||||
chrome={chrome}
|
||||
electric={rt.electric}
|
||||
offline={rt.offline}
|
||||
refuel={planner.refuel}
|
||||
dayId={stage.dayId}
|
||||
legIndex={row.legIndex}
|
||||
onSearch={planner.can('day_edit', planner.trip)
|
||||
? () => planner.askRefuel(stage.dayId, dryPointFor(planner, stage.dayId, row.legIndex))
|
||||
: undefined}
|
||||
onAccept={planner.can('day_edit', planner.trip)
|
||||
? poi => planner.acceptRefuel(stage.dayId, poi, dryPointFor(planner, stage.dayId, row.legIndex))
|
||||
: undefined}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* What is coming up, measured against the clock rather than the plan.
|
||||
*
|
||||
* Without it the stage is a morning plan in a narrow column: leave at 09:15 instead of
|
||||
* 08:30 and every figure on the screen is quietly wrong for the rest of the day. The
|
||||
* planned time stays put and the delta sits beside it, because the planned time is the
|
||||
* number you want to compare against.
|
||||
*/
|
||||
function UpNext({ planner, shell, rt, stageDayId, onOpen }: {
|
||||
planner: MTripTabPanelProps['planner']
|
||||
shell: MTripTabPanelProps['shell']
|
||||
rt: ReturnType<typeof useMRoadtrip>
|
||||
stageDayId: number
|
||||
onOpen: (row: StopRow) => void
|
||||
}) {
|
||||
const { t } = planner
|
||||
const next = rt.upNext
|
||||
if (!next) return null
|
||||
const late = next.minutesUntil < 0
|
||||
const place = planner.places.find(p => p.id === next.row.stop.placeId)
|
||||
const targets = place ? getNavigationTargets(place) : []
|
||||
|
||||
return (
|
||||
<section className="mt-2.5 rounded-[22px] border border-[color:var(--m-inbr)] bg-[color:var(--m-inner)] px-4 py-3.5 shadow-[0_18px_44px_-18px_rgba(0,0,0,.3)]">
|
||||
<button type="button" onClick={() => onOpen(next.row)} className="w-full text-left">
|
||||
<span className="flex items-center justify-between gap-2">
|
||||
<span className="font-geist text-[0.65625rem] font-bold uppercase tracking-[.08em] text-m-muted">
|
||||
{t('mobileTrip.upNext')}
|
||||
</span>
|
||||
{/* One pill, two readings: a countdown while the stop is still ahead, the
|
||||
delay once its planned time has passed. There is no position source, so
|
||||
"behind plan" is the strongest honest claim available. */}
|
||||
<span
|
||||
className="whitespace-nowrap rounded-full px-2 py-[2px] text-[0.6875rem] font-semibold"
|
||||
style={late
|
||||
? { background: 'color-mix(in srgb, var(--m-st-pending) 16%, transparent)', color: 'var(--m-st-pending)' }
|
||||
: { background: 'var(--m-ic)', color: 'var(--m-ink)' }}
|
||||
>
|
||||
{late
|
||||
? t('mobileTrip.rtBehind', { time: formatDurationShort(-next.minutesUntil * 60) })
|
||||
: t('mobileTrip.inCountdown', { time: formatDurationShort(next.minutesUntil * 60) })}
|
||||
</span>
|
||||
</span>
|
||||
<span className="mt-1.5 block truncate text-[1.125rem] font-bold text-m-ink">{next.row.stop.name}</span>
|
||||
{next.row.time && (
|
||||
<span className="mt-[2px] block font-geist text-[0.75rem] tabular-nums text-m-muted">{next.row.time}</span>
|
||||
)}
|
||||
</button>
|
||||
<div className="mt-3 flex gap-2">
|
||||
<a
|
||||
href={targets[0]?.url ?? '#'}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-disabled={!targets.length}
|
||||
className={`flex h-11 flex-1 items-center justify-center gap-[7px] rounded-full bg-m-act text-[0.8125rem] font-semibold text-m-actfg shadow-[0_10px_24px_-10px_rgba(0,0,0,.45)] ${targets.length ? '' : 'pointer-events-none opacity-40'}`}
|
||||
>
|
||||
<Navigation size={15} strokeWidth={2.2} aria-hidden="true" />
|
||||
{t('places.navigate')}
|
||||
</a>
|
||||
<button
|
||||
type="button"
|
||||
// Up next is a stop of the stage on screen, so the day stays put and only the camera moves.
|
||||
onClick={() => showStopOnMap(planner, shell, next.row.stop, stageDayId)}
|
||||
aria-label={t('mobileTrip.showOnMap')}
|
||||
className="flex h-11 w-11 flex-none items-center justify-center rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] text-m-ink backdrop-blur-[24px] backdrop-saturate-[1.7]"
|
||||
>
|
||||
<MapPin size={17} strokeWidth={2} aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* An empty stage is not a failure.
|
||||
*
|
||||
* A day with one place has no drive, because a route needs two. So no summary card
|
||||
* full of zeroes, no skeleton and no button, just the line and the one sentence that
|
||||
* says out loud where the planning happens.
|
||||
*/
|
||||
function EmptyStage({ planner, loading }: { planner: MTripTabPanelProps['planner']; loading: boolean }) {
|
||||
const { t } = planner
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center px-5 py-16 text-center">
|
||||
<MDancingTrek scene="guide" className="mb-2" />
|
||||
<p className="text-[0.9375rem] font-semibold text-m-ink">
|
||||
{loading ? t('roadtrip.summary.partial') : t('roadtrip.empty.title')}
|
||||
</p>
|
||||
{!loading && (
|
||||
<p className="mt-1.5 max-w-[27ch] font-geist text-[0.78125rem] leading-[1.5] text-m-muted">
|
||||
{t('mobileTrip.rtPlanOnDesktop')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/* ── small helpers ────────────────────────────────────────────────────────── */
|
||||
|
||||
function stageDateLabel(planner: MTripTabPanelProps['planner'], dayId: number): string | null {
|
||||
const day = planner.days.find(d => d.id === dayId)
|
||||
if (!day?.date) return null
|
||||
const date = new Date(`${day.date.slice(0, 10)}T00:00:00`)
|
||||
if (Number.isNaN(date.getTime())) return null
|
||||
return new Intl.DateTimeFormat(planner.language, { weekday: 'short', day: 'numeric', month: 'short' }).format(date)
|
||||
}
|
||||
|
||||
/** The dry point the refuel search measures from, looked up by its leg. */
|
||||
function dryPointFor(planner: MTripTabPanelProps['planner'], dayId: number, legIndex: number) {
|
||||
const day = planner.roadtripRoutes.days.find(d => d.dayId === dayId)
|
||||
const point = day?.dryPoints?.find(p => p.legIndex === legIndex)
|
||||
return point!
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import { AlertTriangle, Check, Loader2, Shuffle, X } from 'lucide-react'
|
||||
import MBadge from '../../../components/MBadge'
|
||||
import MIconBtn from '../../../components/MIconBtn'
|
||||
import { alternativeSubline, type AlternativeOverlay } from '../../../../components/Roadtrip/alternativeOverlays'
|
||||
import { useSettingsStore } from '../../../../store/settingsStore'
|
||||
import { formatDistance } from '../../../../utils/units'
|
||||
import { badgeLabel } from './stageBadges'
|
||||
import { RT_ALT_BAR_HEIGHT, type MRtAlternativesController } from './useMRtAlternatives'
|
||||
import type { TripPlanner } from '../MTripShell'
|
||||
|
||||
export interface MRtAlternativesBarProps {
|
||||
planner: TripPlanner
|
||||
alts: MRtAlternativesController
|
||||
}
|
||||
|
||||
/**
|
||||
* The ways of driving one leg, over the map that draws them.
|
||||
*
|
||||
* It takes the stage bar's slot rather than a sheet: the answer is the lines on the map,
|
||||
* and a sheet big enough for three offers would cover the very roads it asks about.
|
||||
*
|
||||
* Three rows at fixed heights, because the map lifts its credit and its round controls by
|
||||
* this bar's height (RT_ALT_BAR_LIFT), and a bar that grew with its text would slide under
|
||||
* them. So every line truncates or clamps instead of wrapping into another row.
|
||||
*
|
||||
* A chip previews and the button takes. The chip lights its road on the map, and so does
|
||||
* a tap on the line itself; nothing is written until the confirm, which stays off until a
|
||||
* road other than the one already driven is picked. The chips go quiet while the choice
|
||||
* is being saved, so a second tap cannot pick another road under a write in flight.
|
||||
*/
|
||||
export default function MRtAlternativesBar({ planner, alts }: MRtAlternativesBarProps) {
|
||||
const { t } = planner
|
||||
const title = t('roadtrip.alt.title')
|
||||
|
||||
return (
|
||||
<section
|
||||
aria-label={title}
|
||||
className="flex flex-col gap-2 rounded-[22px] border border-[color:var(--m-cbr)] bg-[color:var(--m-card)] px-[14px] py-[11px] shadow-[0_16px_44px_-14px_rgba(0,0,0,.35)] backdrop-blur-[24px] backdrop-saturate-[1.6]"
|
||||
style={{ height: RT_ALT_BAR_HEIGHT }}
|
||||
>
|
||||
<div className="flex h-8 flex-none items-center gap-2">
|
||||
<Shuffle size={14} strokeWidth={2} className="flex-none text-m-muted" aria-hidden="true" />
|
||||
<span className="min-w-0 flex-1 truncate font-geist text-[0.625rem] font-bold uppercase tracking-[.09em] text-m-muted">
|
||||
{title}
|
||||
</span>
|
||||
<MIconBtn variant="neutral" size={32} ariaLabel={t('common.close')} onClick={alts.cancel}>
|
||||
<X size={15} strokeWidth={2.2} aria-hidden="true" />
|
||||
</MIconBtn>
|
||||
</div>
|
||||
|
||||
<div className="h-[58px] flex-none">
|
||||
<AlternativesBody planner={planner} alts={alts} />
|
||||
</div>
|
||||
|
||||
<div className="flex h-11 flex-none items-center gap-2.5">
|
||||
{/* The desk hides this sentence in a tooltip on the chip. There is no hover here,
|
||||
so it stands beside the button whose choice it qualifies. */}
|
||||
{alts.picked?.otherEngine && (
|
||||
<span className="line-clamp-2 min-w-0 flex-1 font-geist text-[0.65625rem] leading-[1.35] text-m-muted">
|
||||
{t('roadtrip.alt.otherEngine')}
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={alts.confirm}
|
||||
disabled={!alts.canConfirm}
|
||||
aria-busy={alts.saving}
|
||||
// Saving keeps the fill: the button is busy with the choice, not unavailable.
|
||||
className={`flex h-11 min-w-0 items-center justify-center gap-[7px] rounded-full bg-m-act px-5 text-[0.8125rem] font-semibold text-m-actfg ${
|
||||
alts.saving ? '' : 'disabled:bg-[color:var(--m-ic)] disabled:text-m-faint'
|
||||
} ${alts.picked?.otherEngine ? 'flex-none' : 'flex-1'}`}
|
||||
>
|
||||
{alts.saving
|
||||
? <Loader2 size={15} strokeWidth={2.2} className="flex-none animate-spin" aria-hidden="true" />
|
||||
: <Check size={15} strokeWidth={2.2} className="flex-none" aria-hidden="true" />}
|
||||
<span className="truncate">{t('common.confirm')}</span>
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/** The middle row: what the router said, or the roads to pick from. */
|
||||
function AlternativesBody({ planner, alts }: MRtAlternativesBarProps) {
|
||||
const { t } = planner
|
||||
const unit = useSettingsStore(s => s.settings.distance_unit)
|
||||
|
||||
if (alts.phase === 'loading') {
|
||||
return (
|
||||
<p role="status" className="flex h-full items-center gap-2 text-[0.8125rem] font-medium text-m-muted">
|
||||
<Loader2 size={15} strokeWidth={2.2} className="flex-none animate-spin" aria-hidden="true" />
|
||||
<span className="truncate">{t('roadtrip.alt.loading')}</span>
|
||||
</p>
|
||||
)
|
||||
}
|
||||
if (alts.phase === 'failed') {
|
||||
return (
|
||||
<p role="status" className="flex h-full items-center gap-2 text-[0.8125rem] font-medium text-m-ink">
|
||||
<AlertTriangle size={15} strokeWidth={2.2} className="flex-none text-[color:var(--m-st-pending)]" aria-hidden="true" />
|
||||
<span className="line-clamp-2">{t('roadtrip.alt.failed')}</span>
|
||||
</p>
|
||||
)
|
||||
}
|
||||
if (alts.phase === 'onlyOne') {
|
||||
// One road back is genuinely one sensible way to drive the leg, not a failure.
|
||||
return (
|
||||
<p role="status" className="flex h-full items-center text-[0.8125rem] font-medium text-m-muted">
|
||||
<span className="line-clamp-2">{t('roadtrip.alt.onlyOne')}</span>
|
||||
</p>
|
||||
)
|
||||
}
|
||||
// No phase means no open picker. The tab mounts the bar only while one is open, so this
|
||||
// is at most the render it closes in, and "only one way" there would describe no leg.
|
||||
if (alts.phase !== 'choose') return null
|
||||
|
||||
// Scrolls sideways rather than wrapping, because the row has a fixed height. The negative
|
||||
// margin lets a chip slide under the bar's own edge instead of stopping short of it.
|
||||
return (
|
||||
<div className="-mx-[14px] flex h-full snap-x gap-2 overflow-x-auto px-[14px]">
|
||||
{alts.overlays.map(alt => (
|
||||
<AlternativeChip
|
||||
key={alt.index}
|
||||
alt={alt}
|
||||
picked={alts.picked?.index === alt.index}
|
||||
disabled={alts.saving}
|
||||
distance={formatDistance(alt.distance / 1000, unit)}
|
||||
subline={alternativeSubline(alt, time => t('roadtrip.alt.slower', { time }))}
|
||||
onPick={() => alts.pick(alt.index)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* One offered road: its colour, its drive time, its length and what sets it apart.
|
||||
*
|
||||
* The drive time comes first because it is the exact text of the pill on the map, and it
|
||||
* is that text rather than the swatch that ties a chip to its line: every offer is drawn
|
||||
* in the same pale blue. The distance is a badge, a figure on its own the way the stage
|
||||
* bar sets its figures, and the chip spells its parts out in its name for the reason the
|
||||
* stage bar does.
|
||||
*/
|
||||
function AlternativeChip({ alt, picked, disabled, distance, subline, onPick }: {
|
||||
alt: AlternativeOverlay
|
||||
picked: boolean
|
||||
disabled: boolean
|
||||
distance: string
|
||||
subline: string
|
||||
onPick: () => void
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onPick}
|
||||
disabled={disabled}
|
||||
aria-pressed={picked}
|
||||
aria-label={badgeLabel([alt.label, distance, subline])}
|
||||
className={`flex h-full min-w-[128px] max-w-[232px] flex-none snap-start items-center gap-2.5 rounded-[16px] border px-3 text-start disabled:opacity-60 ${
|
||||
picked ? 'border-[color:var(--m-act)] bg-[color:var(--m-inner)]' : 'border-[color:var(--m-cbr)] bg-[color:var(--m-ic)]'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="h-3 w-3 flex-none rounded-full"
|
||||
// theme-lint-disable: the very colour this road is drawn in on the map, see alternativeColors.ts.
|
||||
style={{ background: alt.color }}
|
||||
/>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="flex min-w-0 items-center gap-1.5">
|
||||
<span className="truncate text-[0.8125rem] font-semibold tabular-nums text-m-ink">{alt.label}</span>
|
||||
<MBadge caps={false}>{distance}</MBadge>
|
||||
</span>
|
||||
<span className="mt-[3px] block truncate font-geist text-[0.6875rem] text-m-muted">{subline}</span>
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { AlertTriangle, Loader2, Search, WifiOff, X } from 'lucide-react'
|
||||
import MIconBtn from '../../../components/MIconBtn'
|
||||
import { formatDistance } from '../../../../utils/units'
|
||||
import { useSettingsStore } from '../../../../store/settingsStore'
|
||||
import type { MRtCorridorController } from './useMRtCorridor'
|
||||
import type { TripPlanner } from '../MTripShell'
|
||||
|
||||
export interface MRtCorridorBarProps {
|
||||
planner: TripPlanner
|
||||
corridor: MRtCorridorController
|
||||
/** Opens the sheet where the question is asked and the answer is read. */
|
||||
onOpen: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* The one control that puts "what is on the way" on a phone screen.
|
||||
*
|
||||
* It sits in the same band as the plan tab's POI bar, on both halves of the road trip
|
||||
* tab, and it never moves: the list and the map are two views of one stage, and a
|
||||
* control that jumps when you switch between them is a control you have to find twice.
|
||||
*
|
||||
* It is a status line as much as a button. A corridor search is several requests over a
|
||||
* mobile connection and can take the better part of half a minute, so the state it is in
|
||||
* has to be readable without opening anything: running, answered, or nothing asked yet.
|
||||
* The answer's own pins are on the map underneath either way.
|
||||
*/
|
||||
export default function MRtCorridorBar({ planner, corridor, onOpen }: MRtCorridorBarProps) {
|
||||
const { t } = planner
|
||||
const unit = useSettingsStore(s => s.settings.distance_unit)
|
||||
|
||||
const reachLabel = corridor.reach === 'stage'
|
||||
? t('roadtrip.poi.wholeDay')
|
||||
: t('mobileTrip.rtReachAhead', { distance: formatDistance(corridor.reachKm, unit) })
|
||||
|
||||
let icon = <Search size={16} strokeWidth={2.1} aria-hidden="true" />
|
||||
let title = t('roadtrip.poi.title')
|
||||
let meta: string | null = reachLabel
|
||||
|
||||
if (corridor.offline) {
|
||||
icon = <WifiOff size={16} strokeWidth={2.1} aria-hidden="true" />
|
||||
title = t('mobileTrip.rtSearchOffline')
|
||||
meta = null
|
||||
} else if (corridor.error) {
|
||||
// Never "0 on the way" after a search that failed: nothing was checked, and a count
|
||||
// of nothing reads as a stretch of road with no petrol station on it.
|
||||
icon = <AlertTriangle size={16} strokeWidth={2.1} aria-hidden="true" />
|
||||
title = t('roadtrip.poi.failed')
|
||||
meta = null
|
||||
} else if (corridor.loading) {
|
||||
icon = <Loader2 size={16} strokeWidth={2.1} className="animate-spin" aria-hidden="true" />
|
||||
title = t('roadtrip.poi.searching', { done: corridor.progress.done, total: corridor.progress.total })
|
||||
meta = null
|
||||
} else if (corridor.answered) {
|
||||
title = t('roadtrip.poi.found', { count: corridor.hits.length })
|
||||
}
|
||||
|
||||
// The trailing round button is a sibling rather than nested: a button inside a button
|
||||
// is markup no browser and no screen reader agrees on. While a search runs it aborts
|
||||
// it; once one has answered it throws the answer away, pins and all.
|
||||
const trailing = corridor.loading || corridor.answered
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="flex h-11 min-w-0 flex-1 items-center gap-2.5 rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] px-3.5 text-left shadow-[0_16px_44px_-16px_rgba(0,0,0,.35)] backdrop-blur-[24px] backdrop-saturate-[1.7]"
|
||||
>
|
||||
<span className="flex-none text-m-ink">{icon}</span>
|
||||
<span className="min-w-0 flex-1 truncate text-[0.8125rem] font-semibold text-m-ink">{title}</span>
|
||||
{meta && (
|
||||
<span className="flex-none whitespace-nowrap font-geist text-[0.6875rem] font-semibold tabular-nums text-m-muted">
|
||||
{meta}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
{trailing && (
|
||||
<MIconBtn
|
||||
size={44}
|
||||
onClick={corridor.clear}
|
||||
ariaLabel={t(corridor.loading ? 'common.cancel' : 'roadtrip.poi.clearResults')}
|
||||
>
|
||||
<X size={16} strokeWidth={2.2} />
|
||||
</MIconBtn>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { AlertTriangle, Loader2, MapPin, Plus, Search, WifiOff, X } from 'lucide-react'
|
||||
import MSheet from '../../../components/MSheet'
|
||||
import MChip from '../../../components/MChip'
|
||||
import MIconBtn from '../../../components/MIconBtn'
|
||||
import { Eyebrow } from '../sheets/MTripSheetUi'
|
||||
import { useMRtCorridor, type MRtCorridorController } from './useMRtCorridor'
|
||||
import { corridorHitLabel } from '../../../../components/Roadtrip/corridorSearchModel'
|
||||
import { CORRIDOR_CATEGORIES, CORRIDOR_CATEGORY_BY_KEY } from '../../../../components/Roadtrip/stopKinds'
|
||||
import { serviceColor } from '../../../../components/Roadtrip/roadtripModel'
|
||||
import { formatDistance } from '../../../../utils/units'
|
||||
import { useSettingsStore } from '../../../../store/settingsStore'
|
||||
import type { CorridorPoi } from '../../../../components/Roadtrip/useCorridorPois'
|
||||
import type { MTripSheetsProps } from '../MTripShell'
|
||||
import type { DistanceUnit, TranslationFn } from '../../../../types'
|
||||
|
||||
/**
|
||||
* Asking "what is on the way" from the passenger seat.
|
||||
*
|
||||
* The desktop asks this in a 420px column with six controls: the day, the categories,
|
||||
* the corridor width, a section of the drive, a plug type and a minimum power. Two of
|
||||
* those are the question and four are ways of narrowing an answer already on screen,
|
||||
* which is a desk activity. Here the question is two chips and a button, and the
|
||||
* narrowing is gone: a phone shows ten rows, not a hundred, and the way to see fewer of
|
||||
* them is to ask about less road.
|
||||
*
|
||||
* That is the second chip. A search covers one day either way, but a day can be three
|
||||
* hundred kilometres and fifteen requests over a mobile connection, while the fifty
|
||||
* ahead of the driver are three. "Ahead" is where the money is; "the whole stage" is
|
||||
* there because somebody planning tomorrow evening's dinner is not driving right now.
|
||||
*/
|
||||
/**
|
||||
* Rows a sheet prints before it starts being a scroll rather than an answer.
|
||||
*
|
||||
* A whole-stage search with four categories comes back with a couple of hundred, which
|
||||
* is a list nobody reads on a 375px screen and a couple of hundred inline icons to draw.
|
||||
* The rest are not lost: every one of them is a pin on the map behind this sheet, and
|
||||
* asking about less road is the way to see fewer.
|
||||
*/
|
||||
const MAX_ROWS = 60
|
||||
|
||||
export default function MRtCorridorSheet({ planner, shell }: MTripSheetsProps) {
|
||||
const { t } = planner
|
||||
const corridor = useMRtCorridor(planner, shell)
|
||||
const unit = useSettingsStore(s => s.settings.distance_unit)
|
||||
const open = shell.sheet?.id === 'rtsearch'
|
||||
|
||||
const reachLabel = t('mobileTrip.rtReachAhead', { distance: formatDistance(corridor.reachKm, unit) })
|
||||
|
||||
/**
|
||||
* Taking a hit onto the trip.
|
||||
*
|
||||
* Through the planner's own POI handler, which is the same door the map's pins use:
|
||||
* it works out where in the day's chain the place belongs from how far along the drive
|
||||
* it sits, and hands the stop kind and the stay to the draft sheet. The sheet closes
|
||||
* first so the draft is not opened underneath it.
|
||||
*/
|
||||
const add = (poi: CorridorPoi) => {
|
||||
shell.closeSheet()
|
||||
planner.handlePoiClick(poi)
|
||||
}
|
||||
|
||||
/** Brings a hit into view, which on a phone means the map half of this tab. */
|
||||
const show = (poi: CorridorPoi) => {
|
||||
shell.closeSheet()
|
||||
planner.focusRoadtripPoint(poi.lat, poi.lng)
|
||||
if (shell.rtView === 'list') shell.toggleRtView()
|
||||
}
|
||||
|
||||
const canAdd = planner.can('place_edit', planner.trip)
|
||||
|
||||
return (
|
||||
<MSheet
|
||||
open={open}
|
||||
onClose={shell.closeSheet}
|
||||
variant="bottom"
|
||||
material="opaque"
|
||||
ariaLabel={t('roadtrip.poi.title')}
|
||||
>
|
||||
<div className="flex-none px-[18px] pt-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-10 w-10 flex-none items-center justify-center rounded-[13px] bg-[color:var(--m-ic)]">
|
||||
<Search size={17} strokeWidth={2} className="text-m-ink" aria-hidden="true" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-[1.0625rem] font-bold leading-tight text-m-ink">{t('roadtrip.poi.title')}</div>
|
||||
<div className="font-geist text-[0.71875rem] leading-snug text-m-muted">
|
||||
{corridor.reach === 'stage'
|
||||
? t('roadtrip.poi.wholeDay')
|
||||
: corridor.anchored
|
||||
? t('mobileTrip.rtFromNext')
|
||||
: t('mobileTrip.rtFromStart')}
|
||||
</div>
|
||||
</div>
|
||||
<MIconBtn variant="neutral" size={34} onClick={shell.closeSheet} ariaLabel={t('common.close')}>
|
||||
<X size={15} strokeWidth={2.2} />
|
||||
</MIconBtn>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-[18px] pb-2 pt-1">
|
||||
<Eyebrow className="mb-[7px] mt-3">{t('roadtrip.poi.looking')}</Eyebrow>
|
||||
<div className="flex flex-wrap gap-[6px]">
|
||||
{CORRIDOR_CATEGORIES.map(({ key, labelKey, Icon }) => (
|
||||
<MChip
|
||||
key={key}
|
||||
size="tap"
|
||||
active={corridor.categories.includes(key)}
|
||||
onClick={() => corridor.toggleCategory(key)}
|
||||
>
|
||||
<Icon size={14} strokeWidth={2} />
|
||||
{t(labelKey)}
|
||||
</MChip>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Eyebrow className="mb-[7px] mt-3.5">{t('mobileTrip.rtReach')}</Eyebrow>
|
||||
<div className="flex flex-wrap gap-[6px]">
|
||||
<MChip size="tap" active={corridor.reach === 'ahead'} onClick={() => corridor.setReach('ahead')}>
|
||||
{reachLabel}
|
||||
</MChip>
|
||||
<MChip size="tap" active={corridor.reach === 'stage'} onClick={() => corridor.setReach('stage')}>
|
||||
{t('roadtrip.poi.wholeDay')}
|
||||
</MChip>
|
||||
</div>
|
||||
|
||||
<StatusBand corridor={corridor} t={t} />
|
||||
|
||||
{corridor.hits.length > 0 && (
|
||||
<>
|
||||
<ul className="mt-3 overflow-hidden rounded-[18px] border border-[color:var(--m-inbr)] bg-[color:var(--m-inner)]">
|
||||
{corridor.hits.slice(0, MAX_ROWS).map((poi, i) => (
|
||||
<HitRow
|
||||
key={poi.osm_id}
|
||||
poi={poi}
|
||||
unit={unit}
|
||||
t={t}
|
||||
first={i === 0}
|
||||
onShow={() => show(poi)}
|
||||
onAdd={canAdd ? () => add(poi) : undefined}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
{corridor.hits.length > MAX_ROWS && (
|
||||
// Said out loud rather than silently cut: a list that stops at sixty
|
||||
// without saying so reads as the whole answer. All of them are on the
|
||||
// map underneath, which is the other half of this screen.
|
||||
<p className="mt-2 text-center font-geist text-[0.6875rem] tabular-nums text-m-faint">
|
||||
{t('roadtrip.poi.foundFiltered', { count: MAX_ROWS, total: corridor.hits.length })}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-none border-t border-[color:var(--m-rowbr)] px-[18px] pb-4 pt-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={corridor.run}
|
||||
disabled={!corridor.canSearch || corridor.loading}
|
||||
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-m-act text-[0.875rem] font-semibold text-m-actfg disabled:opacity-40"
|
||||
>
|
||||
{corridor.loading
|
||||
? <Loader2 size={16} strokeWidth={2.2} className="animate-spin" aria-hidden="true" />
|
||||
: <Search size={16} strokeWidth={2.2} aria-hidden="true" />}
|
||||
{corridor.loading
|
||||
? t('roadtrip.poi.searching', { done: corridor.progress.done, total: corridor.progress.total })
|
||||
: t('roadtrip.poi.search')}
|
||||
</button>
|
||||
</div>
|
||||
</MSheet>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* What the search has to say about itself.
|
||||
*
|
||||
* Every one of these lines exists because the alternative is a list that looks complete
|
||||
* and is not: a stretch nobody asked about, a box that did not answer, an answer the
|
||||
* server cut short. On a desk those are footnotes under a hundred rows; on a phone they
|
||||
* are the difference between "there is no petrol station" and "we did not look".
|
||||
*/
|
||||
function StatusBand({ corridor, t }: { corridor: MRtCorridorController; t: TranslationFn }) {
|
||||
const notes: string[] = []
|
||||
if (corridor.capped) notes.push(t('roadtrip.poi.capped'))
|
||||
if (corridor.failedAreas > 0) notes.push(t('roadtrip.poi.partial', { count: corridor.failedAreas }))
|
||||
// The phone's own wording, because the desk's ends in "narrow the corridor" and the
|
||||
// corridor width is a control this screen deliberately does not have. What it does
|
||||
// have is the category chips, and fewer of them really is what makes a box fit.
|
||||
if (corridor.truncatedAreas > 0) notes.push(t('mobileTrip.rtTruncated', { count: corridor.truncatedAreas }))
|
||||
|
||||
if (corridor.offline) return <Note tone="warn" icon={<WifiOff size={13} strokeWidth={2} />}>{t('mobileTrip.rtSearchOffline')}</Note>
|
||||
if (corridor.error) return <Note tone="warn" icon={<AlertTriangle size={13} strokeWidth={2} />}>{t('roadtrip.poi.failed')}</Note>
|
||||
if (corridor.categories.length === 0) return <Note tone="calm">{t('roadtrip.poi.empty')}</Note>
|
||||
|
||||
const empty = corridor.answered && corridor.hits.length === 0
|
||||
return (
|
||||
<>
|
||||
{empty && (
|
||||
<Note tone="calm">
|
||||
{corridor.reach === 'ahead' ? t('mobileTrip.rtNoneAhead') : t('mobileTrip.rtNoneOnStage')}
|
||||
</Note>
|
||||
)}
|
||||
{notes.map(note => (
|
||||
<Note key={note} tone="warn" icon={<AlertTriangle size={13} strokeWidth={2} />}>{note}</Note>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function Note({ tone, icon, children }: { tone: 'warn' | 'calm'; icon?: ReactNode; children: ReactNode }) {
|
||||
return (
|
||||
<div
|
||||
className="mt-3 flex items-start gap-[7px] rounded-[15px] px-3 py-[9px] font-geist text-[0.71875rem] leading-[1.45]"
|
||||
style={tone === 'warn'
|
||||
? { background: 'color-mix(in srgb, var(--m-st-pending) 12%, transparent)', color: 'var(--m-st-pending)' }
|
||||
: { background: 'var(--m-inner)', color: 'var(--m-muted)' }}
|
||||
>
|
||||
{icon && <span className="mt-px flex-none">{icon}</span>}
|
||||
<span>{children}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* One hit: what it is, where on the drive it sits, and the one action worth a button.
|
||||
*
|
||||
* Two targets and not three. The row shows it on the map, the plus takes it onto the
|
||||
* trip, and everything the desktop puts beside those (the plug list, the price, the
|
||||
* opening hours) belongs to the stop once it exists, where the stop sheet already
|
||||
* prints it. Adding it twice would be the same duplication the corridor line avoids.
|
||||
*/
|
||||
function HitRow({ poi, unit, t, first, onShow, onAdd }: {
|
||||
poi: CorridorPoi
|
||||
unit: DistanceUnit
|
||||
t: TranslationFn
|
||||
first: boolean
|
||||
onShow: () => void
|
||||
onAdd?: () => void
|
||||
}) {
|
||||
const Icon = CORRIDOR_CATEGORY_BY_KEY[poi.category]?.Icon ?? MapPin
|
||||
const color = serviceColor(poi.category)
|
||||
return (
|
||||
<li className={`flex items-center gap-2.5 px-3 py-2 ${first ? '' : 'border-t border-[color:var(--m-rowbr)]'}`}>
|
||||
<button type="button" onClick={onShow} className="flex min-w-0 flex-1 items-center gap-2.5 py-1 text-left">
|
||||
<span
|
||||
className="grid h-[30px] w-[30px] flex-none place-items-center rounded-[10px]"
|
||||
// theme-lint-disable: the road-signage palette from `roadtripModel`, the same
|
||||
// colour this kind of stop carries on the map and in the chain.
|
||||
style={{ background: `${color}1f`, color }}
|
||||
>
|
||||
<Icon size={14} strokeWidth={1.9} aria-hidden="true" />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-[0.8125rem] font-semibold text-m-ink">{poi.name}</span>
|
||||
<span className="mt-px block truncate font-geist text-[0.6875rem] tabular-nums text-m-muted">
|
||||
{corridorHitLabel(poi, unit, t)}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
{onAdd && (
|
||||
<MIconBtn variant="neutral" size={34} onClick={onAdd} ariaLabel={t('roadtrip.poi.add')}>
|
||||
<Plus size={15} strokeWidth={2.2} />
|
||||
</MIconBtn>
|
||||
)}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { AlertTriangle, BedDouble, Hourglass, ParkingSquare } from 'lucide-react'
|
||||
import MSheet from '../../../components/MSheet'
|
||||
import MChip from '../../../components/MChip'
|
||||
import { Eyebrow, FormSheetHeader } from '../sheets/PlSheetChrome'
|
||||
import { STOP_KINDS, STOP_KIND_BY_KEY, isOvernightCategory } from '../../../../components/Roadtrip/stopKinds'
|
||||
import { formatDurationShort } from '../../../../components/Roadtrip/roadtripModel'
|
||||
import type { RoadtripStopDraft } from '../../../../components/Roadtrip/RoadtripStopPopup'
|
||||
import type { TripPlanner } from '../MTripShell'
|
||||
import type { RoadtripStopType } from '@trek/shared'
|
||||
|
||||
export interface MRtDraftSheetProps {
|
||||
planner: TripPlanner
|
||||
}
|
||||
|
||||
/**
|
||||
* How long to stand still, offered as the few answers anybody actually gives.
|
||||
* The same six the desktop popup offers, so a stop added on the phone and one
|
||||
* added at the desk are the same stop.
|
||||
*/
|
||||
const DWELL_CHOICES = [5, 10, 20, 30, 45, 60]
|
||||
|
||||
/**
|
||||
* Taking a hit found along the drive onto the trip, on the phone.
|
||||
*
|
||||
* Driven by `planner.stopDraft` rather than by `shell.sheet`, because the draft
|
||||
* is what every entry point produces: the fuel search accepting a station
|
||||
* (`acceptRefuel`), a corridor hit dropped on the map, and the chain opening a
|
||||
* service stop it already owns all set that one piece of state and nothing
|
||||
* else. Without a consumer here the fuel button on the phone visibly did
|
||||
* nothing, because the draft was set and no surface read it.
|
||||
*
|
||||
* The write goes through `planner.saveStopDraft`, the same call the desktop
|
||||
* popup makes. It owns the whole sequence a stop needs (the place, the
|
||||
* assignment at the worked-out position, the via re-anchoring, the re-route)
|
||||
* and reports its own failure with a toast, so there is no second path here for
|
||||
* any of it to go wrong in.
|
||||
*/
|
||||
export default function MRtDraftSheet({ planner }: MRtDraftSheetProps) {
|
||||
const { t, stopDraft, setStopDraft, saveStopDraft, stopDraftDuplicate } = planner
|
||||
|
||||
const [stopType, setStopType] = useState<RoadtripStopType | null>(null)
|
||||
const [dwell, setDwell] = useState<number>(30)
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
// Hold the last draft so the panel keeps its content through the 280ms exit
|
||||
// animation: saving clears the draft immediately, and rendering off the live
|
||||
// value alone would blank the sheet mid-slide.
|
||||
const heldRef = useRef<RoadtripStopDraft | null>(null)
|
||||
if (stopDraft) heldRef.current = stopDraft
|
||||
const draft = stopDraft ?? heldRef.current
|
||||
|
||||
// Seeded from what the hit brings with it: a charge is not a fuel stop, and
|
||||
// each kind carries how long it usually takes. An edit answers with what the
|
||||
// stop already says instead.
|
||||
useEffect(() => {
|
||||
if (!stopDraft) return
|
||||
const suggested = STOP_KINDS.find(k => k.key === stopDraft.poi.category)
|
||||
setStopType(stopDraft.editing ? stopDraft.editing.stopType : suggested?.key ?? null)
|
||||
setDwell(stopDraft.editing?.dwellMinutes ?? suggested?.defaultMinutes ?? 30)
|
||||
setSaving(false)
|
||||
}, [stopDraft])
|
||||
|
||||
if (!draft) return null
|
||||
|
||||
const kind = STOP_KINDS.find(k => k.key === stopType)
|
||||
|
||||
/**
|
||||
* A place somebody could sleep at is not offered here at all.
|
||||
*
|
||||
* Booking a night is a second write path (the room, the two days it spans,
|
||||
* the check-in) and the phone has no surface for any of it yet. Saving such a
|
||||
* hit as an ordinary pause would look like it worked while quietly losing the
|
||||
* night, which is worse than saying where it can be done.
|
||||
*/
|
||||
const overnightOnly = draft.overnight != null || isOvernightCategory(draft.poi.category)
|
||||
|
||||
const discard = () => setStopDraft(null)
|
||||
|
||||
const pickKind = (key: RoadtripStopType) => {
|
||||
if (stopType === key) return
|
||||
setStopType(key)
|
||||
// Picking a kind picks its usual length too, until the user says otherwise.
|
||||
// Tapping the kind already chosen changes nothing, so a time set by hand
|
||||
// survives it.
|
||||
setDwell(STOP_KIND_BY_KEY[key]?.defaultMinutes ?? dwell)
|
||||
}
|
||||
|
||||
const submit = async (): Promise<void> => {
|
||||
if (saving) return
|
||||
setSaving(true)
|
||||
try {
|
||||
await saveStopDraft({ stopType, dwellMinutes: dwell })
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<MSheet open={stopDraft != null} onClose={discard} variant="bottom" material="opaque" ariaLabel={draft.poi.name}>
|
||||
<FormSheetHeader
|
||||
icon={kind?.Icon ?? ParkingSquare}
|
||||
title={draft.poi.name}
|
||||
subtitle={draft.poi.address}
|
||||
onClose={discard}
|
||||
closeLabel={t('common.close')}
|
||||
/>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-[18px] pb-2">
|
||||
<div className="font-geist text-[0.6875rem] tabular-nums text-m-muted">
|
||||
{t('roadtrip.stop.landsOn', { day: draft.dayNumber, position: draft.position + 1 })}
|
||||
</div>
|
||||
|
||||
{stopDraftDuplicate && (
|
||||
// The full place form warns about duplicates; without the same warning
|
||||
// here this would be the quickest way to add one petrol station twice.
|
||||
<div className="mt-[6px] flex items-start gap-[6px] font-geist text-[0.6875rem] text-[color:var(--m-st-pending)]">
|
||||
<AlertTriangle size={12} strokeWidth={2} className="mt-px flex-none" />
|
||||
<span>{t('roadtrip.stop.duplicate', { name: stopDraftDuplicate })}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{overnightOnly ? (
|
||||
<div className="mt-3 flex items-start gap-[9px] rounded-[16px] border border-[color:var(--m-inbr)] bg-[color:var(--m-inner)] px-3 py-[11px]">
|
||||
<BedDouble size={15} strokeWidth={1.8} className="mt-px flex-none text-m-muted" />
|
||||
<p className="font-geist text-[0.71875rem] leading-[1.5] text-m-muted">
|
||||
{t('mobileTrip.rtNightDesktopOnly')}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<Eyebrow className="mb-[6px] mt-3">{t('roadtrip.stop.kind')}</Eyebrow>
|
||||
<div className="flex flex-wrap gap-[6px]">
|
||||
{STOP_KINDS.map(({ key, labelKey, Icon }) => (
|
||||
<MChip key={key} active={stopType === key} onClick={() => pickKind(key)}>
|
||||
<Icon size={13} strokeWidth={2} />
|
||||
{t(labelKey)}
|
||||
</MChip>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Eyebrow className="mb-[6px] mt-3">{t('roadtrip.stop.stay')}</Eyebrow>
|
||||
<div className="flex flex-wrap gap-[6px]">
|
||||
{DWELL_CHOICES.map(minutes => (
|
||||
<MChip
|
||||
key={minutes}
|
||||
active={dwell === minutes}
|
||||
onClick={() => setDwell(minutes)}
|
||||
className="tabular-nums"
|
||||
>
|
||||
<Hourglass size={12} strokeWidth={2} />
|
||||
{formatDurationShort(minutes * 60)}
|
||||
</MChip>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-none items-center gap-2 border-t border-[color:var(--m-rowbr)] px-[18px] pb-4 pt-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={discard}
|
||||
className="flex h-11 items-center rounded-full px-3 text-[0.8125rem] font-semibold text-m-muted"
|
||||
>
|
||||
{t('common.discard')}
|
||||
</button>
|
||||
{!overnightOnly && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { void submit() }}
|
||||
disabled={saving}
|
||||
className="ml-auto flex h-11 items-center rounded-full bg-m-act px-[22px] text-[0.8125rem] font-semibold text-m-actfg disabled:opacity-40"
|
||||
>
|
||||
{t(draft.editing ? 'common.save' : 'roadtrip.poi.add')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</MSheet>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { Car, Fuel, Zap } from 'lucide-react'
|
||||
import MSheet from '../../../components/MSheet'
|
||||
import type { MTripSheetsProps } from '../MTripShell'
|
||||
import { useTranslation } from '../../../../i18n'
|
||||
import { useSettingsStore } from '../../../../store/settingsStore'
|
||||
import { useRoadtripSettings } from '../../../../hooks/useRoadtripSettings'
|
||||
import { useVehicleRange } from '../../../../components/Roadtrip/useVehicleRange'
|
||||
import { blockMask } from '../../../../components/Roadtrip/RangeStrip'
|
||||
import { dayWindow } from '../../../../components/Roadtrip/dayWindow'
|
||||
import { formatDurationShort, parseAvoid } from '../../../../components/Roadtrip/roadtripModel'
|
||||
import { valhallaAvailable } from '../../../../components/Map/valhallaRoute'
|
||||
import { convertDistance, formatDistance, getDistanceUnitLabel } from '../../../../utils/units'
|
||||
import { Eyebrow, TileHeader } from '../sheets/MTripSheetUi'
|
||||
import type { DistanceUnit } from '../../../../types'
|
||||
|
||||
/**
|
||||
* The figures the stage plans with, read out loud.
|
||||
*
|
||||
* The chain says a stretch is too long, or that there is nothing to fill up at before the
|
||||
* tank runs dry, and on a phone there was nothing behind those sentences: the numbers they
|
||||
* are measured against live in a desktop dialog with seven panels and two columns. Without
|
||||
* them a warning is an opinion. So two of those panels come along, the two that decide what
|
||||
* the stage is allowed to say, and nothing else does.
|
||||
*
|
||||
* Nothing here can be changed. That is the point rather than a gap: driving limits are set
|
||||
* once, at a table, before anybody is in the car, and a form in the passenger seat is a way
|
||||
* to break a trip while it is happening. So there is no field, no slider and no greyed-out
|
||||
* button that looks like one, and the last line says plainly where the settings are and what
|
||||
* else that screen can do that this one cannot.
|
||||
*/
|
||||
|
||||
/**
|
||||
* How many kilometres one block of the bar stands for.
|
||||
*
|
||||
* The same fifty as `RangeStrip`, whose `blockMask` cuts the bar here too. The mask comes
|
||||
* from that module so the two pictures cannot drift apart; the figure the note quotes is
|
||||
* the one thing it does not hand out, so it is stated once here.
|
||||
*/
|
||||
const BLOCK_KM = 50
|
||||
|
||||
/** One value of the driving limits, with the row rule above every row but the first. */
|
||||
function LimitLine({ label, value, fallback, first }: {
|
||||
label: string
|
||||
value: string | null
|
||||
fallback: string
|
||||
first: boolean
|
||||
}) {
|
||||
return (
|
||||
<div className={`flex items-center justify-between gap-3 py-2 ${first ? '' : 'border-t border-[color:var(--m-rowbr)]'}`}>
|
||||
<span className="min-w-0 flex-1 text-[0.8125rem] text-m-muted">{label}</span>
|
||||
<span
|
||||
className={`flex-none text-[0.8125rem] font-semibold tabular-nums ${value ? 'text-m-ink' : 'text-m-faint'}`}
|
||||
>
|
||||
{value ?? fallback}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** One card of the sheet: eyebrow plus whatever the section is made of. */
|
||||
function InfoCard({ label, children }: { label: string; children: ReactNode }) {
|
||||
return (
|
||||
<div className="rounded-[16px] bg-[color:var(--m-ic)] px-3.5 py-3">
|
||||
<Eyebrow>{label}</Eyebrow>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Driving figures sheet ('rtinfo'): the vehicle's range as the tank it leaves the factory
|
||||
* with, and the limits every warning on the stage is measured against. Read-only.
|
||||
*/
|
||||
export default function MRtInfoSheet({ planner, shell }: MTripSheetsProps) {
|
||||
const { t } = useTranslation()
|
||||
const open = shell.sheet?.id === 'rtinfo'
|
||||
const tripId = planner.tripId
|
||||
|
||||
const unitSetting = useSettingsStore(s => s.settings.distance_unit)
|
||||
const unit: DistanceUnit = unitSetting === 'imperial' ? 'imperial' : 'metric'
|
||||
|
||||
// The same range the stage plans with: the vehicle's own figures when they add up,
|
||||
// the typed one otherwise. Reading it through the shared hook is what keeps the sheet
|
||||
// from becoming a second opinion about the tank.
|
||||
const { vehicleKind, rangeKm } = useVehicleRange(tripId)
|
||||
const legMinutes = useRoadtripSettings(s => s.roadtrip_leg_minutes, tripId)
|
||||
const dayMinutes = useRoadtripSettings(s => s.roadtrip_day_minutes, tripId)
|
||||
const dayStart = useRoadtripSettings(s => s.roadtrip_day_start, tripId)
|
||||
const dayEnd = useRoadtripSettings(s => s.roadtrip_day_end, tripId)
|
||||
const fillPercent = useRoadtripSettings(s => s.roadtrip_fill_percent, tripId)
|
||||
const degradation = useRoadtripSettings(s => s.roadtrip_battery_degradation, tripId)
|
||||
const avoidRaw = useRoadtripSettings(s => s.roadtrip_avoid, tripId)
|
||||
|
||||
const electric = vehicleKind === 'electric'
|
||||
const VehicleIcon = electric ? Zap : vehicleKind === 'combustion' ? Fuel : Car
|
||||
|
||||
// Capped where the arithmetic caps it, so no picture can claim a battery is gone. The
|
||||
// range above the bar already has this taken off it, which is exactly why it gets said.
|
||||
const wear = electric ? Math.min(90, Math.max(0, degradation ?? 0)) : 0
|
||||
const fill = fillPercent && fillPercent > 0 && fillPercent < 100 ? fillPercent : 100
|
||||
|
||||
// Split rather than formatted whole, so the unit can sit smaller beside the figure. The
|
||||
// rounding is formatDistance's own, because the stage header uses that and the two must
|
||||
// not disagree by a tenth.
|
||||
const shown = rangeKm ? Math.round(convertDistance(rangeKm, unit) * 10) / 10 : null
|
||||
const mask = blockMask(rangeKm)
|
||||
|
||||
const notes = [
|
||||
shown === null ? t('roadtrip.limit.rangeEmptyHint') : null,
|
||||
shown !== null && fill < 100
|
||||
? t('roadtrip.limit.afterFill', { percent: fill, distance: formatDistance((rangeKm ?? 0) * fill / 100, unit) })
|
||||
: null,
|
||||
mask ? t('roadtrip.limit.blockNote', { distance: formatDistance(BLOCK_KM, unit) }) : null,
|
||||
wear > 0 ? t('roadtrip.limit.wearNote', { percent: wear }) : null,
|
||||
].filter((note): note is string => note !== null)
|
||||
|
||||
const unitLabel = getDistanceUnitLabel(unit)
|
||||
const perLabel = t(electric ? 'roadtrip.limit.perCharge' : 'roadtrip.limit.perFill')
|
||||
const barLabel = shown === null
|
||||
? t('roadtrip.limit.rangeEmpty')
|
||||
: `${shown} ${unitLabel} ${perLabel}`
|
||||
|
||||
// Both times on one line, in the separator the desktop badge already uses. A dash
|
||||
// between two clock readings is the one place a phone line breaks in the wrong spot.
|
||||
const windowText = dayWindow(dayStart, dayEnd) ? `${dayStart} · ${dayEnd}` : null
|
||||
|
||||
// No second routing engine, no avoidance: the stored classes would be a promise the
|
||||
// router cannot keep, so the row says the same "off" it would say with none set.
|
||||
const avoiding = parseAvoid(avoidRaw)
|
||||
const avoidText = valhallaAvailable() && avoiding.length > 0
|
||||
? t('roadtrip.avoid.badge', { count: avoiding.length })
|
||||
: null
|
||||
|
||||
const off = t('roadtrip.limit.off')
|
||||
const lines: { key: string; label: string; value: string | null; fallback: string }[] = [
|
||||
{
|
||||
key: 'leg',
|
||||
label: t('roadtrip.limit.legLabel'),
|
||||
value: legMinutes ? formatDurationShort(legMinutes * 60) : null,
|
||||
fallback: off,
|
||||
},
|
||||
{
|
||||
key: 'day',
|
||||
label: t('roadtrip.limit.dayLabel'),
|
||||
value: dayMinutes ? formatDurationShort(dayMinutes * 60) : null,
|
||||
fallback: off,
|
||||
},
|
||||
{ key: 'window', label: t('roadtrip.window.title'), value: windowText, fallback: off },
|
||||
{
|
||||
key: 'fill',
|
||||
label: t('roadtrip.limit.fillLabel'),
|
||||
value: fill < 100 ? `${fill} %` : null,
|
||||
// "off" is the wrong word for a tank: not saying how far you fill it means you fill
|
||||
// it right up, which is what the arithmetic then does.
|
||||
fallback: t('roadtrip.limit.fillFull'),
|
||||
},
|
||||
{ key: 'avoid', label: t('roadtrip.avoid.section'), value: avoidText, fallback: off },
|
||||
]
|
||||
|
||||
return (
|
||||
<MSheet open={open} onClose={shell.closeSheet} variant="bottom" material="opaque" ariaLabel={t('mobileTrip.rtInfoTitle')}>
|
||||
<div className="flex-none px-[18px] pt-4">
|
||||
<TileHeader
|
||||
icon={<VehicleIcon size={19} strokeWidth={1.8} />}
|
||||
title={<span className="truncate">{t('mobileTrip.rtInfoTitle')}</span>}
|
||||
onClose={shell.closeSheet}
|
||||
closeLabel={t('common.close')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-[18px] pb-[18px]">
|
||||
{/* ── Vehicle: how far it goes, drawn as the tank it leaves the factory with ── */}
|
||||
<div className="mt-[14px]">
|
||||
<InfoCard label={t('roadtrip.limit.sectionVehicle')}>
|
||||
<div className="mt-1.5 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-0.5">
|
||||
<span className="flex items-baseline gap-1">
|
||||
<span className="text-[1.375rem] font-extrabold leading-none tabular-nums text-m-ink">
|
||||
{shown ?? '-'}
|
||||
</span>
|
||||
{shown !== null && (
|
||||
<span className="text-[0.875rem] font-semibold leading-none text-m-muted">{unitLabel}</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="font-geist text-[0.65625rem] text-m-faint">
|
||||
{shown === null ? t('roadtrip.limit.rangeEmpty') : perLabel}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="mt-2.5 h-2.5 w-full overflow-hidden rounded-full bg-[color:var(--m-trackoff)]"
|
||||
role="img"
|
||||
aria-label={barLabel}
|
||||
>
|
||||
{/* Cut as a mask rather than painted over, so the gaps are real holes and
|
||||
the glass behind the sheet shows through them. */}
|
||||
<div
|
||||
className="flex h-full w-full"
|
||||
style={mask ? { maskImage: mask, WebkitMaskImage: mask } : undefined}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<div className="h-full bg-m-act" style={{ width: `${shown === null ? 0 : fill}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{notes.length > 0 && (
|
||||
<div className="mt-2 font-geist text-[0.65625rem] leading-snug text-m-faint">
|
||||
{notes.join(' · ')}
|
||||
</div>
|
||||
)}
|
||||
</InfoCard>
|
||||
</div>
|
||||
|
||||
{/* ── Limits: what every warning on the stage is measured against ── */}
|
||||
<div className="mt-2.5">
|
||||
<InfoCard label={t('roadtrip.limit.title')}>
|
||||
<div className="mt-1">
|
||||
{lines.map((line, i) => (
|
||||
<LimitLine
|
||||
key={line.key}
|
||||
label={line.label}
|
||||
value={line.value}
|
||||
fallback={line.fallback}
|
||||
first={i === 0}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</InfoCard>
|
||||
</div>
|
||||
|
||||
<p className="mt-3 font-geist text-[0.6875rem] leading-snug text-m-faint">
|
||||
{t('mobileTrip.rtDesktopNote')}
|
||||
</p>
|
||||
</div>
|
||||
</MSheet>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import { MapPin } from 'lucide-react'
|
||||
import MSheet from '../../../components/MSheet'
|
||||
import type { MTripSheetsProps } from '../MTripShell'
|
||||
import { useTranslation } from '../../../../i18n'
|
||||
import { STOP_KINDS } from '../../../../components/Roadtrip/stopKinds'
|
||||
import { FormSheetHeader } from '../sheets/PlSheetChrome'
|
||||
import type { RoadtripStopType } from '@trek/shared'
|
||||
|
||||
/** What the chain hands over when a stop's disc is tapped. */
|
||||
interface RtKindSheetPayload {
|
||||
placeId?: number
|
||||
/** What the stop is now: a service kind, or null for a destination. */
|
||||
stopType?: string | null
|
||||
name?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Turning a place on the drive into a pause, and back, on the phone ('rtkind', payload
|
||||
* { placeId, stopType, name }).
|
||||
*
|
||||
* Opened from the stop's own disc in the chain, which is where the desktop opens it from
|
||||
* and for the same reason: the disc is exactly what changes. A destination wears its
|
||||
* running number, a service stop wears its kind's icon in that kind's colour, so the
|
||||
* control is its own preview. Tap the 3, pick the pump, and the 3 becomes an orange disc
|
||||
* while everything below it renumbers.
|
||||
*
|
||||
* A sheet rather than the desktop's popover under the disc: a popover is aimed at an
|
||||
* anchor with a mouse, and the same palette on a phone would land under the thumb that
|
||||
* opened it. The kinds stay a palette of discs rather than a list of words, as they are
|
||||
* on the desktop. At this size the colour and the shape are the label, and seven rows of
|
||||
* text for seven icons would be a menu where a palette does. Each disc still carries its
|
||||
* name for a screen reader.
|
||||
*
|
||||
* It writes through `planner.setRoadtripStopKind`, the very call the desktop rail makes:
|
||||
* one field on one place, with the chain redrawing off the store as soon as it lands.
|
||||
*/
|
||||
export default function MRtKindSheet({ planner, shell }: MTripSheetsProps) {
|
||||
const { t } = useTranslation()
|
||||
const open = shell.sheet?.id === 'rtkind'
|
||||
const payload = (shell.sheet?.payload ?? {}) as RtKindSheetPayload
|
||||
const canEdit = planner.can('place_edit', planner.trip)
|
||||
|
||||
// Hold the last payload so the name and the current kind survive the exit animation
|
||||
// instead of blinking out while the sheet slides away.
|
||||
const heldRef = useRef<RtKindSheetPayload | null>(null)
|
||||
if (open && typeof payload.placeId === 'number') heldRef.current = payload
|
||||
const stop = open && typeof payload.placeId === 'number' ? payload : heldRef.current
|
||||
|
||||
const [saving, setSaving] = useState(false)
|
||||
const current = stop?.stopType ?? null
|
||||
|
||||
/**
|
||||
* Writes the kind and closes.
|
||||
*
|
||||
* Closing rather than reopening the stop sheet: the answer to "what kind is this" is
|
||||
* the disc in the chain, which is already on screen behind this sheet and redraws the
|
||||
* moment the store lands. `setRoadtripStopKind` reports its own failures and resolves
|
||||
* either way, so what the guard buys is a sheet that does not sit open pretending to
|
||||
* save.
|
||||
*/
|
||||
const pick = async (kind: RoadtripStopType | null) => {
|
||||
const placeId = stop?.placeId
|
||||
if (!canEdit || saving || placeId == null) return
|
||||
setSaving(true)
|
||||
try {
|
||||
await planner.setRoadtripStopKind(placeId, kind)
|
||||
shell.closeSheet()
|
||||
} catch {
|
||||
// Swallowed rather than toasted again: `setRoadtripStopKind` catches its own
|
||||
// failures and shows the message itself, so a second one here would be the same
|
||||
// news twice. What this catch is for is the sheet, which stays open on a write that
|
||||
// never landed instead of closing as if it had.
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<MSheet
|
||||
open={open && !!stop}
|
||||
onClose={shell.closeSheet}
|
||||
variant="bottom"
|
||||
material="opaque"
|
||||
ariaLabel={t('roadtrip.stop.kind')}
|
||||
>
|
||||
{stop && (
|
||||
<>
|
||||
<FormSheetHeader
|
||||
title={t('roadtrip.stop.kind')}
|
||||
onClose={shell.closeSheet}
|
||||
closeLabel={t('common.close')}
|
||||
/>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-[18px] pb-1">
|
||||
{stop.name && (
|
||||
<div className="truncate text-[0.875rem] font-semibold text-m-ink">{stop.name}</div>
|
||||
)}
|
||||
|
||||
{/* Wrapped rather than scrolled sideways: seven discs do not fit one phone row,
|
||||
and a row that scrolls hides the kinds past its edge behind a gesture. */}
|
||||
<div className="mt-[18px] flex flex-wrap justify-center gap-[10px]">
|
||||
{STOP_KINDS.map(({ key, labelKey, Icon, color }) => {
|
||||
const on = current === key
|
||||
return (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
aria-pressed={on}
|
||||
aria-label={t(labelKey)}
|
||||
disabled={!canEdit || saving}
|
||||
// Tapping the kind a stop already is takes it back to a destination,
|
||||
// the same second tap the desktop palette answers to.
|
||||
onClick={() => { void pick(on ? null : key) }}
|
||||
className="grid h-[54px] w-[54px] place-items-center rounded-[18px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] disabled:opacity-35"
|
||||
>
|
||||
<span
|
||||
className="grid h-[34px] w-[34px] place-items-center rounded-full text-white"
|
||||
// theme-lint-disable: the road-signage palette from roadtripModel, the
|
||||
// same one the chain disc and the map marker use, so the choice looks
|
||||
// like what it will become.
|
||||
style={{ background: color, ...(on ? { boxShadow: `0 0 0 3px color-mix(in srgb, ${color} 45%, transparent)` } : {}) }}
|
||||
>
|
||||
<Icon size={17} strokeWidth={2.1} aria-hidden="true" />
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Only once there is something to undo. On a destination it would be a button
|
||||
saying "leave everything as it is". */}
|
||||
{current && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={!canEdit || saving}
|
||||
onClick={() => { void pick(null) }}
|
||||
className="mt-[18px] flex w-full items-center justify-center gap-2 rounded-[14px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 py-3 text-[0.8125rem] font-semibold text-m-ink disabled:opacity-35"
|
||||
>
|
||||
<MapPin size={15} strokeWidth={2.2} className="flex-none text-m-muted" aria-hidden="true" />
|
||||
{t('roadtrip.stop.backToDestination')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</MSheet>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { ArrowRight, Minus, Plus } from 'lucide-react'
|
||||
import MSheet from '../../../components/MSheet'
|
||||
import MChip from '../../../components/MChip'
|
||||
import type { MTripSheetsProps } from '../MTripShell'
|
||||
import { useTranslation } from '../../../../i18n'
|
||||
import { useSettingsStore } from '../../../../store/settingsStore'
|
||||
import { formatClock, formatDurationShort, parseClock } from '../../../../components/Roadtrip/roadtripModel'
|
||||
import { stageOf } from '../../../../components/Roadtrip/roadtripRowModel'
|
||||
import { formatClockTime } from '../../../../utils/formatters'
|
||||
import { FormSheetHeader } from '../sheets/PlSheetChrome'
|
||||
import { INNER_CLS } from '../sheets/MTripSheetUi'
|
||||
|
||||
/** What the chain hands over when a stop's stay is tapped. */
|
||||
interface RtStaySheetPayload {
|
||||
placeId?: number
|
||||
/** The stay the place carries right now; absent and zero mean the same thing. */
|
||||
minutes?: number | null
|
||||
name?: string
|
||||
}
|
||||
|
||||
/** The step the two buttons move in. Same five minutes as the desktop dialog. */
|
||||
const STEP = 5
|
||||
|
||||
const DAY_MINUTES = 24 * 60
|
||||
|
||||
/**
|
||||
* As far as a stay goes, in minutes: a full day, like the desktop slider.
|
||||
*
|
||||
* Kept even though there is no slider here: the plus button has to stop somewhere, and
|
||||
* a stay longer than a day is a second day rather than a longer stop.
|
||||
*/
|
||||
const MAX = DAY_MINUTES
|
||||
|
||||
/**
|
||||
* The lengths a stop usually takes, so the common answer is one tap.
|
||||
*
|
||||
* The same eight the desktop offers. They are the whole of the coarse control here: the
|
||||
* desktop's slider runs 0 to 1440, which on a 343px phone row is four minutes a pixel,
|
||||
* and a control that cannot hit the value it is dragged to is worse than no control.
|
||||
*/
|
||||
const PRESETS = [15, 30, 45, 60, 90, 120, 480, 720]
|
||||
|
||||
const clampMinutes = (value: number): number => Math.min(MAX, Math.max(0, Math.round(value)))
|
||||
|
||||
/**
|
||||
* How long the traveller stays at one stop, on the phone ('rtstay', payload
|
||||
* { placeId, minutes, name }).
|
||||
*
|
||||
* Writes `places.duration_minutes` through `planner.setRoadtripStay`, which is the same
|
||||
* single write the desktop dialog makes. Zero rather than null clears it: the update
|
||||
* statement folds a null into "leave it alone", so a null could give a stop a stay but
|
||||
* never take one away.
|
||||
*
|
||||
* Two things this sheet deliberately does not do:
|
||||
*
|
||||
* 1. The two buttons do not auto-repeat on hold. Five-minute steps under a repeat land
|
||||
* forty minutes past the intended value about as often as they land on it, and the
|
||||
* eight presets already cover every length anybody holds a button for.
|
||||
* 2. The preview moves this stop's own departure and nothing else. Every later arrival
|
||||
* shifts too, but that is the routing round's answer after the write, and computing
|
||||
* second time here would be two sources for one number, and they would disagree the
|
||||
* first time a rule changed.
|
||||
*/
|
||||
export default function MRtStaySheet({ planner, shell }: MTripSheetsProps) {
|
||||
const { t } = useTranslation()
|
||||
const open = shell.sheet?.id === 'rtstay'
|
||||
const payload = (shell.sheet?.payload ?? {}) as RtStaySheetPayload
|
||||
const is12h = useSettingsStore(s => s.settings.time_format) === '12h'
|
||||
const canEdit = planner.can('place_edit', planner.trip)
|
||||
|
||||
// Hold the last payload so the name and the number survive the exit animation
|
||||
// instead of blinking out while the sheet slides away.
|
||||
const heldRef = useRef<RtStaySheetPayload | null>(null)
|
||||
if (open && typeof payload.placeId === 'number') heldRef.current = payload
|
||||
const stop = open && typeof payload.placeId === 'number' ? payload : heldRef.current
|
||||
|
||||
/** What the place carries now: the value the draft starts from and falls back to. */
|
||||
const stored = clampMinutes(stop?.minutes ?? 0)
|
||||
|
||||
const [minutes, setMinutes] = useState(stored)
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
// Reopened on a different stop, so it starts from that stop's own value rather than
|
||||
// from whatever the last one was left on.
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setMinutes(clampMinutes(payload.minutes ?? 0))
|
||||
setSaving(false)
|
||||
}, [open, payload.placeId, payload.minutes])
|
||||
|
||||
/**
|
||||
* When the drive gets here.
|
||||
*
|
||||
* Read off the stage (the one day both halves of the road trip tab show) rather than
|
||||
* passed in, so the arrival on screen is the arrival the chain drew, from the same
|
||||
* routing round, for the same day. A place planned on several days has an arrival per
|
||||
* day, and the stage is the day the tap came from.
|
||||
*/
|
||||
const stage = stageOf(planner.roadtripRoutes.days, planner.selectedDayId)
|
||||
const stopPlaceId = stop?.placeId
|
||||
const arrival = useMemo(() => {
|
||||
if (!stage || stopPlaceId == null) return null
|
||||
const index = stage.stops.findIndex(s => s.placeId === stopPlaceId)
|
||||
if (index === -1) return null
|
||||
return stage.schedule.entries[index]?.arrival ?? null
|
||||
}, [stage, stopPlaceId])
|
||||
|
||||
// What the stay does to this stop: the arrival is fixed by the drive, the departure is
|
||||
// the one end this sheet moves.
|
||||
const preview = useMemo(() => {
|
||||
const at = parseClock(arrival)
|
||||
if (at === null) return null
|
||||
return {
|
||||
arrive: formatClockTime(formatClock(at), is12h),
|
||||
leave: formatClockTime(formatClock(at + minutes), is12h),
|
||||
// `formatClock` wraps modulo 24 h, so a stay running past midnight reads as a small
|
||||
// number again. Without the carry the sheet would quietly promise "leave 01:00" for
|
||||
// a departure the chain places on the next day.
|
||||
carry: Math.floor((at + minutes) / DAY_MINUTES) - Math.floor(at / DAY_MINUTES),
|
||||
}
|
||||
}, [arrival, minutes, is12h])
|
||||
|
||||
const nudge = (delta: number) => setMinutes(m => clampMinutes(m + delta))
|
||||
|
||||
/**
|
||||
* Writes the draft, then hands the traveller back to the stop they came from.
|
||||
*
|
||||
* Reopening 'rtstop' is the point of the save: the times that just moved are shown
|
||||
* there, in the chain's own reading, so the change lands where it was asked for.
|
||||
* Closing without saving deliberately does not reopen it: nothing moved.
|
||||
*
|
||||
* `setRoadtripStay` reports its own failures and resolves either way, so the catch is
|
||||
* the second line rather than the first: what it guards is the sheet being left showing
|
||||
* a number the place does not have.
|
||||
*/
|
||||
const save = async () => {
|
||||
const placeId = stop?.placeId
|
||||
if (!canEdit || saving || placeId == null) return
|
||||
const value = minutes
|
||||
setSaving(true)
|
||||
try {
|
||||
await planner.setRoadtripStay(placeId, value)
|
||||
shell.openSheet('rtstop', { ...stop, placeId, minutes: value })
|
||||
} catch {
|
||||
setMinutes(stored)
|
||||
planner.toast.error(t('common.unknownError'))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const stepCls =
|
||||
'flex h-11 w-11 flex-none items-center justify-center rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] text-m-ink disabled:opacity-35'
|
||||
const captionCls = 'font-geist text-[0.5625rem] font-bold uppercase tracking-[.09em] text-m-faint'
|
||||
|
||||
return (
|
||||
<MSheet
|
||||
open={open && !!stop}
|
||||
onClose={shell.closeSheet}
|
||||
variant="bottom"
|
||||
material="opaque"
|
||||
ariaLabel={t('roadtrip.stay.add')}
|
||||
>
|
||||
{stop && (
|
||||
<>
|
||||
<FormSheetHeader
|
||||
title={t('roadtrip.stay.add')}
|
||||
onClose={shell.closeSheet}
|
||||
closeLabel={t('common.close')}
|
||||
/>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-[18px] pb-1">
|
||||
{/* Which stop, and what the number actually attaches to. The stay is a column
|
||||
on the place, not on the day's assignment, so a place planned twice keeps
|
||||
one stay for both, and saying so here is cheaper than the surprise. */}
|
||||
{stop.name && (
|
||||
<div className="truncate text-[0.875rem] font-semibold text-m-ink">{stop.name}</div>
|
||||
)}
|
||||
<div className="mt-[3px] font-geist text-[0.65625rem] leading-snug text-m-faint">
|
||||
{t('mobileTrip.rtStayScope')}
|
||||
</div>
|
||||
|
||||
{/* The number, the way a timer shows one, with minus and plus either side so a
|
||||
value can be nudged without a control to aim at. */}
|
||||
<div className="mt-[18px] flex items-center justify-center gap-5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => nudge(-STEP)}
|
||||
disabled={!canEdit || saving || minutes <= 0}
|
||||
aria-label={t('mobileTrip.rtStayLess', { count: STEP })}
|
||||
className={stepCls}
|
||||
>
|
||||
<Minus size={17} strokeWidth={2.2} aria-hidden="true" />
|
||||
</button>
|
||||
<div className="flex min-w-[6rem] flex-col items-center">
|
||||
<span
|
||||
aria-live="polite"
|
||||
className="text-[2.5rem] font-extrabold leading-none tabular-nums text-m-ink"
|
||||
>
|
||||
{minutes}
|
||||
</span>
|
||||
<span className="mt-[7px] font-geist text-[0.625rem] font-bold uppercase tracking-[.09em] text-m-faint">
|
||||
{t('roadtrip.stay.custom')}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => nudge(STEP)}
|
||||
disabled={!canEdit || saving || minutes >= MAX}
|
||||
aria-label={t('mobileTrip.rtStayMore', { count: STEP })}
|
||||
className={stepCls}
|
||||
>
|
||||
<Plus size={17} strokeWidth={2.2} aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* The eight usual answers. Read as durations rather than as raw minutes: a
|
||||
tile saying 480 is a number to work out, one saying 8 h is an answer. */}
|
||||
{canEdit && (
|
||||
<div className="mt-[18px] grid grid-cols-4 gap-[7px]">
|
||||
{PRESETS.map(value => (
|
||||
<MChip
|
||||
key={value}
|
||||
active={minutes === value}
|
||||
onClick={() => setMinutes(value)}
|
||||
className="h-11 w-full justify-center tabular-nums"
|
||||
>
|
||||
{formatDurationShort(value * 60)}
|
||||
</MChip>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Arrival, arrow, new departure. Only this stop's own two ends. */}
|
||||
{preview && (
|
||||
<div className={`mt-[18px] flex items-center justify-center gap-4 rounded-[16px] px-3 py-[11px] ${INNER_CLS}`}>
|
||||
<span className="flex flex-col items-center gap-[2px]">
|
||||
<span className={captionCls}>{t('roadtrip.stay.arrive')}</span>
|
||||
<span dir="ltr" className="text-[0.875rem] font-bold tabular-nums text-m-muted">
|
||||
{preview.arrive}
|
||||
</span>
|
||||
</span>
|
||||
<ArrowRight size={14} strokeWidth={2} className="mt-[11px] flex-none text-m-faint" aria-hidden="true" />
|
||||
<span className="flex flex-col items-center gap-[2px]">
|
||||
<span className={captionCls}>{t('roadtrip.stay.leave')}</span>
|
||||
<span dir="ltr" className="text-[0.875rem] font-bold tabular-nums text-m-ink">
|
||||
{preview.leave}
|
||||
{preview.carry > 0 && (
|
||||
<span className="ms-[3px]">
|
||||
{`+${preview.carry}`}
|
||||
<span className="sr-only">{` ${t('roadtrip.warn.overnight')}`}</span>
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-none items-center gap-2 border-t border-[color:var(--m-rowbr)] px-[18px] pb-4 pt-3">
|
||||
{/* Clearing is the same write as setting one, so it only fills the number in;
|
||||
the save below is still the one way anything is written. */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setMinutes(0)}
|
||||
disabled={!canEdit || saving || minutes === 0}
|
||||
className="inline-flex h-11 items-center rounded-full px-3 text-[0.8125rem] font-semibold text-[color:var(--m-st-danger)] disabled:opacity-40"
|
||||
>
|
||||
{t('roadtrip.stay.none')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { void save() }}
|
||||
disabled={!canEdit || saving}
|
||||
className="ml-auto inline-flex h-11 items-center rounded-full bg-m-act px-[18px] text-[0.8125rem] font-semibold text-m-actfg disabled:opacity-40"
|
||||
>
|
||||
{t('common.save')}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</MSheet>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode, type Ref } from 'react'
|
||||
import {
|
||||
AlertTriangle, Clock, Footprints, Fuel, Hourglass, MapPin, Moon, Navigation, Pencil, X,
|
||||
} from 'lucide-react'
|
||||
import MSheet from '../../../components/MSheet'
|
||||
import MIconBtn from '../../../components/MIconBtn'
|
||||
import MListRow from '../../../components/MListRow'
|
||||
import MToggle from '../../../components/MToggle'
|
||||
import type { MTripSheetsProps } from '../MTripShell'
|
||||
import { useTranslation } from '../../../../i18n'
|
||||
import { useSettingsStore } from '../../../../store/settingsStore'
|
||||
import { useTripStore } from '../../../../store/tripStore'
|
||||
import ChargingInfo from '../../../../components/Roadtrip/ChargingInfo'
|
||||
import { formatDurationShort } from '../../../../components/Roadtrip/roadtripModel'
|
||||
import { roadtripRows, stageOf, type StopRow } from '../../../../components/Roadtrip/roadtripRowModel'
|
||||
import { STOP_KIND_BY_KEY } from '../../../../components/Roadtrip/stopKinds'
|
||||
import { getNavigationTargets, openNavigationTarget } from '../../../../components/Planner/placeNavigation'
|
||||
import { NavigationMenu } from '../../../../components/shared/NavigationMenu'
|
||||
import { formatDistance } from '../../../../utils/units'
|
||||
import { Eyebrow, displayTime } from '../sheets/MTripSheetUi'
|
||||
import { showStopOnMap } from './useMRoadtrip'
|
||||
import type { DistanceUnit } from '../../../../types'
|
||||
import type { RoadtripDay, ScheduleWarning } from '@trek/shared/roadtrip'
|
||||
|
||||
/**
|
||||
* One stop of the stage, written out.
|
||||
*
|
||||
* The chain gives a stop a disc, a name, a clock and at most two marks, because that is
|
||||
* what a 375px line carries while somebody is driving. Everything the marks stand for is
|
||||
* here instead, as sentences: why the clock reads what it reads, how long the stay is,
|
||||
* how far the road stops short, and which limit the drive to here went past.
|
||||
*
|
||||
* Read-mostly on purpose. Deleting a stop, reordering the day, changing what kind of stop
|
||||
* it is and how full the tank leaves it are desktop work, done at a table before anybody
|
||||
* is in the car, and they are not here at all: not greyed out, not hidden behind a
|
||||
* confirmation, simply absent, because a dead control on a phone is a promise the screen
|
||||
* cannot keep. What is left are the three things a passenger does decide on the road:
|
||||
* navigate there, stay longer, stop for the night here.
|
||||
*
|
||||
* Editing the place is the one way out of that rule, and it is a hand-over rather than a
|
||||
* control of this sheet: the pencil opens the place editor the plan tab opens, with this
|
||||
* very visit in context, and this sheet closes behind it. The time somebody fixed for a
|
||||
* stop is that editor's start time (the chain anchors on the visit's own start time), so
|
||||
* a time control here would be a second writer for one number. A booked night can also
|
||||
* be held by its check-in, which belongs to the booking and not to the place.
|
||||
*/
|
||||
|
||||
interface RtStopSheetPayload {
|
||||
dayId?: number
|
||||
assignmentId?: number
|
||||
}
|
||||
|
||||
/** The stop the sheet is about, and the card it is drawn on. */
|
||||
interface Located {
|
||||
day: RoadtripDay
|
||||
row: StopRow
|
||||
/** Index into the CARD's stops, which is what every finding is filed under. */
|
||||
index: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the stop across the routed days.
|
||||
*
|
||||
* The caller names the day a stop is stored on (`ownerDayId`), which after a night drive
|
||||
* is not the card that draws it: a stop set off from on Tuesday and reached on Wednesday
|
||||
* appears in Wednesday's `stops`. So the named day is tried first and the rest after it,
|
||||
* rather than trusting one lookup that is right most of the time.
|
||||
*/
|
||||
function locate(days: readonly RoadtripDay[], dayId: number | null, assignmentId: number | null): Located | null {
|
||||
if (assignmentId == null) return null
|
||||
const named = stageOf(days, dayId)
|
||||
const search = named ? [named, ...days.filter(d => d !== named)] : days
|
||||
for (const day of search) {
|
||||
const index = day.stops.findIndex(s => s.assignmentId === assignmentId && !s.automaticNight)
|
||||
if (index < 0) continue
|
||||
const row = roadtripRows(day).find(
|
||||
(r): r is StopRow => r.kind === 'stop' && r.stop.assignmentId === assignmentId,
|
||||
)
|
||||
if (row) return { day, row, index }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** One finding: an icon, a sentence, and the figure it is about when that reads better apart. */
|
||||
function Finding({ icon, label, value, warn = false }: {
|
||||
icon: ReactNode
|
||||
label: string
|
||||
value?: string
|
||||
warn?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className="flex min-h-[44px] items-center gap-2.5 rounded-[13px] bg-[color:var(--m-ic)] px-3 py-2.5"
|
||||
style={warn ? { color: 'var(--m-st-pending)' } : undefined}
|
||||
>
|
||||
<span className={`flex-none ${warn ? '' : 'text-m-muted'}`} aria-hidden="true">{icon}</span>
|
||||
<span className={`min-w-0 flex-1 text-[0.75rem] font-medium leading-snug ${warn ? '' : 'text-m-muted'}`}>
|
||||
{label}
|
||||
</span>
|
||||
{value && (
|
||||
<span className={`flex-none text-[0.8125rem] font-semibold tabular-nums ${warn ? '' : 'text-m-ink'}`}>
|
||||
{value}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** One 56px action tile. Without a handler it stays a plain box instead of a dead button. */
|
||||
function ActionTile({ icon, label, value, onClick, tileRef }: {
|
||||
icon: ReactNode
|
||||
label: string
|
||||
value?: string
|
||||
onClick?: () => void
|
||||
tileRef?: Ref<HTMLButtonElement>
|
||||
}) {
|
||||
const inner = (
|
||||
<>
|
||||
<span className="flex-none text-m-muted" aria-hidden="true">{icon}</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-[0.8125rem] font-semibold text-m-ink">{label}</span>
|
||||
{value && (
|
||||
<span className="mt-px block truncate font-geist text-[0.65625rem] tabular-nums text-m-faint">{value}</span>
|
||||
)}
|
||||
</span>
|
||||
</>
|
||||
)
|
||||
const box = 'flex h-14 min-w-0 items-center gap-2.5 rounded-[14px] bg-[color:var(--m-ic)] px-3 text-left'
|
||||
if (!onClick) return <div className={box}>{inner}</div>
|
||||
return <button ref={tileRef} type="button" onClick={onClick} className={`${box} border-0`}>{inner}</button>
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop detail sheet ('rtstop', payload { dayId, assignmentId }) of the road trip tab.
|
||||
*/
|
||||
export default function MRtStopSheet({ planner, shell }: MTripSheetsProps) {
|
||||
const { t, locale } = useTranslation()
|
||||
const open = shell.sheet?.id === 'rtstop'
|
||||
const payload = (shell.sheet?.payload ?? {}) as RtStopSheetPayload
|
||||
|
||||
const timeFormat = useSettingsStore(s => s.settings.time_format) || '24h'
|
||||
const unitSetting = useSettingsStore(s => s.settings.distance_unit)
|
||||
const unit: DistanceUnit = unitSetting === 'imperial' ? 'imperial' : 'metric'
|
||||
const tripPlaces = useTripStore(s => s.places)
|
||||
|
||||
const days = planner.roadtripRoutes.days
|
||||
const live = useMemo(
|
||||
() => locate(days, payload.dayId ?? null, payload.assignmentId ?? null),
|
||||
[days, payload.dayId, payload.assignmentId],
|
||||
)
|
||||
|
||||
// Hold the last stop so the card keeps its content through the 280ms exit.
|
||||
const heldRef = useRef<Located | null>(null)
|
||||
if (live) heldRef.current = live
|
||||
const located = live ?? heldRef.current
|
||||
|
||||
const [navOpen, setNavOpen] = useState(false)
|
||||
const navBtnRef = useRef<HTMLButtonElement>(null)
|
||||
const [saving, setSaving] = useState(false)
|
||||
// The end-day switch, as it should read while the write is in the air.
|
||||
const [pending, setPending] = useState<{ from: boolean; to: boolean } | null>(null)
|
||||
useEffect(() => {
|
||||
if (!open) { setNavOpen(false); setPending(null) }
|
||||
}, [open])
|
||||
useEffect(() => { setPending(null) }, [payload.assignmentId])
|
||||
|
||||
const stop = located?.row.stop ?? null
|
||||
// From the whole trip store, not planner.places: with service stops hidden from the day
|
||||
// lists the phone filters them out of that list, while the stage still draws them, and
|
||||
// both the pencil and the directions have to reach the row the chain drew.
|
||||
const place = tripPlaces.find(p => p.id === stop?.placeId) ?? null
|
||||
|
||||
/**
|
||||
* Addressed by stop, not by selection.
|
||||
*
|
||||
* `planner.roadtripEndDay` derives itself from the place selection, which is what the
|
||||
* desktop inspector needs. Here that would mean moving the selection to open a sheet,
|
||||
* and the place inspector hangs off the same value and would come up underneath. So
|
||||
* the stage sheet calls the stop-addressed writer directly.
|
||||
*/
|
||||
const canEndDay = stop != null && planner.dailyTimesActive && planner.can('day_edit', planner.trip)
|
||||
const endDayTruth = !!stop?.endDay
|
||||
// The optimistic value is released the moment the planner's own answer moves off what
|
||||
// it was taken from, so a landed write shows the real state rather than a copy of it.
|
||||
const endDayActive = pending && pending.from === endDayTruth ? pending.to : endDayTruth
|
||||
|
||||
if (!located || !stop) {
|
||||
return <MSheet open={false} onClose={shell.closeSheet} variant="bottom" />
|
||||
}
|
||||
|
||||
const { day, row, index } = located
|
||||
const kind = stop.stopType ? STOP_KIND_BY_KEY[stop.stopType] : undefined
|
||||
const KindIcon = kind?.Icon
|
||||
|
||||
const entry = row.entry
|
||||
const arrive = displayTime(entry?.arrival, locale, timeFormat)
|
||||
const leave = displayTime(entry?.departure, locale, timeFormat)
|
||||
|
||||
// Every finding filed at this stop, not just the one the chain had room for: being late
|
||||
// and driving too far are separate answers and the sheet is where both fit.
|
||||
const warnings: ScheduleWarning[] = [
|
||||
...day.schedule.warnings.filter(w => w.index === index && w.code === 'late'),
|
||||
...day.driveWarnings.filter(w => w.index === index && (w.code === 'leg' || w.code === 'range')),
|
||||
]
|
||||
const warningText = (w: ScheduleWarning): string => {
|
||||
if (w.code === 'late') return t('roadtrip.warn.late', { minutes: w.minutes ?? 0 })
|
||||
if (w.code === 'range') return t('roadtrip.limit.range', { distance: formatDistance(w.sinceKm ?? 0, unit) })
|
||||
return t('roadtrip.limit.legOver', { time: formatDurationShort((w.overMinutes ?? 0) * 60) })
|
||||
}
|
||||
const warningIcon = (w: ScheduleWarning): ReactNode => {
|
||||
if (w.code === 'late') return <AlertTriangle size={15} strokeWidth={2} />
|
||||
if (w.code === 'range') return <Fuel size={15} strokeWidth={2} />
|
||||
return <Hourglass size={15} strokeWidth={2} />
|
||||
}
|
||||
|
||||
// One app offered means no picker: the tap opens it, exactly as the place sheet does.
|
||||
// The stop's own name and position stand in when the place row is not to hand, so the
|
||||
// one control a driver actually needs is there whatever else the device is missing.
|
||||
const navTargets = getNavigationTargets(place ?? { name: stop.name, lat: stop.lat, lng: stop.lng })
|
||||
const openDirections = () => {
|
||||
if (navTargets.length === 1) openNavigationTarget(navTargets[0])
|
||||
else if (navTargets.length > 1) setNavOpen(true)
|
||||
}
|
||||
|
||||
const stayMinutes = stop.dwellMinutes
|
||||
const canEditPlace = planner.can('place_edit', planner.trip)
|
||||
const editStay = () => {
|
||||
shell.openSheet('rtstay', { placeId: stop.placeId, minutes: stayMinutes })
|
||||
}
|
||||
|
||||
// A negative id is the optimistic row of a stop still being saved. The editor would
|
||||
// write the time against an id the server never issued, and handing it null instead is
|
||||
// no way round that: the planner then falls back to the place's only visit, which can be
|
||||
// that same row. So the pencil waits until the stop carries the id the server gave it.
|
||||
const canOpenEditor = canEditPlace && place != null && stop.assignmentId > 0
|
||||
const editPlace = () => {
|
||||
if (!place) return
|
||||
planner.openPlaceEditor(place, stop.assignmentId)
|
||||
shell.closeSheet()
|
||||
}
|
||||
|
||||
const toggleEndDay = async (next: boolean) => {
|
||||
if (!canEndDay || saving) return
|
||||
setPending({ from: endDayTruth, to: next })
|
||||
setSaving(true)
|
||||
try {
|
||||
await planner.setRoadtripEndDay(stop)
|
||||
} catch (err: unknown) {
|
||||
setPending(null)
|
||||
planner.toast.error(err instanceof Error ? err.message : t('common.unknownError'))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
// The camera rather than the place selection, for the reason the end-day switch above
|
||||
// stays off it: the place inspector would come up over the map. `day` is the card the
|
||||
// stop is drawn on, so a stop reached after a night drive shows on the stage that has it.
|
||||
const showOnMap = () => {
|
||||
showStopOnMap(planner, shell, stop, day.dayId)
|
||||
shell.closeSheet()
|
||||
}
|
||||
|
||||
const tiles = (navTargets.length > 0 ? 1 : 0) + 1
|
||||
|
||||
return (
|
||||
<MSheet open={open && !!live} onClose={shell.closeSheet} variant="bottom" material="opaque" ariaLabel={stop.name}>
|
||||
{/* ── Header: the disc the chain draws, the name, the way to the editor and the way out ── */}
|
||||
<div className="flex-none px-[18px] pt-4">
|
||||
{/* Centred, not top-aligned: one line of the name is shorter than the 34px disc, so
|
||||
hung from the top it sat high beside it. A name that wraps to its two lines grows
|
||||
the row, and the disc and the buttons centre on both, as they do in the chain row. */}
|
||||
<div className="flex items-center gap-3">
|
||||
{row.service ? (
|
||||
kind && KindIcon ? (
|
||||
<span
|
||||
className="grid h-[34px] w-[34px] flex-none place-items-center rounded-full text-white"
|
||||
// theme-lint-disable: the stop kinds share their colour with the map
|
||||
// markers, which sit on tiles rather than on one of the app's surfaces.
|
||||
style={{ background: kind.color }}
|
||||
>
|
||||
<KindIcon size={16} strokeWidth={2.1} aria-hidden="true" />
|
||||
</span>
|
||||
) : (
|
||||
<span className="grid h-[34px] w-[34px] flex-none place-items-center rounded-full bg-[color:var(--m-ic)] text-m-muted">
|
||||
<MapPin size={16} strokeWidth={2} aria-hidden="true" />
|
||||
</span>
|
||||
)
|
||||
) : (
|
||||
// Deliberately not font-geist: that tier caps the weight at Medium and would
|
||||
// quietly undo the bold on a number that has to read at 13px.
|
||||
<span className="grid h-[34px] w-[34px] flex-none place-items-center rounded-full bg-[color:var(--m-ic)] text-[0.8125rem] font-bold tabular-nums text-m-ink">
|
||||
{row.number}
|
||||
</span>
|
||||
)}
|
||||
<h2 className="min-w-0 flex-1 line-clamp-2 text-[1.0625rem] font-bold leading-tight text-m-ink">
|
||||
{stop.name}
|
||||
</h2>
|
||||
<div className="flex flex-none items-center gap-2">
|
||||
{canOpenEditor && (
|
||||
<MIconBtn variant="neutral" size={34} onClick={editPlace} ariaLabel={t('common.edit')}>
|
||||
<Pencil size={15} strokeWidth={2.2} />
|
||||
</MIconBtn>
|
||||
)}
|
||||
<MIconBtn variant="neutral" size={34} onClick={shell.closeSheet} ariaLabel={t('common.close')}>
|
||||
<X size={15} strokeWidth={2.2} />
|
||||
</MIconBtn>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-[18px] pb-[18px]">
|
||||
{/* ── The two clock readings, and where they come from ── */}
|
||||
{(arrive || leave) && (
|
||||
<div className="mt-[14px] rounded-[16px] bg-[color:var(--m-inner)] px-3.5 py-3">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
{arrive && (
|
||||
<div className="min-w-0">
|
||||
<Eyebrow>{t('roadtrip.stay.arrive')}</Eyebrow>
|
||||
{/* dir=ltr so a clock reads the same way round in an RTL locale. */}
|
||||
<div dir="ltr" className="mt-1 text-[1.375rem] font-extrabold leading-none tabular-nums text-m-ink">
|
||||
{arrive}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{leave && (
|
||||
<div className="min-w-0 ms-auto text-end">
|
||||
<Eyebrow>{t('roadtrip.stay.leave')}</Eyebrow>
|
||||
<div dir="ltr" className="mt-1 text-[1.375rem] font-extrabold leading-none tabular-nums text-m-ink">
|
||||
{leave}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{/* The desktop says this in a tooltip, which a phone has nowhere to put. */}
|
||||
<div className="mt-2 font-geist text-[0.65625rem] leading-snug text-m-faint">
|
||||
{entry?.anchored ? t('roadtrip.stop.pinned') : t('roadtrip.stop.computed')}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── What this stop costs, and what the drive to it went past ── */}
|
||||
{(!!stayMinutes || !!row.offRoadMeters || warnings.length > 0) && (
|
||||
<div className="mt-2.5 flex flex-col gap-2">
|
||||
{!!stayMinutes && (
|
||||
<Finding
|
||||
icon={<Hourglass size={15} strokeWidth={2} />}
|
||||
label={t('roadtrip.stop.stayShort')}
|
||||
value={formatDurationShort(stayMinutes * 60)}
|
||||
/>
|
||||
)}
|
||||
{!!row.offRoadMeters && (
|
||||
<Finding
|
||||
icon={<Footprints size={15} strokeWidth={2} />}
|
||||
label={t('roadtrip.stop.offRoad', { distance: formatDistance(row.offRoadMeters / 1000, unit) })}
|
||||
/>
|
||||
)}
|
||||
{warnings.map(w => (
|
||||
<Finding key={`${w.code}-${w.index}`} icon={warningIcon(w)} label={warningText(w)} warn />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Charging: availability and price, polled only while the sheet is up ── */}
|
||||
{open && stop.stopType === 'charging' && (
|
||||
<div className="mt-2.5">
|
||||
<ChargingInfo placeId={stop.placeId} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── The two decisions a passenger makes on the road ── */}
|
||||
<div className={`mt-2.5 grid gap-2 ${tiles > 1 ? 'grid-cols-2' : 'grid-cols-1'}`}>
|
||||
{navTargets.length > 0 && (
|
||||
<ActionTile
|
||||
tileRef={navBtnRef}
|
||||
icon={<Navigation size={16} strokeWidth={2} />}
|
||||
label={t('inspector.navigation')}
|
||||
value={navTargets.length === 1 ? navTargets[0].label : undefined}
|
||||
onClick={openDirections}
|
||||
/>
|
||||
)}
|
||||
<ActionTile
|
||||
icon={<Clock size={16} strokeWidth={2} />}
|
||||
label={t('roadtrip.stop.stayShort')}
|
||||
value={stayMinutes ? formatDurationShort(stayMinutes * 60) : t('roadtrip.stay.none')}
|
||||
onClick={canEditPlace ? editStay : undefined}
|
||||
/>
|
||||
</div>
|
||||
{navOpen && (
|
||||
<NavigationMenu
|
||||
targets={navTargets}
|
||||
anchor={navBtnRef.current}
|
||||
onClose={() => setNavOpen(false)}
|
||||
title={t('inspector.openWith')}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* ── Stopping here for the night. Offline too: it is a plan, not a lookup. ── */}
|
||||
{canEndDay && (
|
||||
<div className="mt-2.5 flex min-h-[44px] items-center gap-2.5 rounded-[13px] bg-[color:var(--m-ic)] px-3 py-2">
|
||||
<Moon
|
||||
size={16}
|
||||
strokeWidth={2}
|
||||
className={`flex-none ${endDayActive ? 'text-m-ink' : 'text-m-muted'}`}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="min-w-0 flex-1 text-[0.8125rem] font-semibold text-m-ink">
|
||||
{t('roadtrip.window.endHere')}
|
||||
</span>
|
||||
<MToggle
|
||||
checked={endDayActive}
|
||||
onChange={next => { void toggleEndDay(next) }}
|
||||
ariaLabel={t('roadtrip.window.endHere')}
|
||||
disabled={saving}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Out to the map, with the stop marked on it ── */}
|
||||
<div className="mt-2 border-t border-[color:var(--m-rowbr)] pt-2">
|
||||
<MListRow
|
||||
icon={MapPin}
|
||||
label={t('mobileTrip.showOnMap')}
|
||||
onClick={showOnMap}
|
||||
className="min-h-[44px]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</MSheet>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { badgeLabel, distanceBadge } from './stageBadges'
|
||||
|
||||
// FE-MOB-RTBADGE-001 to FE-MOB-RTBADGE-004
|
||||
|
||||
describe('distanceBadge', () => {
|
||||
it('FE-MOB-RTBADGE-001: formats metres in the traveller\'s own unit', () => {
|
||||
expect(distanceBadge(412_000, 'metric')).toBe('412 km')
|
||||
expect(distanceBadge(412_000, 'imperial')).toBe('256 mi')
|
||||
// A short hop keeps its metres reading, the one the route connectors print.
|
||||
expect(distanceBadge(300, 'metric')).toBe('300 m')
|
||||
})
|
||||
|
||||
it('FE-MOB-RTBADGE-002: nothing measured is no badge, never a 0 m one', () => {
|
||||
expect(distanceBadge(0, 'metric')).toBeNull()
|
||||
expect(distanceBadge(-5, 'metric')).toBeNull()
|
||||
expect(distanceBadge(Number.NaN, 'metric')).toBeNull()
|
||||
expect(distanceBadge(Number.POSITIVE_INFINITY, 'imperial')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('badgeLabel', () => {
|
||||
it('FE-MOB-RTBADGE-003: joins the parts with a comma and leaves the empty ones out', () => {
|
||||
expect(badgeLabel(['Sat 2', null, '', undefined, '123 km'])).toBe('Sat 2, 123 km')
|
||||
})
|
||||
|
||||
it('FE-MOB-RTBADGE-004: a single part is itself, and no parts is an empty name', () => {
|
||||
expect(badgeLabel(['Sat 2'])).toBe('Sat 2')
|
||||
expect(badgeLabel([])).toBe('')
|
||||
expect(badgeLabel([null, undefined])).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,32 @@
|
||||
import { formatDistance } from '../../../../utils/units'
|
||||
import type { DistanceUnit } from '../../../../types'
|
||||
|
||||
/**
|
||||
* What the two bars of the road trip tab put in their badges, kept out of their markup.
|
||||
*
|
||||
* Phone only: the shell's stage header and the stage bar over the map are the two places
|
||||
* that draw these figures as badges, and the desktop has neither of them.
|
||||
*/
|
||||
|
||||
/**
|
||||
* A distance as a badge reads it, or null when there is nothing to read.
|
||||
*
|
||||
* Nothing measured is no badge rather than a "0 m" one. A stage sits at zero while its
|
||||
* legs are still routing, and a zero in a badge reads as a drive that goes nowhere, which
|
||||
* is a claim, where a missing badge only says that the figure is not there yet.
|
||||
*/
|
||||
export function distanceBadge(meters: number, unit: DistanceUnit): string | null {
|
||||
return Number.isFinite(meters) && meters > 0 ? formatDistance(meters / 1000, unit) : null
|
||||
}
|
||||
|
||||
/**
|
||||
* The accessible name of a button made of badges.
|
||||
*
|
||||
* The eye separates two pills by their edges, but the name a screen reader builds from
|
||||
* them runs the texts together ("Sat 2123 km"), so the button spells the separators out.
|
||||
* A comma rather than Intl.ListFormat: the parts are facts in a row, not a list with an
|
||||
* "and" before its last item, and the client's ES2020 lib does not type that API anyway.
|
||||
*/
|
||||
export function badgeLabel(parts: readonly (string | null | undefined)[]): string {
|
||||
return parts.filter((part): part is string => !!part).join(', ')
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { destinationCount, roadtripRows, stageClocks, stageEnd, stageOf, upNextStop } from '../../../../components/Roadtrip/roadtripRowModel'
|
||||
import { useRoadtripSettings } from '../../../../hooks/useRoadtripSettings'
|
||||
import { useSettingsStore } from '../../../../store/settingsStore'
|
||||
import { useTripStore } from '../../../../store/tripStore'
|
||||
import { isEffectivelyOffline, onNetworkModeChange } from '../../../../sync/networkMode'
|
||||
import type { RoadtripDay } from '@trek/shared/roadtrip'
|
||||
import type { MTripShellApi, TripPlanner } from '../MTripShell'
|
||||
import type { RoadtripRow, StopRow } from '../../../../components/Roadtrip/roadtripRowModel'
|
||||
import type { Category, Place } from '../../../../types'
|
||||
|
||||
/** Minutes since midnight, local time. */
|
||||
const nowMinutes = (): number => {
|
||||
const d = new Date()
|
||||
return d.getHours() * 60 + d.getMinutes()
|
||||
}
|
||||
|
||||
/** The same 30 s tick the day timeline runs on, so the two never disagree by a minute. */
|
||||
const TICK_MS = 30_000
|
||||
|
||||
export interface MRoadtripController {
|
||||
stage: RoadtripDay | null
|
||||
rows: RoadtripRow[]
|
||||
/** The head card's two figures, both taken from the arrival column the rows print. See stageClocks. */
|
||||
clocks: ReturnType<typeof stageClocks>
|
||||
/** The stop the bar over the map names, pictures and opens, with the clock it shows. See stageEnd. */
|
||||
end: StopRow | null
|
||||
/** The place row behind `end`, for the picture the bar leads with. Null without one. */
|
||||
endPlace: Place | null
|
||||
/** Its category, whose icon and colour stand in for a place that has no photo. */
|
||||
endCategory: Category | null
|
||||
stops: number
|
||||
/** True while the routing round is still working through the trip's days. */
|
||||
loading: boolean
|
||||
/** The trip has the addon on but nothing routable: one place on a day is not a drive. */
|
||||
empty: boolean
|
||||
offline: boolean
|
||||
electric: boolean
|
||||
/** Next destination the plan still owes, today only. Negative minutesUntil is late. */
|
||||
upNext: ReturnType<typeof upNextStop>
|
||||
isToday: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything the stage screen needs, kept out of its markup.
|
||||
*
|
||||
* The clock is the only moving part: a screen that shows a morning's plan all day
|
||||
* quietly lies once you leave twenty minutes late, and the fix is arithmetic on the
|
||||
* schedule rather than a request. Nothing here asks the network for anything.
|
||||
*/
|
||||
export function useMRoadtrip(planner: TripPlanner): MRoadtripController {
|
||||
const { roadtripRoutes, selectedDayId, days } = planner
|
||||
const vehicle = useRoadtripSettings(s => s.roadtrip_vehicle, planner.tripId)
|
||||
const [minutes, setMinutes] = useState(nowMinutes)
|
||||
const [offline, setOffline] = useState(isEffectivelyOffline)
|
||||
|
||||
useEffect(() => {
|
||||
const id = window.setInterval(() => setMinutes(nowMinutes()), TICK_MS)
|
||||
return () => window.clearInterval(id)
|
||||
}, [])
|
||||
|
||||
useEffect(() => onNetworkModeChange(() => setOffline(isEffectivelyOffline())), [])
|
||||
|
||||
const stage = useMemo(
|
||||
() => stageOf(roadtripRoutes.days, selectedDayId),
|
||||
[roadtripRoutes.days, selectedDayId],
|
||||
)
|
||||
|
||||
const rows = useMemo(() => (stage ? roadtripRows(stage) : []), [stage])
|
||||
const clocks = useMemo(() => stageClocks(rows), [rows])
|
||||
const end = useMemo(() => stageEnd(rows), [rows])
|
||||
|
||||
// The place behind the end comes from the whole trip store, not planner.places: with
|
||||
// service stops hidden from the day lists the phone filters them out of that list, while
|
||||
// the stage still draws them, and a day that ends at a hidden campsite still ends there.
|
||||
// The stop sheet and the stage pins read the same list for the same reason.
|
||||
const tripPlaces = useTripStore(s => s.places)
|
||||
const endPlace = useMemo(
|
||||
() => (end ? tripPlaces.find(p => p.id === end.stop.placeId) ?? null : null),
|
||||
[end, tripPlaces],
|
||||
)
|
||||
const categories = planner.categories
|
||||
const endCategory = useMemo(
|
||||
() => (endPlace?.category_id == null ? null : categories.find(c => c.id === endPlace.category_id) ?? null),
|
||||
[endPlace, categories],
|
||||
)
|
||||
|
||||
// "Today" is the stage's own date, not the selected day's index: a trip can be
|
||||
// planned for next year, and a countdown on a day in March is noise.
|
||||
const isToday = useMemo(() => {
|
||||
const date = days.find(d => d.id === selectedDayId)?.date
|
||||
if (!date) return false
|
||||
return date.slice(0, 10) === new Date().toISOString().slice(0, 10)
|
||||
}, [days, selectedDayId])
|
||||
|
||||
return {
|
||||
stage,
|
||||
rows,
|
||||
clocks,
|
||||
end,
|
||||
endPlace,
|
||||
endCategory,
|
||||
stops: stage ? destinationCount(stage) : 0,
|
||||
loading: roadtripRoutes.loading,
|
||||
empty: !roadtripRoutes.loading && roadtripRoutes.days.length === 0,
|
||||
offline,
|
||||
electric: vehicle === 'electric',
|
||||
upNext: upNextStop(stage, minutes, isToday),
|
||||
isToday,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Brings one stop of the drive into view on the map half, from wherever it was asked for.
|
||||
*
|
||||
* Through the camera and never through the planner's place selection: the place inspector
|
||||
* opens off that selection, so selecting the place came up with the plan tab's card over
|
||||
* the very map this was meant to show. The corridor search shows its hits the same way.
|
||||
*
|
||||
* `cardDayId` is the card the stop is DRAWN on, which after a night drive is not the day it
|
||||
* is stored on. When that card is not the stage on screen it becomes the stage first, so the
|
||||
* line around the stop the camera lands on is the stage the bar is about. With skipFit, as
|
||||
* the day swipe does it: on the stage the camera follows focus points, and here the focus
|
||||
* is the stop. The map area lets a focus go once the day moves off the one it arrived with,
|
||||
* so the day is picked first, in the same tap, and the focus arrives together with it
|
||||
* instead of being let go by it (see MMapArea).
|
||||
*/
|
||||
export function showStopOnMap(
|
||||
planner: TripPlanner,
|
||||
shell: MTripShellApi,
|
||||
stop: { lat: number; lng: number },
|
||||
cardDayId: number,
|
||||
): void {
|
||||
if (planner.selectedDayId !== cardDayId) planner.handleSelectDay(cardDayId, true)
|
||||
planner.focusRoadtripPoint(stop.lat, stop.lng)
|
||||
if (shell.rtView === 'list') shell.toggleRtView()
|
||||
}
|
||||
|
||||
/** The trip's own distance unit, for every figure the stage prints. */
|
||||
export function useDistanceUnit() {
|
||||
return useSettingsStore(s => s.settings.distance_unit)
|
||||
}
|
||||
|
||||
/** Kept for the tick's identity in tests. */
|
||||
export const ROADTRIP_TICK_MS = TICK_MS
|
||||
@@ -0,0 +1,136 @@
|
||||
import { useEffect, useTransition } from 'react'
|
||||
import { alternativesPhase, type AlternativeOverlay, type AlternativesPhase } from '../../../../components/Roadtrip/alternativeOverlays'
|
||||
import type { LegAlternatives } from '../../../../components/Roadtrip/useRouteAlternatives'
|
||||
import type { MTripShellApi, TripPlanner } from '../MTripShell'
|
||||
|
||||
/**
|
||||
* The alternatives bar's fixed height, in pixels. MRtAlternativesBar is drawn at exactly
|
||||
* this, and the map floor below is worked out from it, so the two cannot drift apart.
|
||||
*/
|
||||
export const RT_ALT_BAR_HEIGHT = 174
|
||||
|
||||
/**
|
||||
* How far the map floor rises while the alternatives bar stands over the dock, in pixels.
|
||||
*
|
||||
* The bar's height plus the 15px gap between the top of the dock and the foot of a bar
|
||||
* standing over it. So the floor lands on this bar's top edge and the round controls
|
||||
* clear it rather than sitting in it. It is the only bar left in that slot: the stage bar
|
||||
* that used to hold it whenever the map was up is gone.
|
||||
*
|
||||
* A number rather than a CSS length because the map's fit padding is added up from it.
|
||||
* Kept in this module rather than in the bar's, so the map area reads it without pulling
|
||||
* a component in.
|
||||
*/
|
||||
export const RT_ALT_BAR_LIFT = RT_ALT_BAR_HEIGHT + 15
|
||||
|
||||
export interface MRtAlternativesController {
|
||||
/** The leg being reconsidered and what came back for it. Null while no picker is open. */
|
||||
open: LegAlternatives | null
|
||||
/** The very overlays the map draws, so a chip and its line can never disagree. */
|
||||
overlays: AlternativeOverlay[]
|
||||
/** Which of its four states the open picker is in. Null while none is open. */
|
||||
phase: AlternativesPhase | null
|
||||
/** The road a tap is previewing, lit on the map and waiting for confirm. */
|
||||
picked: AlternativeOverlay | null
|
||||
/** May this person reshape the drive at all. Without it no leg offers the question. */
|
||||
canAsk: boolean
|
||||
/** False offline: a choice is written as a via, and vias are online only. */
|
||||
editable: boolean
|
||||
canConfirm: boolean
|
||||
/** True while the chosen road is being written. */
|
||||
saving: boolean
|
||||
isOpenFor: (dayId: number, legIndex: number) => boolean
|
||||
ask: (dayId: number, legIndex: number) => void
|
||||
pick: (index: number) => void
|
||||
confirm: () => void
|
||||
cancel: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Other ways of driving a leg, as a phone asks for them and takes one.
|
||||
*
|
||||
* Holds no picker state of its own. The road trip tab is mounted in two places, one per
|
||||
* half of the list and map switch, so it remounts on every toggle, and a picker living
|
||||
* here would be gone the moment somebody looked back at the chain. Everything stays in
|
||||
* the planner, where the desk keeps it too: the open leg, the offers, the overlays and
|
||||
* the road lit on the map. What this adds is what a desk does not need.
|
||||
*
|
||||
* A tap previews and a confirm takes. On the desk a pointer hovers to preview and a
|
||||
* click writes; glass has no hover, so the first touch on a chip or a line would already
|
||||
* be the write. Here that touch only lights the road (`pick`), and the bar's button
|
||||
* commits it (`confirm`).
|
||||
*
|
||||
* The question is always about the leg on screen. Asking goes to the map, where the
|
||||
* answer is drawn, and a stage change closes the picker, because offers drawn for a leg
|
||||
* of another day are lines nobody on this stage asked about.
|
||||
*/
|
||||
export function useMRtAlternatives(planner: TripPlanner, shell: MTripShellApi): MRtAlternativesController {
|
||||
const { open, close } = planner.routeAlternatives
|
||||
const overlays = planner.alternativeOverlays
|
||||
const editable = planner.roadtripVias.editable
|
||||
const [saving, startSaving] = useTransition()
|
||||
|
||||
const phase = open ? alternativesPhase(open, overlays) : null
|
||||
const highlighted = planner.highlightedAlternative
|
||||
const picked = highlighted == null ? null : overlays.find(o => o.index === highlighted) ?? null
|
||||
// The road already driven is no choice: taking it writes nothing and only closes the
|
||||
// picker, which the close button already does without pretending to save.
|
||||
const canConfirm = !!picked && phase === 'choose' && !open?.routes[picked.index]?.current && editable && !saving
|
||||
|
||||
const isOpenFor = (dayId: number, legIndex: number) => open?.dayId === dayId && open.index === legIndex
|
||||
|
||||
// The day chips, a swipe and the all days switch all move the stage under an open
|
||||
// picker. `close` is the planner's stable callback, so this runs when the leg or the
|
||||
// stage changes and not on every render.
|
||||
const selectedDayId = planner.selectedDayId
|
||||
useEffect(() => {
|
||||
if (open && open.dayId !== selectedDayId) close()
|
||||
}, [open, selectedDayId, close])
|
||||
|
||||
const ask = (dayId: number, legIndex: number) => {
|
||||
// The planner's own ask toggles a leg that is already open, which is the desk
|
||||
// button's second click. Here the pressed button on the chain is the way back to the
|
||||
// answer on the map, so it must not close what it is pointing at.
|
||||
if (!isOpenFor(dayId, legIndex)) {
|
||||
// A pick belongs to the leg it was made on. Carried over, it would light a road
|
||||
// on the next leg by its position in a list that leg never offered.
|
||||
planner.setHighlightedAlternative(null)
|
||||
// An open fuel search keeps the camera on its stations (see mapFocusPoints), so the
|
||||
// leg would be asked about and never framed. The picker is modal on the map anyway.
|
||||
planner.refuel.close()
|
||||
// The card's day, as the desk passes it: the planner looks the stops up on that
|
||||
// card and works out the day each one is stored on by itself.
|
||||
planner.askRouteAlternatives(dayId, legIndex)
|
||||
}
|
||||
if (shell.rtView === 'list') shell.toggleRtView()
|
||||
}
|
||||
|
||||
const pick = (index: number) => planner.setHighlightedAlternative(index)
|
||||
|
||||
const confirm = () => {
|
||||
if (!canConfirm || !picked) return
|
||||
const index = picked.index
|
||||
// A transition rather than a flag of our own, so the pending state ends when the
|
||||
// write does. The planner reports a failure itself and leaves the picker open for
|
||||
// another go, and closes it once the via is saved.
|
||||
startSaving(async () => {
|
||||
await planner.chooseRouteAlternative(index)
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
open,
|
||||
overlays,
|
||||
phase,
|
||||
picked,
|
||||
canAsk: planner.can('day_edit', planner.trip),
|
||||
editable,
|
||||
canConfirm,
|
||||
saving,
|
||||
isOpenFor,
|
||||
ask,
|
||||
pick,
|
||||
confirm,
|
||||
cancel: close,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import { useCallback, useEffect, useMemo } from 'react'
|
||||
import { anchorKmFor, corridorWindow, PHONE_REACH_KM, type CorridorReach } from '../../../../components/Roadtrip/corridorSearchModel'
|
||||
import { stageOf, upNextStop } from '../../../../components/Roadtrip/roadtripRowModel'
|
||||
import { useNetworkMode } from '../../../../hooks/useNetworkMode'
|
||||
import type { CorridorPoi } from '../../../../components/Roadtrip/useCorridorPois'
|
||||
import type { MTripShellApi, TripPlanner } from '../MTripShell'
|
||||
|
||||
/** Minutes since midnight, local time: the same reading the stage screen takes. */
|
||||
const nowMinutes = (): number => {
|
||||
const d = new Date()
|
||||
return d.getHours() * 60 + d.getMinutes()
|
||||
}
|
||||
|
||||
export interface MRtCorridorController {
|
||||
/** What is being looked for. Several at once: they ride one query per box. */
|
||||
categories: string[]
|
||||
toggleCategory: (key: string) => void
|
||||
/** How much of the stage the next search covers. */
|
||||
reach: CorridorReach
|
||||
setReach: (value: CorridorReach) => void
|
||||
/** How far "ahead" reaches, in kilometres of driving. */
|
||||
reachKm: number
|
||||
/**
|
||||
* True when "ahead" would start at the stop the clock says is next, false when it
|
||||
* starts at the beginning of the stage. The sheet says which, because that difference
|
||||
* is the whole meaning of the answer.
|
||||
*/
|
||||
anchored: boolean
|
||||
/** Asks. Does nothing without a route, a category and a connection. */
|
||||
run: () => void
|
||||
/** Throws the answer away, pins included. */
|
||||
clear: () => void
|
||||
canSearch: boolean
|
||||
loading: boolean
|
||||
progress: { done: number; total: number }
|
||||
/** What was found, in driving order, and the same array the map draws. */
|
||||
hits: CorridorPoi[]
|
||||
/** True once a search has run and left something to read. */
|
||||
answered: boolean
|
||||
offline: boolean
|
||||
error: boolean
|
||||
capped: boolean
|
||||
failedAreas: number
|
||||
truncatedAreas: number
|
||||
}
|
||||
|
||||
/**
|
||||
* The corridor search, as a phone asks it.
|
||||
*
|
||||
* The state itself is the planner's: the map draws `corridor.visible`, so a search
|
||||
* living inside a sheet would lose its pins the moment the sheet closed. What is added
|
||||
* here is the two things a desk does not need: which stretch of the day to ask about,
|
||||
* and where that stretch starts.
|
||||
*
|
||||
* Called from two places (the bar over the stage, and the sheet), so it holds no state
|
||||
* of its own: the reach lives on the shell and everything else on the planner. The one
|
||||
* thing that would need a clock (where "ahead" begins) is read at the moment the
|
||||
* button is pressed rather than ticked, so this hook costs a screen nothing while
|
||||
* nobody is searching.
|
||||
*
|
||||
* The stage on screen decides the day. Switching stages therefore drops the results,
|
||||
* and that is not a special case handled here: `useCorridorPois` clears whenever the
|
||||
* routed line changes, so an answer can never outlive the question it belongs to.
|
||||
*/
|
||||
export function useMRtCorridor(planner: TripPlanner, shell: MTripShellApi): MRtCorridorController {
|
||||
const corridor = planner.roadtripCorridor
|
||||
const { setDayId, clear: clearCorridor, search, categories, toggleCategory, stopsAlongKm } = corridor
|
||||
const { offline } = useNetworkMode()
|
||||
const reach = shell.rtReach
|
||||
|
||||
const stage = useMemo(
|
||||
() => stageOf(planner.roadtripRoutes.days, planner.selectedDayId),
|
||||
[planner.roadtripRoutes.days, planner.selectedDayId],
|
||||
)
|
||||
|
||||
// The chip rail names the stage, so the stage names the drive being searched. Written
|
||||
// as an effect rather than as a prop because `dayId` is also the desktop day picker's
|
||||
// state, and only one of the two shells is ever mounted.
|
||||
const stageDayId = stage ? String(stage.dayId) : ''
|
||||
useEffect(() => {
|
||||
if (stageDayId) setDayId(stageDayId)
|
||||
}, [stageDayId, setDayId])
|
||||
|
||||
/**
|
||||
* Whether the clock can say where the drive has got to.
|
||||
*
|
||||
* Only on the day itself, and only once one stop is behind: on the first stop of the
|
||||
* morning "ahead" and "the whole stage" are the same stretch, and claiming a position
|
||||
* nobody gave us would be worse than starting at the beginning.
|
||||
*/
|
||||
const upNextIndexNow = useCallback((): number => {
|
||||
if (!stage) return -1
|
||||
const date = planner.days.find(d => d.id === planner.selectedDayId)?.date
|
||||
const isToday = !!date && date.slice(0, 10) === new Date().toISOString().slice(0, 10)
|
||||
const next = upNextStop(stage, nowMinutes(), isToday)
|
||||
if (!next) return -1
|
||||
return stage.stops.findIndex(s => s.assignmentId === next.row.stop.assignmentId)
|
||||
}, [stage, planner.days, planner.selectedDayId])
|
||||
|
||||
const anchored = upNextIndexNow() > 0
|
||||
|
||||
const canSearch = !offline && categories.length > 0 && search.spine.length > 1
|
||||
|
||||
const runSearch = search.search
|
||||
const run = useCallback(() => {
|
||||
if (!canSearch) return
|
||||
const index = upNextIndexNow()
|
||||
runSearch(corridorWindow(anchorKmFor(stopsAlongKm, index > 0 ? index : null), reach))
|
||||
}, [canSearch, runSearch, upNextIndexNow, stopsAlongKm, reach])
|
||||
|
||||
/**
|
||||
* Changing the reach throws the answer away on purpose.
|
||||
*
|
||||
* Hits found in the fifty kilometres ahead are not an answer to "the whole stage", and
|
||||
* a list that stays put while the chip above it says something else is the kind of
|
||||
* quiet wrongness that gets a stop planned in the wrong place. The categories behave
|
||||
* the same way one level down, in `useCorridorPois`.
|
||||
*/
|
||||
const { setRtReach } = shell
|
||||
const setReach = useCallback((value: CorridorReach) => {
|
||||
if (value === reach) return
|
||||
setRtReach(value)
|
||||
clearCorridor()
|
||||
}, [reach, setRtReach, clearCorridor])
|
||||
|
||||
return {
|
||||
categories,
|
||||
toggleCategory,
|
||||
reach,
|
||||
setReach,
|
||||
reachKm: PHONE_REACH_KM,
|
||||
anchored,
|
||||
run,
|
||||
clear: clearCorridor,
|
||||
canSearch,
|
||||
loading: search.loading,
|
||||
progress: search.progress,
|
||||
hits: corridor.visible,
|
||||
answered: !search.loading && search.progress.total > 0,
|
||||
offline,
|
||||
error: search.error,
|
||||
capped: search.capped,
|
||||
failedAreas: search.failedAreas,
|
||||
truncatedAreas: search.truncatedAreas,
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,12 @@ import { ChevronRight, FileDown, Settings, Share2 } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import MSheet from '../../../components/MSheet'
|
||||
import type { MTripSheetsProps } from '../MTripShell'
|
||||
import { dockTabIds } from '../dockTabs'
|
||||
import { useTranslation } from '../../../../i18n'
|
||||
|
||||
/** The sections living in the dock — everything else surfaces in this sheet. */
|
||||
const DOCK_IDS = new Set(['plan', 'transports', 'buchungen', 'finanzplan', 'listen'])
|
||||
|
||||
/** Demo tile tints per legacy tab id; plugins share the files neutral. */
|
||||
const TILE_COLORS: Record<string, string> = {
|
||||
roadtrip: '#0a84ff',
|
||||
transports: '#4A7DDB',
|
||||
buchungen: '#9B5DE5',
|
||||
listen: '#2FA9A0',
|
||||
@@ -27,7 +26,10 @@ export default function MMehrSheet({ planner, shell }: MTripSheetsProps) {
|
||||
const open = shell.sheet?.id === 'mehr'
|
||||
const canEditTrip = planner.can('trip_edit', planner.trip)
|
||||
|
||||
const gridTabs = planner.TRIP_TABS.filter(tab => !DOCK_IDS.has(tab.id))
|
||||
// Derived from the same priority list the dock seats itself from, so a section
|
||||
// can never show up in both places at once.
|
||||
const seated = dockTabIds(new Set(planner.TRIP_TABS.map(tab => tab.id)))
|
||||
const gridTabs = planner.TRIP_TABS.filter(tab => !seated.has(tab.id))
|
||||
|
||||
const tileStat = (id: string): string | null => {
|
||||
if (id === 'dateien') {
|
||||
|
||||
@@ -14,7 +14,7 @@ import PlPlaceSearch, { type PlSearchPick } from './PlPlaceSearch'
|
||||
import PlCategoryPicker from './PlCategoryPicker'
|
||||
import PlTimeFields from './PlTimeFields'
|
||||
import PlFileAttach from './PlFileAttach'
|
||||
import type { Place } from '../../../../types'
|
||||
import type { Assignment, AssignmentsMap, Place } from '../../../../types'
|
||||
import type { TripPlanner } from '../MTripShell'
|
||||
import { useLocationBias } from '../../../../hooks/useLocationBias'
|
||||
|
||||
@@ -48,6 +48,21 @@ function findDuplicateName(
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* The visit the editor was opened on, looked up in the planner's STORED list.
|
||||
*
|
||||
* Not planner.assignments: the phone filters booked nights (always) and service stops
|
||||
* (while the day lists hide them) out of that one, and the road trip stop sheet opens
|
||||
* this editor on exactly those visits. Looked up there the visit was not found, Start
|
||||
* prefilled from the pool place, and a plain save wrote that over the time the stop was
|
||||
* pinned to; the day note was dropped the same way. Every visit the plan tab shows is in
|
||||
* the stored list as well, so its entry points resolve exactly as they did.
|
||||
*/
|
||||
function findVisit(stored: AssignmentsMap, assignmentId: number | null): Assignment | null {
|
||||
if (!assignmentId) return null
|
||||
return Object.values(stored).flat().find(a => a.id === assignmentId) ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Add/edit place sheet — the mobile counterpart of PlaceFormModal, driven by
|
||||
* the planner's own editor flags (showPlaceForm / editingPlace / prefillCoords /
|
||||
@@ -58,7 +73,7 @@ function findDuplicateName(
|
||||
*/
|
||||
export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSheetProps) {
|
||||
const {
|
||||
t, toast, places, assignments, canUploadFiles,
|
||||
t, toast, places, assignments, storedAssignments, canUploadFiles,
|
||||
showPlaceForm, setShowPlaceForm,
|
||||
editingPlace, setEditingPlace,
|
||||
prefillCoords, setPrefillCoords,
|
||||
@@ -84,11 +99,23 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
|
||||
const [sheetPlace, setSheetPlace] = useState<Place | null>(null)
|
||||
const [sheetAssignmentId, setSheetAssignmentId] = useState<number | null>(null)
|
||||
|
||||
const dayAssignments = useMemo(
|
||||
() => (sheetPlace ? Object.values(assignments).flat() : []),
|
||||
[sheetPlace, assignments],
|
||||
// Live rather than the open-time snapshot, so the note's dirty check compares against
|
||||
// the note as it stands when Save is tapped.
|
||||
const ctxAssignment = useMemo(
|
||||
() => (sheetPlace ? findVisit(storedAssignments, sheetAssignmentId) : null),
|
||||
[sheetPlace, storedAssignments, sheetAssignmentId],
|
||||
)
|
||||
|
||||
// The overlap warning keeps to what the day lists show: on the plan tab a clash with a
|
||||
// pump or a booked night the list does not draw would name a stop nobody can see there.
|
||||
// The visit under edit joins when the lists hide it, because the warning reads the day
|
||||
// to compare against off that very row.
|
||||
const dayAssignments = useMemo(() => {
|
||||
if (!sheetPlace) return []
|
||||
const listed = Object.values(assignments).flat()
|
||||
return ctxAssignment && !listed.some(a => a.id === ctxAssignment.id) ? [...listed, ctxAssignment] : listed
|
||||
}, [sheetPlace, assignments, ctxAssignment])
|
||||
|
||||
// Prefill on open — same source order as the desktop form: editing place
|
||||
// (times off the in-context assignment), map/POI prefill coords, blank.
|
||||
useEffect(() => {
|
||||
@@ -96,9 +123,7 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
|
||||
setSheetPlace(editingPlace)
|
||||
setSheetAssignmentId(editingAssignmentId)
|
||||
if (editingPlace) {
|
||||
const assignment = editingAssignmentId
|
||||
? Object.values(assignments).flat().find(a => a.id === editingAssignmentId)
|
||||
: null
|
||||
const assignment = findVisit(storedAssignments, editingAssignmentId)
|
||||
const timeSource = assignment?.place ?? editingPlace
|
||||
setForm({
|
||||
name: editingPlace.name || '',
|
||||
@@ -143,7 +168,7 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
|
||||
setPendingFiles([])
|
||||
setDuplicateWarning(null)
|
||||
setDeleteArmed(false)
|
||||
// assignments is a fresh map each load — read at open time only.
|
||||
// storedAssignments is a fresh map each load, so it is read at open time only.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [showPlaceForm, editingPlace, prefillCoords, editingAssignmentId])
|
||||
|
||||
@@ -236,7 +261,6 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
|
||||
// #2163: the per-assignment note only travels when an assignment is in
|
||||
// context AND the value actually changed — same dirty-check as the
|
||||
// desktop form, so an untouched note never produces a PUT.
|
||||
const ctxAssignment = sheetAssignmentId ? dayAssignments.find(a => a.id === sheetAssignmentId) : null
|
||||
if (!ctxAssignment || (form.assignment_notes ?? '') === (ctxAssignment.notes ?? '')) {
|
||||
delete payload.assignment_notes
|
||||
}
|
||||
|
||||
@@ -23,6 +23,12 @@ import MNoteSheet, { type MNoteSheetPayload } from './MNoteSheet'
|
||||
import MImportSheet from './MImportSheet'
|
||||
import MExportSheet from './MExportSheet'
|
||||
import MMehrSheet from './MMehrSheet'
|
||||
import MRtStopSheet from '../roadtrip/MRtStopSheet'
|
||||
import MRtStaySheet from '../roadtrip/MRtStaySheet'
|
||||
import MRtKindSheet from '../roadtrip/MRtKindSheet'
|
||||
import MRtInfoSheet from '../roadtrip/MRtInfoSheet'
|
||||
import MRtCorridorSheet from '../roadtrip/MRtCorridorSheet'
|
||||
import MRtDraftSheet from '../roadtrip/MRtDraftSheet'
|
||||
import type { BookingExpenseRequest } from '../../../../components/Planner/BookingCostsSection.types'
|
||||
import type { BudgetItem } from '../../../../types'
|
||||
import type { MTripSheetsProps } from '../MTripShell'
|
||||
@@ -63,6 +69,17 @@ export default function MTripSheets({ planner, shell }: MTripSheetsProps) {
|
||||
<MTransportSheet planner={planner} shell={shell} />
|
||||
<MBrowseActionsSheet planner={planner} shell={shell} />
|
||||
<MMehrSheet planner={planner} shell={shell} />
|
||||
{/* The stage's own sheets. Each one checks shell.sheet?.id itself, the draft
|
||||
sheet hangs off planner.stopDraft the way the place editor hangs off its flag. */}
|
||||
<MRtStopSheet planner={planner} shell={shell} />
|
||||
<MRtStaySheet planner={planner} shell={shell} />
|
||||
<MRtKindSheet planner={planner} shell={shell} />
|
||||
<MRtInfoSheet planner={planner} shell={shell} />
|
||||
{/* Before the draft sheet, not after: both sit at the same z, so the one mounted
|
||||
later paints on top, and taking a hit onto the trip opens the draft OVER the
|
||||
search it came from. */}
|
||||
<MRtCorridorSheet planner={planner} shell={shell} />
|
||||
<MRtDraftSheet planner={planner} />
|
||||
<MExportSheet planner={planner} shell={shell} />
|
||||
<MNoteSheet
|
||||
planner={planner}
|
||||
|
||||
@@ -6,6 +6,7 @@ import MCostsTab from './MCostsTab'
|
||||
import MFilesTab from './MFilesTab'
|
||||
import MCollabTab from './MCollabTab'
|
||||
import MListsTab from './MListsTab'
|
||||
import MRoadtripTab from '../roadtrip/MRoadtripTab'
|
||||
import PluginFrame from '../../../../components/Plugins/PluginFrame'
|
||||
|
||||
/**
|
||||
@@ -55,6 +56,11 @@ export default function MTripTabPanel({ planner, shell, tab }: MTripTabPanelProp
|
||||
return <MCollabTab planner={planner} shell={shell} />
|
||||
case 'listen':
|
||||
return <MListsTab planner={planner} shell={shell} />
|
||||
// The only tab with two halves of its own: the chain, or the same map showing
|
||||
// the stage. Both are this one component, because they share a stage and the
|
||||
// switch between them must not lose it.
|
||||
case 'roadtrip':
|
||||
return <MRoadtripTab planner={planner} shell={shell} tab={tab} />
|
||||
default:
|
||||
return <TabScroller>{null}</TabScroller>
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user