mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 07:30:04 +00:00
add open charging data and polish roadtrip warnings
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
import React from 'react'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import { TranslationProvider } from '../../i18n'
|
||||
import ChargingInfo from './ChargingInfo'
|
||||
import { chargingRepo } from '../../repo/chargingRepo'
|
||||
|
||||
vi.mock('../../store/tripStore', () => ({ useTripStore: (select: (s: { trip: { id: number } }) => unknown) => select({ trip: { id: 1 } }) }))
|
||||
vi.mock('../../repo/chargingRepo', () => ({ chargingRepo: { read: vi.fn() } }))
|
||||
const info = { checkedAt: new Date().toISOString(), status: 'ok' as const, station: 'Station', source: 'Operator', sourceUrl: 'https://example.com', license: 'CC-0', updatedAt: new Date().toISOString(), stale: false, available: 2, total: 4, unknown: 0, tariffs: [], pricesUnavailable: false }
|
||||
describe('Charging information', () => {
|
||||
it('shows availability, attribution and missing prices without inventing a price', async () => {
|
||||
vi.mocked(chargingRepo.read).mockResolvedValue(info)
|
||||
render(<TranslationProvider><ChargingInfo placeId={7} /></TranslationProvider>)
|
||||
expect(await screen.findByText('2/4 available')).toBeInTheDocument()
|
||||
expect(screen.getByText('No reliable data available')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByText('Charging'))
|
||||
expect(screen.getByRole('link', { name: 'Operator' })).toHaveAttribute('href', 'https://example.com')
|
||||
})
|
||||
it('does not display free capacity for stale data', async () => {
|
||||
vi.mocked(chargingRepo.read).mockResolvedValue({ ...info, stale: true })
|
||||
render(<TranslationProvider><ChargingInfo placeId={7} /></TranslationProvider>)
|
||||
expect(await screen.findByText('Status outdated')).toBeInTheDocument()
|
||||
expect(screen.queryByText('2/4')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { PlugZap, Coins, ChevronDown } from 'lucide-react'
|
||||
import type { ChargingInfo as Info } from '@trek/shared'
|
||||
import { useTranslation } from '../../i18n/TranslationContext'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { chargingRepo } from '../../repo/chargingRepo'
|
||||
import { isEffectivelyOffline } from '../../sync/networkMode'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
|
||||
export default function ChargingInfo({ placeId, compact = false }: { placeId: number; compact?: boolean }) {
|
||||
const tripId = useTripStore(s => s.trip?.id)
|
||||
const { t } = useTranslation()
|
||||
const [info, setInfo] = useState<Info | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
setInfo(null); setLoading(true)
|
||||
const refresh = async () => {
|
||||
if (!tripId || document.hidden) return
|
||||
try { const value = await chargingRepo.read(tripId, placeId); if (active) setInfo(value) }
|
||||
catch { if (active) setInfo(null) }
|
||||
finally { if (active) setLoading(false) }
|
||||
}
|
||||
const offline = () => { setInfo(null); setLoading(false) }
|
||||
void refresh()
|
||||
const timer = window.setInterval(() => void refresh(), 60000)
|
||||
window.addEventListener('offline', offline)
|
||||
window.addEventListener('online', refresh)
|
||||
document.addEventListener('visibilitychange', refresh)
|
||||
return () => { active = false; clearInterval(timer); window.removeEventListener('offline', offline); window.removeEventListener('online', refresh); document.removeEventListener('visibilitychange', refresh) }
|
||||
}, [tripId, placeId])
|
||||
const known = !isEffectivelyOffline() && info?.available != null && !info.stale && Date.now() - Date.parse(info.checkedAt) < 120000
|
||||
const status = loading ? t('common.loading') : known ? `${info.available}/${info.total} ${t('roadtrip.charging.available')}` : t(info?.stale ? 'roadtrip.charging.stale' : 'roadtrip.charging.unknown')
|
||||
const components = info?.tariffs.flatMap(tariff => tariff.components.map(component => ({ ...component, currency: tariff.currency }))) ?? []
|
||||
const energy = components.filter(component => component.kind === 'ENERGY' && component.taxIncluded && !component.conditional)
|
||||
const sameCurrency = new Set(energy.map(component => component.currency)).size === 1
|
||||
const cheapest = sameCurrency ? energy.reduce<typeof energy[number] | null>((best, component) => !best || component.price < best.price ? component : best, null) : null
|
||||
const price = (value: number, currency: string) => new Intl.NumberFormat(undefined, { style: 'currency', currency }).format(value)
|
||||
const badges = <span className="inline-flex shrink-0 items-center gap-1 align-middle whitespace-nowrap font-medium text-[length:calc(10px*var(--fs-scale-caption,1))] leading-none">
|
||||
<Tooltip label={`${status}${info?.updatedAt ? ` (${new Date(info.updatedAt).toLocaleString()})` : ''}`}><span tabIndex={0} className={`inline-flex items-center gap-1 rounded px-1 py-0.5 ${known && info.available! > 0 ? 'bg-success-soft text-success' : 'bg-surface-secondary text-content-muted'}`}><PlugZap size={10} />{known ? `${info.available}/${info.total}` : '?'}</span></Tooltip>
|
||||
{cheapest && <Tooltip label={t('roadtrip.charging.note')}><span tabIndex={0} className="inline-flex items-center gap-1 rounded bg-surface-secondary px-1 py-0.5 text-content-muted"><Coins size={10} />{price(cheapest.price, cheapest.currency)}/kWh*</span></Tooltip>}
|
||||
</span>
|
||||
if (compact) return badges
|
||||
return <details className="group rounded-[10px] bg-surface-hover text-[length:calc(12px*var(--fs-scale-body,1))] text-content-secondary">
|
||||
<summary className="flex cursor-pointer list-none items-center gap-1.5 px-3 py-2 [&::-webkit-details-marker]:hidden">
|
||||
<PlugZap size={13} className="shrink-0 text-content-faint" />
|
||||
<span className="font-medium">{t('roadtrip.poi.charging')}</span>
|
||||
<span className="ml-2 text-content-muted">{status}</span>
|
||||
{cheapest && <span className="ml-auto whitespace-nowrap font-medium">{price(cheapest.price, cheapest.currency)}/kWh*</span>}
|
||||
<ChevronDown size={13} className={'shrink-0 text-content-faint group-open:rotate-180 ' + (cheapest ? '' : 'ml-auto')} />
|
||||
</summary>
|
||||
<div className="space-y-2 px-3 pb-3 text-content-muted">
|
||||
{info?.station && <p>{info.station}</p>}
|
||||
<div className="space-y-1"><p className="font-medium">{t('roadtrip.charging.prices')}</p>
|
||||
{!components.length && <p className="text-content-muted">{info?.pricesUnavailable ? `${t('common.error')}: ` : ''}{t('roadtrip.charging.unknown')}</p>}
|
||||
{components.map((component, index) => <p key={index}>{price(component.price, component.currency)}{component.kind === 'ENERGY' ? '/kWh' : ['TIME', 'PARKING_TIME'].includes(component.kind) ? '/h' : ''} {component.kind === 'FLAT' ? 'Σ' : ''}{component.conditional || !component.taxIncluded ? '*' : ''}{component.afterSeconds != null && component.afterSeconds > 0 ? ` (> ${Math.round(component.afterSeconds / 60)} min)` : ''}</p>)}
|
||||
{!!components.length && <p className="text-content-muted">* {t('roadtrip.charging.note')}</p>}
|
||||
</div>
|
||||
<p className="text-content-muted">{t('roadtrip.charging.coverage')}</p>
|
||||
{info?.source && <p className="text-content-muted"><a className="underline" href={info.sourceUrl?.startsWith('https://') ? info.sourceUrl : 'https://mobidata-bw.de/de/dataset/e-ladesaulen'} target="_blank" rel="noreferrer">{info.source}</a> · <a className="underline" href="https://mobidata-bw.de/de/dataset/e-ladesaulen" target="_blank" rel="noreferrer">MobiData BW</a><br />{info.license}{info.updatedAt && ` · ${new Date(info.updatedAt).toLocaleString()}`}</p>}
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
@@ -12,8 +12,8 @@ export default function EndDayControl({ active, onToggle }: EndDayControlProps)
|
||||
const { t } = useTranslation()
|
||||
const [pending, setPending] = useState(false)
|
||||
return (
|
||||
<fieldset disabled={pending} aria-busy={pending} className="flex min-w-0 items-center justify-between gap-2 rounded-lg border border-edge-faint bg-surface-secondary px-3 py-2.5 disabled:opacity-60">
|
||||
<span className="flex flex-1 items-center gap-2 text-caption font-medium text-content"><Moon size={15} className={`shrink-0 ${active ? 'text-accent-on' : 'text-content-faint'}`} aria-hidden />{t('roadtrip.window.endHere')}</span>
|
||||
<fieldset disabled={pending} aria-busy={pending} className="flex min-w-0 items-center justify-between gap-2 rounded-[10px] bg-surface-hover px-3 py-2 disabled:opacity-60">
|
||||
<span className="flex flex-1 items-center gap-1.5 text-[length:calc(12px*var(--fs-scale-body,1))] font-medium text-content-secondary"><Moon size={13} className={`shrink-0 ${active ? 'text-accent-on' : 'text-content-faint'}`} aria-hidden />{t('roadtrip.window.endHere')}</span>
|
||||
<ToggleSwitch on={active} label={t('roadtrip.window.endHere')} onToggle={async () => {
|
||||
if (pending) return
|
||||
setPending(true)
|
||||
|
||||
@@ -14,7 +14,7 @@ async function openPreview() {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Import Google Maps route' }))
|
||||
fireEvent.click(screen.getByText('Import Google Maps route', { selector: 'span' }))
|
||||
fireEvent.change(screen.getByRole('textbox', { name: 'Google Maps URL' }), { target: { value: 'https://google.com/maps/dir/A/B' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Preview', exact: true }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Preview' }))
|
||||
await screen.findByText('Munich')
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ describe('Google route preview', () => {
|
||||
expect(screen.getAllByRole('listitem').map(item => item.textContent)).toEqual([expect.stringContaining('Munich'), expect.stringContaining('Unknown'), expect.stringContaining('Rome')])
|
||||
expect(screen.getByText('Location unresolved; this stop will be skipped.')).toBeInTheDocument()
|
||||
expect(googleRouteRepo.append).not.toHaveBeenCalled()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Import', exact: true }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Import' }))
|
||||
await waitFor(() => expect(loadTrip).toHaveBeenCalledWith(1))
|
||||
expect(googleRouteRepo.append).toHaveBeenCalledWith(1, { dayId: 3, stops: [{ name: 'Munich', lat: 48, lng: 11 }, { name: 'Rome', lat: 41, lng: 12 }] }, expect.any(String))
|
||||
})
|
||||
@@ -36,7 +36,7 @@ describe('Google route preview', () => {
|
||||
it('blocks import when fewer than two locations resolve', async () => {
|
||||
vi.mocked(googleRouteRepo.preview).mockResolvedValue({ stops: [{ name: 'Munich', lat: 48, lng: 11 }, { name: 'Unknown', lat: null, lng: null }] })
|
||||
await openPreview()
|
||||
expect(screen.getByRole('button', { name: 'Import', exact: true })).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'Import' })).toBeDisabled()
|
||||
expect(googleRouteRepo.append).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import ChargingInfo from './ChargingInfo'
|
||||
import { useRoadtripSettings } from '../../hooks/useRoadtripSettings'
|
||||
import React, { useState } from 'react'
|
||||
import {
|
||||
@@ -833,10 +834,10 @@ function ServiceStop({ stop, entry, late, driveFindings, selected, onSelect, onE
|
||||
{/* Truncated, not wrapped: a service stop is a waypoint, and its full name lives
|
||||
on the map pin — where a place's name is the row's whole reason to exist. */}
|
||||
<span
|
||||
className="min-w-0 truncate font-semibold leading-6 tracking-[-0.012em] text-content-secondary"
|
||||
className="flex min-w-0 items-center gap-2 font-semibold leading-6 tracking-[-0.012em] text-content-secondary"
|
||||
style={{ fontSize: FS.name }}
|
||||
>
|
||||
{stop.name}
|
||||
<span className="min-w-0 truncate">{stop.name}</span>{stop.stopType === 'charging' && <ChargingInfo placeId={stop.placeId} compact />}
|
||||
</span>
|
||||
<span className="flex flex-wrap items-center gap-1">
|
||||
<StayBadge minutes={stop.dwellMinutes} onEdit={onEditStay} />
|
||||
@@ -1090,10 +1091,10 @@ function Stop({ stop, number, entry, late, driveFindings, selected, continues, s
|
||||
{/* Wraps rather than truncates: the name is what the row is for, and thirty of
|
||||
them cut off mid-word is a list nobody reads. */}
|
||||
<span
|
||||
className="min-w-0 break-words font-semibold leading-6 tracking-[-0.012em] text-content"
|
||||
className="flex min-w-0 items-center gap-2 font-semibold leading-6 tracking-[-0.012em] text-content"
|
||||
style={{ fontSize: FS.name }}
|
||||
>
|
||||
{stop.name}
|
||||
<span className={stop.stopType === 'charging' ? 'min-w-0 truncate' : 'min-w-0 break-words'}>{stop.name}</span>{stop.stopType === 'charging' && <ChargingInfo placeId={stop.placeId} compact />}
|
||||
</span>
|
||||
{/* Two halves under one border: the word says what the number means, so the
|
||||
number needs no unit of explanation beside it. */}
|
||||
|
||||
@@ -14,9 +14,9 @@ export default function VisitControls({ endDay, stay }: { endDay?: EndDayControl
|
||||
<div className={`grid gap-2 ${endDay && stay ? 'grid-cols-2' : 'grid-cols-1'}`}>
|
||||
{endDay && <EndDayControl {...endDay} />}
|
||||
{stay && <button type="button" onClick={stay.onEdit} disabled={!stay.onEdit}
|
||||
className="flex min-w-0 items-center justify-between gap-2 rounded-lg border border-edge-faint bg-surface-secondary px-3 py-2.5 text-start enabled:hover:bg-surface-hover disabled:cursor-default">
|
||||
<span className="flex items-center gap-2 text-caption font-medium uppercase text-content"><Clock size={15} className="shrink-0 text-content-faint" aria-hidden />{t('roadtrip.stop.stayShort')}</span>
|
||||
{' '}<span className="flex shrink-0 items-center gap-2 text-caption font-medium text-content">
|
||||
className="flex min-w-0 items-center justify-between gap-2 rounded-[10px] bg-surface-hover px-3 py-2 text-start enabled:hover:bg-surface-tertiary disabled:cursor-default">
|
||||
<span className="flex items-center gap-1.5 text-[length:calc(12px*var(--fs-scale-body,1))] font-medium uppercase text-content-secondary"><Clock size={13} className="shrink-0 text-content-faint" aria-hidden />{t('roadtrip.stop.stayShort')}</span>
|
||||
{' '}<span className="flex shrink-0 items-center gap-1.5 text-[length:calc(12px*var(--fs-scale-body,1))] font-medium text-content-secondary">
|
||||
{formatDurationShort((stay.minutes ?? 0) * 60)}{stay.onEdit && <Pencil size={12} className="text-content-faint" aria-hidden />}
|
||||
</span>
|
||||
</button>}
|
||||
|
||||
Reference in New Issue
Block a user