diff --git a/client/scripts/size-baseline.json b/client/scripts/size-baseline.json index 5b589778c..3d3878d81 100644 --- a/client/scripts/size-baseline.json +++ b/client/scripts/size-baseline.json @@ -7,7 +7,7 @@ "src/components/Budget/CostsPanel.tsx": 1607, "src/components/Map/MapView.tsx": 1200, "src/components/Map/MapViewGL.test.tsx": 2919, - "src/components/Map/MapViewGL.tsx": 2118, + "src/components/Map/MapViewGL.tsx": 2116, "src/components/Planner/DayDetailPanel.test.tsx": 2333, "src/components/Planner/DayPlanSidebar.test.tsx": 5349, "src/components/Planner/DayPlanSidebar.tsx": 2910, diff --git a/client/src/components/Map/VectorBasemap.tsx b/client/src/components/Map/VectorBasemap.tsx index 6100ebe74..ace778346 100644 --- a/client/src/components/Map/VectorBasemap.tsx +++ b/client/src/components/Map/VectorBasemap.tsx @@ -47,9 +47,47 @@ async function loadLayerFactory() { import('./engines/maplibre'), import('@maplibre/maplibre-gl-leaflet'), ]) + guardTransitionEnd(bridge.MaplibreGL.prototype as unknown as GlLayerInternals) return bridge.maplibreGL } +interface GlLayerInternals { + _map: L.Map | null + _glMap: { _actualCanvas: HTMLElement; once(event: string, fn: () => void): void; jumpTo(view: { center: L.LatLng; zoom: number }): void } + _resizeContainer(): void + _zoomEnd(): void + _transitionEnd: (e?: unknown) => void + _trekGuarded?: boolean +} + +/** + * The bridge answers a map resize by scheduling a frame that reads + * `this._map.getZoom()` without asking whether the layer is still on a map. A + * layer taken off before that frame (a dialog closed at once, React mounting a + * map twice in development) threw "Cannot read properties of null (reading + * 'getZoom')" from inside the frame. This is the bridge's own method (0.1.4, + * pinned) with that question added; patched once, on the class. + */ +function guardTransitionEnd(proto: GlLayerInternals): void { + if (proto._trekGuarded) return + proto._transitionEnd = function (this: GlLayerInternals) { + L.Util.requestAnimFrame(() => { + const map = this._map + if (!map) return + const zoom = map.getZoom() + const center = map.getCenter() + const offset = map.latLngToContainerPoint(map.getBounds().getNorthWest()) + this._resizeContainer() + L.DomUtil.setTransform(this._glMap._actualCanvas, offset, 1) + this._glMap.once('moveend', () => { + if (this._map) this._zoomEnd() + }) + this._glMap.jumpTo({ center, zoom: zoom - 1 }) + }) + } + proto._trekGuarded = true +} + /** The factory, or null when its chunk never arrived. A dead chunk is not the basemap's problem. */ async function loadLayerFactoryOrNull() { try { diff --git a/client/src/components/Map/flightAircraft.css b/client/src/components/Map/flightAircraft.css index fbf9da2f3..71555a516 100644 --- a/client/src/components/Map/flightAircraft.css +++ b/client/src/components/Map/flightAircraft.css @@ -30,7 +30,7 @@ .trek-aircraft__halo { position: absolute; - left: 0; + inset-inline-start: 0; top: 0; width: 30px; height: 30px; @@ -53,7 +53,7 @@ .trek-aircraft__label { position: absolute; - left: 36px; + inset-inline-start: 36px; top: 50%; transform: translateY(-50%); padding: 3px 8px; diff --git a/client/src/components/Planner/bookings/BookingCard.tsx b/client/src/components/Planner/bookings/BookingCard.tsx index ef91de68b..fc144fb86 100644 --- a/client/src/components/Planner/bookings/BookingCard.tsx +++ b/client/src/components/Planner/bookings/BookingCard.tsx @@ -72,7 +72,7 @@ export default function BookingCard(p: BookingCardProps) {
- {r.type === 'flight' && } + {transit ? : ( <> diff --git a/client/src/components/Planner/bookings/BookingDetailDialog.tsx b/client/src/components/Planner/bookings/BookingDetailDialog.tsx index 48c6c45e3..2a073f27b 100644 --- a/client/src/components/Planner/bookings/BookingDetailDialog.tsx +++ b/client/src/components/Planner/bookings/BookingDetailDialog.tsx @@ -146,11 +146,12 @@ export default function BookingDetailDialog(p: BookingDetailDialogProps) { {!!r.needs_review && } {r.confirmation_number && ( - + // The copy button rides in the pill's padding (-my-1), so this pill is as tall as its neighbours. + #{r.confirmation_number} diff --git a/client/src/components/Planner/flightLive/FlightArc.tsx b/client/src/components/Planner/flightLive/FlightArc.tsx deleted file mode 100644 index 02ed0b612..000000000 --- a/client/src/components/Planner/flightLive/FlightArc.tsx +++ /dev/null @@ -1,113 +0,0 @@ -import { useId } from 'react'; - -interface FlightArcProps { - /** Share of the way flown, 0 to 1. */ - progress: number; - /** Draws the aircraft; off where only the route is shown. */ - showPlane: boolean; - /** Softens the aircraft while its position is a guess (stale feed). */ - dimPlane?: boolean; - /** Colours as CSS values, so the desktop and the phone dress it in their own tokens. */ - track: string; - flown: string; - plane: string; - className?: string; -} - -// The arc is a quadratic curve across a fixed box; the SVG scales to its column. -const W = 320; -const H = 74; -const P0 = { x: 14, y: 62 }; -const P1 = { x: W / 2, y: -14 }; -const P2 = { x: W - 14, y: 62 }; - -function pointAt(t: number): { x: number; y: number; angle: number } { - const u = 1 - t; - const x = u * u * P0.x + 2 * u * t * P1.x + t * t * P2.x; - const y = u * u * P0.y + 2 * u * t * P1.y + t * t * P2.y; - const dx = 2 * u * (P1.x - P0.x) + 2 * t * (P2.x - P1.x); - const dy = 2 * u * (P1.y - P0.y) + 2 * t * (P2.y - P1.y); - return { x, y, angle: (Math.atan2(dy, dx) * 180) / Math.PI }; -} - -const PATH = `M${P0.x} ${P0.y} Q${P1.x} ${P1.y} ${P2.x} ${P2.y}`; - -/** An airliner seen from above, nose along +x, about 18 units long. */ -const PLANE = - 'M9 0c0-.9-.7-1.3-1.6-1.3H3.2L-1.6-7.6h-2.1l2.3 6.3h-4.1l-1.7-2.4h-1.6l1 3.7-1 3.7h1.6l1.7-2.4h4.1l-2.3 6.3h2.1l4.8-6.3h4.2C8.3 1.3 9 .9 9 0Z'; - -/** - * The route of a flight as a gentle arc: dashed where it is still to fly, - * solid where it has flown, the aircraft riding the curve at its heading. - * Around the aircraft the lines are masked out rather than covered, so it sits - * cleanly on any card, translucent ones included. In a right-to-left layout - * the origin stands on the right, so the whole drawing is mirrored with it. - * Purely visual; the numbers sit in the card around it. - */ -export default function FlightArc({ - progress, - showPlane, - dimPlane, - track, - flown, - plane, - className = '', -}: FlightArcProps) { - const maskId = useId(); - const p = Math.min(1, Math.max(0, progress)); - const at = pointAt(p); - // A CSS transform rather than the attribute, so a new position glides there. - const placed = { transform: `translate(${at.x}px, ${at.y}px) rotate(${at.angle}deg)` }; - return ( - - ); -} diff --git a/client/src/components/Planner/flightLive/FlightLiveCard.test.tsx b/client/src/components/Planner/flightLive/FlightLiveCard.test.tsx index e1b5e2793..2aa8df1ae 100644 --- a/client/src/components/Planner/flightLive/FlightLiveCard.test.tsx +++ b/client/src/components/Planner/flightLive/FlightLiveCard.test.tsx @@ -1,16 +1,18 @@ -// FE-PLANNER-FLIGHTLIVE-001 to FE-PLANNER-FLIGHTLIVE-008 +// FE-PLANNER-FLIGHTLIVE-001 to FE-PLANNER-FLIGHTLIVE-007 import type { FlightLiveLeg } from '@trek/shared'; -import { beforeEach, describe, expect, it } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; import { render, screen } from '../../../../tests/helpers/render'; import MFlightLiveStrip, { MPlanFlightLine } from '../../../mobile/screens/trip/MFlightLiveStrip'; import MFlightLiveCard from '../../../mobile/screens/trip/sheets/MFlightLiveCard'; import { legKey, useFlightLiveStore } from '../../../store/flightLiveStore'; import type { Reservation } from '../../../types'; -import FlightArc from './FlightArc'; import FlightLiveCard from './FlightLiveCard'; import FlightLiveStrip, { PlanFlightLiveLine } from './FlightLiveStrip'; +// The map is Leaflet and WebGL, neither of which jsdom draws; the card around it is what is under test here. +vi.mock('./FlightMiniMap', () => ({ default: () => null, FLIGHT_MAP_CREDIT: 'map credit' })); + const H = 3_600_000; function leg(over: Partial = {}): FlightLiveLeg { @@ -76,7 +78,6 @@ describe('FlightLiveCard', () => { expect(screen.getByText('+35 min')).toBeInTheDocument(); expect(screen.getByText('Altitude')).toBeInTheDocument(); expect(screen.getByText('A359 D-AIXA')).toBeInTheDocument(); - expect(screen.getByText('Live positions: adsb.lol (ODbL)')).toBeInTheDocument(); }); it('FE-PLANNER-FLIGHTLIVE-002: renders nothing while TREK follows no state for the leg', () => { @@ -106,7 +107,7 @@ describe('FlightLiveCard', () => { expect(screen.queryByText('Altitude')).not.toBeInTheDocument(); }); - it('FE-PLANNER-FLIGHTLIVE-004: explains a flight the feed cannot find, and the missing gate only around boarding', () => { + it('FE-PLANNER-FLIGHTLIVE-004: shows nothing without live data, and the missing gate only around boarding', () => { seed( leg({ phase: 'unknown', @@ -117,11 +118,8 @@ describe('FlightLiveCard', () => { last_seen_at: null, }) ); - const { unmount } = render(); - expect(screen.getByText('No live data')).toBeInTheDocument(); - expect(screen.queryByText(/Gate, terminal and baggage belt/)).not.toBeInTheDocument(); - // Nothing heard, so the feed is not credited either. - expect(screen.queryByText('Live positions: adsb.lol (ODbL)')).not.toBeInTheDocument(); + const { container, unmount } = render(); + expect(container).toBeEmptyDOMElement(); unmount(); const now = Date.now(); seed( @@ -156,7 +154,7 @@ describe('strips and plan lines', () => { seed(leg()); render( <> - + {}} /> ); @@ -179,7 +177,7 @@ describe('strips and plan lines', () => { const res = { id: 6, type: 'flight' } as Reservation; const { container } = render( <> - + @@ -188,14 +186,3 @@ describe('strips and plan lines', () => { expect(container).toBeEmptyDOMElement(); }); }); - -describe('FlightArc', () => { - it('FE-PLANNER-FLIGHTLIVE-008: draws the flown part only once under way, and the aircraft on request', () => { - const { container, rerender } = render( - - ); - expect(container.querySelectorAll('path')).toHaveLength(1); - rerender(); - expect(container.querySelectorAll('path')).toHaveLength(3); - }); -}); diff --git a/client/src/components/Planner/flightLive/FlightLiveCard.tsx b/client/src/components/Planner/flightLive/FlightLiveCard.tsx index f105dbebc..3ae0d0cfd 100644 --- a/client/src/components/Planner/flightLive/FlightLiveCard.tsx +++ b/client/src/components/Planner/flightLive/FlightLiveCard.tsx @@ -1,142 +1,167 @@ -import { Info, Radio } from 'lucide-react'; +import { Clock, Info } from 'lucide-react'; import { useTranslation } from '../../../i18n'; import type { DelayTone } from '../../../utils/flightLiveModel'; -import FlightArc from './FlightArc'; +import { Field } from '../bookings/bookingParts'; +import FlightMiniMap, { FLIGHT_MAP_CREDIT } from './FlightMiniMap'; import { useFlightLiveCard, type FlightTimeCell } from './useFlightLiveCard'; -const DELAY_CHIP: Record = { - ok: 'bg-success-soft text-success', - minor: 'bg-warning-soft text-warning', - major: 'bg-danger-soft text-danger', +type CardTone = 'live' | 'done' | 'planned'; + +/** The dialog head's pill, one size down: this head sits inside the dialog, under the real one. */ +const PILL = + 'inline-flex flex-none items-center gap-1 rounded-full bg-surface-card px-2 py-0.5 text-caption font-semibold text-content shadow-sm'; + +const DELAY_TONE: Record = { + ok: 'text-success', + minor: 'text-warning', + major: 'text-danger', +}; + +/** The head band's tint and the status dot, in the stage's colour like a booking dialog's head. */ +const HEAD: Record = { + live: { band: 'bg-[color-mix(in_srgb,var(--info)_11%,transparent)]', dot: 'bg-info' }, + done: { band: 'bg-[color-mix(in_srgb,var(--success)_11%,transparent)]', dot: 'bg-success' }, + planned: { band: 'bg-surface-tertiary', dot: 'bg-content-faint' }, }; interface FlightLiveCardProps { tripId: number; reservationId: number; legIndex: number; - /** "Flight 2 of 3" above the card, for a booking with stopovers. */ + /** "Flight 2 of 3" in the head, for a booking with stopovers. */ legLabel?: string; } -function TimeBlock({ +/** The time that counts on a white tile, the planned one struck beside it; both ends' tiles are the same size. */ +function TimeTile({ cell, end }: { cell: FlightTimeCell; end?: boolean }) { + return ( + + {cell.planned && {cell.planned}} + {cell.value} + + ); +} + +/** One end of the pass: its label, the airport code large, the city, and its time at the foot. */ +function End({ + label, code, city, cell, end, }: { + label: string; code: string; city: string | null; cell: FlightTimeCell; end?: boolean; }) { return ( -
- {code} +
+ + {label} + + {code} {city && ( - + {city} )} - - {cell.planned && {cell.planned}} - {cell.value} - - {cell.note && {cell.note}} + +
); } /** - * A flight's live state in the booking dialog: what is happening now in one - * line, both airports with their times, the route as an arc with the aircraft - * on it, and the numbers of the moment. Renders nothing while TREK follows no - * state for this leg, so the dialog keeps its plain schedule tiles. + * A flight's live state in the booking dialog, built from the dialog's own + * parts: a tinted head with pills (where the flight stands, what comes next, + * the delay) like the dialog's head; the pass with a small real map of the + * route behind it and both times on tiles; then the numbers of the moment as + * the dialog's fields. Renders nothing while TREK has no live state to show + * for this leg, so the dialog keeps its plain schedule tiles. */ export default function FlightLiveCard({ tripId, reservationId, legIndex, legLabel }: FlightLiveCardProps) { const { t } = useTranslation(); const card = useFlightLiveCard(tripId, reservationId, legIndex); if (!card) return null; const { leg, view } = card; - const quiet = view.stage === 'past' || view.stage === 'unknown'; + const head = HEAD[card.tone]; return (
- {legLabel && ( -
- {legLabel} -
- )} -
- - {card.live && ( - - )} - - -
-
{card.headline}
- {card.detail &&
{card.detail}
} -
- {card.delay && ( - - {card.delay.text} +
+ {legLabel && ( + + {legLabel} )} + + + {card.headline} + + {card.detail && ( + + + {card.detail} + + )} + {card.delay && ( + {card.delay.text} + )}
-
- -
- +
+ + +
+ + {leg.flight_number} + +
+ - - {leg.flight_number} -
- + + {card.stats.length > 0 && ( +
+ {card.stats.map((s) => ( + + {s.value} + + ))} +
+ )} + + {card.gateHint && ( +

+ + {t('flightLive.noGateHint')} +

+ )}
- - {card.stats.length > 0 && ( -
- {card.stats.map((s) => ( -
-
{s.label}
-
{s.value}
-
- ))} -
- )} - - {card.gateHint && ( -

- - {t('flightLive.noGateHint')} -

- )} - - {card.footnote && ( -
- - - {card.footnote} - - {card.attribution && {card.attribution}} -
- )}
); } diff --git a/client/src/components/Planner/flightLive/FlightLiveStrip.tsx b/client/src/components/Planner/flightLive/FlightLiveStrip.tsx index 9b7fff5ee..0f002e506 100644 --- a/client/src/components/Planner/flightLive/FlightLiveStrip.tsx +++ b/client/src/components/Planner/flightLive/FlightLiveStrip.tsx @@ -4,21 +4,11 @@ import { useCurrentFlightLegIndex, useFlightLiveCard } from './useFlightLiveCard const DELAY_TEXT: Record = { ok: 'text-success', minor: 'text-warning', major: 'text-danger' }; -/** The status dot: pulsing accent while the aircraft moves, green once landed, faint otherwise. */ -function Dot({ live, landed, size }: { live: boolean; landed: boolean; size: string }) { - return ( - - {live && } - - - ); -} - interface FlightLiveStripProps { tripId: number; reservationId: number; + /** The booking's type: anything but a flight renders nothing, so a card can hand every booking in. */ + type: string; className?: string; } @@ -28,20 +18,24 @@ interface FlightLiveStripProps { * picture is one click away in the booking dialog. Nothing far ahead of the * flight (the card shows its date already), nothing once it is long over. */ -export default function FlightLiveStrip({ tripId, reservationId, className = '' }: FlightLiveStripProps) { +export default function FlightLiveStrip({ tripId, reservationId, type, className = '' }: FlightLiveStripProps) { const legIndex = useCurrentFlightLegIndex(tripId, reservationId); - if (legIndex == null) return null; + if (type !== 'flight' || legIndex == null) return null; return ; } -function Strip({ tripId, reservationId, legIndex, className }: FlightLiveStripProps & { legIndex: number }) { +function Strip({ + tripId, + reservationId, + legIndex, + className, +}: Omit & { legIndex: number }) { const card = useFlightLiveCard(tripId, reservationId, legIndex); - if (!card || card.view.stage === 'past' || card.view.stage === 'upcoming') return null; + if (!card || card.view.stage === 'upcoming') return null; const { view } = card; return (
- {card.line} {card.delay && card.delay.tone !== 'ok' && ( @@ -84,10 +78,9 @@ export function PlanFlightLiveLine({ function PlanLine({ tripId, reservationId, legIndex }: { tripId: number; reservationId: number; legIndex: number }) { const card = useFlightLiveCard(tripId, reservationId, legIndex); const stage = card?.view.stage; - if (!card || stage === 'past' || stage === 'upcoming') return null; + if (!card || stage === 'upcoming') return null; return (
- {card.line} diff --git a/client/src/components/Planner/flightLive/FlightMiniMap.tsx b/client/src/components/Planner/flightLive/FlightMiniMap.tsx new file mode 100644 index 000000000..607386226 --- /dev/null +++ b/client/src/components/Planner/flightLive/FlightMiniMap.tsx @@ -0,0 +1,226 @@ +import type { FlightLiveLeg } from '@trek/shared'; +import L from 'leaflet'; +import { useEffect, useMemo, useState } from 'react'; +import { CircleMarker, MapContainer, Marker, Polyline, Tooltip, useMap } from 'react-leaflet'; +import { OFM_DARK, OFM_POSITRON } from '../../../constants/mapDefaults'; +import { useIsDark } from '../../../hooks/useIsDark'; +import { greatCircle, splitRoute, type LatLng } from '../../../utils/flightRoute'; +import VectorBasemap from '../../Map/VectorBasemap'; +import './flightMiniMap.css'; + +/** Who made the map under the route; named on the map itself, as the tiles' licence asks. */ +export const FLIGHT_MAP_CREDIT = '© OpenFreeMap © OpenMapTiles © OpenStreetMap'; + +/** An airliner seen from above, nose up, in a 24 box. */ +const PLANE_PATH = + 'M12 2c.9 0 1.3.7 1.3 1.6v4.2l6.3 4.8v2.1l-6.3-2.3v4.1l2.4 1.7v1.6l-3.7-1-3.7 1v-1.6l2.4-1.7v-4.1l-6.3 2.3v-2.1l6.3-4.8V3.6C10.7 2.7 11.1 2 12 2Z'; + +function planeIcon(heading: number, dim: boolean): L.DivIcon { + return L.divIcon({ + className: 'flight-mini-plane', + iconSize: [20, 20], + iconAnchor: [10, 10], + html: ``, + }); +} + +/** Where along the route the aircraft really is: the route point nearest to its reported position. */ +function progressOf(route: LatLng[], at: LatLng | null, fallback: number): number { + if (!at) return fallback; + let best = 0; + let bestD = Infinity; + route.forEach((p, i) => { + const d = (p.lat - at.lat) ** 2 + (((p.lng - at.lng + 540) % 360) - 180) ** 2; + if (d < bestD) { + bestD = d; + best = i; + } + }); + return best / (route.length - 1); +} + +/** + * Frames the whole route in the free middle of the box, right away and again a + * moment later for a box whose fonts were still settling. `inset` is the share + * of the width kept clear on either side, where the card lays its airports and + * times over the map; the map itself runs on under them, faded. + */ +function FitRoute({ route, inset, onReady }: { route: LatLng[]; inset: number; onReady: () => void }) { + const map = useMap(); + useEffect(() => { + // No invalidateSize: the dialog and the sheet slide in by transform, which leaves + // the layout size alone, and a resize here makes the GL layer schedule a frame + // that can outlive the map when React mounts it twice. + const fit = () => { + const side = Math.round(map.getSize().x * inset) + 10; + map.fitBounds(L.latLngBounds(route.map((p) => [p.lat, p.lng])), { + paddingTopLeft: [side, 22], + paddingBottomRight: [side, 46], + animate: false, + }); + }; + fit(); + const id = window.setTimeout(() => { + fit(); + onReady(); + }, 180); + return () => window.clearTimeout(id); + }, [map, route, inset, onReady]); + return null; +} + +/** The slice of a MapLibre map this file touches. */ +interface GlMap { + getStyle(): { layers?: { id: string; type: string }[] } | undefined; + setLayoutProperty(id: string, key: string, value: string): void; + on(event: string, fn: () => void): void; + off(event: string, fn: () => void): void; +} + +/** + * Hides the basemap's place names. Under a faded route at world scale they are + * clutter ("Italy" beside a Frankfurt dot), and the two airport codes on the + * route say all there is. The GL map only exists once its layer attached, so + * this waits for it, and hides again on each restyle (dark mode). + */ +function HideLabels() { + const map = useMap(); + useEffect(() => { + let gl: GlMap | null = null; + const hide = () => { + for (const layer of gl?.getStyle()?.layers ?? []) { + if (layer.type === 'symbol') gl?.setLayoutProperty(layer.id, 'visibility', 'none'); + } + }; + const find = () => { + if (gl) return; + map.eachLayer((layer) => { + const found = (layer as unknown as { getMaplibreMap?: () => GlMap }).getMaplibreMap?.(); + if (found && !gl) { + gl = found; + gl.on('styledata', hide); + hide(); + } + }); + }; + find(); + map.on('layeradd', find); + return () => { + map.off('layeradd', find); + gl?.off('styledata', hide); + }; + }, [map]); + return null; +} + +/** One end of the route: a ring with the airport code under it. */ +function RouteEnd({ at, code }: { at: LatLng; code: string }) { + return ( + + + {code} + + + ); +} + +interface FlightMiniMapProps { + leg: FlightLiveLeg; + /** Share of the way flown, used while the feed reports no position. */ + progress: number; + /** The aircraft only while it is on its way or just down; never for a flight still at the gate. */ + showPlane: boolean; + dimPlane: boolean; + /** The licences behind the picture (live data, map), kept on the map as its hover text and for screen readers. */ + credits: string[]; + /** Share of the width on either side kept clear of the route, for what the card lays over the map there. */ + inset?: number; + className?: string; +} + +/** + * The flight on a real map, small and quiet: the great circle between the two + * airports, solid where it is flown and dotted where it is left, the aircraft + * on the line as far as the feed last saw it, turned along the route. Nothing on it reacts to a + * touch, it is a picture. The edges fade into the surface on all four sides + * (flightMiniMap.css), and the map fades in once it is framed, so it never + * shows a jump from the world view to the route. Colours come in as the custom + * properties --fm-flown, --fm-ahead, --fm-end, --fm-plane and --fm-code. + */ +export default function FlightMiniMap({ + leg, + progress, + showPlane, + dimPlane, + credits, + inset = 0, + className = '', +}: FlightMiniMapProps) { + const dark = useIsDark(); + // The quiet OpenFreeMap styles rather than the user's basemap: under a faded route any busier map is noise. + const style = dark ? OFM_DARK : OFM_POSITRON; + const [ready, setReady] = useState(false); + const onReady = useMemo(() => () => setReady(true), []); + + const { origin, destination, position } = leg; + const route = useMemo( + () => greatCircle({ lat: origin.lat, lng: origin.lng }, { lat: destination.lat, lng: destination.lng }), + [origin.lat, origin.lng, destination.lat, destination.lng] + ); + // The reported position only says how far along the flight is; the aircraft + // itself sits on the drawn line, nose along it, so it never floats beside it. + const split = useMemo( + () => splitRoute(route, progressOf(route, position ? { lat: position.lat, lng: position.lng } : null, progress)), + [route, position, progress] + ); + const planeAt = split.at; + const icon = useMemo(() => planeIcon(split.heading, dimPlane), [split, dimPlane]); + + return ( +
+ {credits.join(', ')} + + + + + [p.lat, p.lng])} + pathOptions={{ className: 'flight-mini-ahead', interactive: false }} + /> + [p.lat, p.lng])} + pathOptions={{ className: 'flight-mini-flown', interactive: false }} + /> + + + {showPlane && } + +
+ ); +} diff --git a/client/src/components/Planner/flightLive/flightMiniMap.css b/client/src/components/Planner/flightLive/flightMiniMap.css new file mode 100644 index 000000000..028d726d2 --- /dev/null +++ b/client/src/components/Planner/flightLive/flightMiniMap.css @@ -0,0 +1,92 @@ +/* The flight mini map (FlightMiniMap.tsx). Leaflet draws its lines and markers + as SVG and HTML it builds itself, so their colours come from custom + properties the card sets on the box: --fm-flown, --fm-ahead, --fm-plane. */ + +/* Fades the map into the surface on all four sides: two crossed linear masks, + intersected, so the middle with the route is fully there, the map stays + faint under the airports and times laid over it, and every edge runs out. */ +.flight-mini-map { + -webkit-mask-image: + linear-gradient( + to right, + transparent 4%, + rgb(0 0 0 / 0.35) 24%, + #000 38%, + #000 62%, + rgb(0 0 0 / 0.35) 76%, + transparent 96% + ), + linear-gradient(to bottom, transparent, #000 22%, #000 78%, transparent); + -webkit-mask-composite: source-in; + mask-image: + linear-gradient( + to right, + transparent 4%, + rgb(0 0 0 / 0.35) 24%, + #000 38%, + #000 62%, + rgb(0 0 0 / 0.35) 76%, + transparent 96% + ), + linear-gradient(to bottom, transparent, #000 22%, #000 78%, transparent); + mask-composite: intersect; +} + +.flight-mini-map .leaflet-container { + background: transparent; + cursor: default; +} + +.flight-mini-map .flight-mini-flown { + stroke: var(--fm-flown); + stroke-width: 2.5; + stroke-linecap: round; + fill: none; +} + +.flight-mini-map .flight-mini-ahead { + stroke: var(--fm-ahead); + stroke-width: 1.75; + stroke-dasharray: 2 5; + stroke-linecap: round; + fill: none; +} + +.flight-mini-map .flight-mini-end { + stroke: var(--fm-flown); + stroke-width: 2; + fill: var(--fm-end); + fill-opacity: 1; +} + +.flight-mini-map .flight-mini-plane { + background: none; + border: 0; +} + +.flight-mini-map .flight-mini-plane svg { + fill: var(--fm-plane); + /* A light outline lifts the aircraft off the line and the map under it. */ + stroke: var(--fm-halo, #fff); + stroke-width: 1.6; + paint-order: stroke; + stroke-linejoin: round; + filter: drop-shadow(0 1px 2px rgb(0 0 0 / 0.3)); +} + +/* The airport codes at the two ends of the route, quiet text without Leaflet's tooltip box. */ +.flight-mini-map .leaflet-tooltip.flight-mini-code { + padding: 0; + border: 0; + background: none; + box-shadow: none; + color: var(--fm-code); + font-family: var(--font-geist, inherit); + font-size: 10px; + font-weight: 700; + letter-spacing: 0.06em; +} + +.flight-mini-map .leaflet-tooltip.flight-mini-code::before { + display: none; +} diff --git a/client/src/components/Planner/flightLive/useFlightLiveCard.ts b/client/src/components/Planner/flightLive/useFlightLiveCard.ts index 79ffc434a..3331bd375 100644 --- a/client/src/components/Planner/flightLive/useFlightLiveCard.ts +++ b/client/src/components/Planner/flightLive/useFlightLiveCard.ts @@ -11,6 +11,7 @@ import { splitDuration, type DelayTone, type FlightLiveView, + type FlightStage, } from '../../../utils/flightLiveModel'; type T = ReturnType['t']; @@ -18,10 +19,8 @@ type T = ReturnType['t']; export interface FlightTimeCell { /** The time that counts now: observed, estimated or planned. */ value: string; - /** The planned time, only when it differs from `value`. */ + /** The planned time, only when it differs from `value`, shown struck beside it. */ planned: string | null; - /** Shown under the time: "estimated", "actual" or nothing. */ - note: string | null; } interface FlightStat { @@ -32,9 +31,9 @@ interface FlightStat { interface FlightLiveCard { leg: FlightLiveLeg; view: FlightLiveView; - /** The big line: "Departs in 2 h 10 min", "In the air", "Landed". */ + /** Where the flight stands: "Scheduled", "In the air", "Landed". */ headline: string; - /** The quieter line under it, or null. */ + /** What comes next: "Departs in 2 h 10 min", "Lands in 5 h", or null. */ detail: string | null; /** Both in one line for the strips and plan rows, in the language's own joining. */ line: string; @@ -42,22 +41,28 @@ interface FlightLiveCard { dep: FlightTimeCell; arr: FlightTimeCell; stats: FlightStat[]; - /** "Updated 2 min ago" with the feed's credit, or null before any data. */ - footnote: string | null; + /** Who the live data came from, credited quietly on the map once the feed has seen this flight. */ attribution: string | null; /** Around boarding, where a traveller looks for a gate open data does not have. */ gateHint: boolean; - /** True while the aircraft is moving, for the pulsing status dot. */ + /** True while the aircraft is moving. */ live: boolean; + /** The colour family of the stage, for the tinted head of the card. */ + tone: 'live' | 'done' | 'planned'; } -/** The current time, ticking every `ms` while mounted, for countdowns that move. */ -function useNow(ms: number): number { +/** + * The current time, ticking every `ms` while `active`, for countdowns that move. + * Idle without a flight to show, so a booking TREK follows no state for sets + * no timer at all. + */ +function useNow(ms: number, active: boolean): number { const [now, setNow] = useState(() => Date.now()); useEffect(() => { + if (!active) return; const id = window.setInterval(() => setNow(Date.now()), ms); return () => window.clearInterval(id); - }, [ms]); + }, [ms, active]); return now; } @@ -75,21 +80,23 @@ function delayText(minutes: number | null, t: T): { text: string; tone: DelayTon return { text: t('flightLive.onTime'), tone: 'ok' }; } +/** The stages a card speaks for; without live data (past, unknown) there is no card. */ +type ShownStage = Exclude; + function headlineOf( + stage: ShownStage, view: FlightLiveView, leg: FlightLiveLeg, t: T, time: (ms: number, tz: string | null) => string ): { headline: string; detail: string | null } { - switch (view.stage) { + switch (stage) { case 'upcoming': case 'soon': return { - headline: - view.countdownMs != null - ? t('flightLive.departsIn', { time: durationText(view.countdownMs, t) }) - : t('flightLive.scheduled'), - detail: view.stage === 'soon' ? t('flightLive.watching') : null, + headline: t('flightLive.scheduled'), + detail: + view.countdownMs != null ? t('flightLive.departsIn', { time: durationText(view.countdownMs, t) }) : null, }; case 'taxiing': return { headline: t('flightLive.taxiing'), detail: t('flightLive.atAirport', { code: leg.origin.code }) }; @@ -109,32 +116,31 @@ function headlineOf( }) : null, }; - case 'past': - return { headline: t('flightLive.over'), detail: null }; - case 'unknown': - return { headline: t('flightLive.noSignal'), detail: t('flightLive.noSignalHint') }; } } +/** One end's time: what counts now (observed or estimated), the planned one beside it when they differ. */ function timeCell( actual: number | null, planned: number | null, tz: string | null, - estimate: boolean, - time: (ms: number, tz: string | null) => string, - t: T + time: (ms: number, tz: string | null) => string ): FlightTimeCell { const shown = actual ?? planned; - if (shown == null) return { value: '--:--', planned: null, note: null }; + if (shown == null) return { value: '--:--', planned: null }; const value = time(shown, tz); const plannedText = planned != null ? time(planned, tz) : null; - return { - value, - planned: actual != null && plannedText !== value ? plannedText : null, - note: actual == null ? null : estimate ? t('flightLive.estimated') : t('flightLive.actual'), - }; + return { value, planned: actual != null && plannedText !== value ? plannedText : null }; } +const TONE: Record = { + upcoming: 'planned', + soon: 'planned', + taxiing: 'live', + airborne: 'live', + landed: 'done', +}; + /** Altitude, speed and distance in the user's units while in the air, and the aircraft when known. */ function statsOf(leg: FlightLiveLeg, view: FlightLiveView, imperial: boolean, locale: string, t: T): FlightStat[] { const stats: FlightStat[] = []; @@ -164,18 +170,8 @@ function statsOf(leg: FlightLiveLeg, view: FlightLiveView, imperial: boolean, lo return stats; } -/** "Updated 2 min ago", or the age of the last signal once it is stale; null before the feed ever heard it. */ -function footnoteOf(leg: FlightLiveLeg, view: FlightLiveView, now: number, t: T): string | null { - if (!leg.last_seen_at) return null; - const age = now - Date.parse(leg.last_seen_at); - return view.stale - ? t('flightLive.lastSignal', { time: durationText(age, t) }) - : t('flightLive.updated', { time: durationText(Math.max(60_000, age), t) }); -} - /** In the air and on the ground the arrival delay counts, before take-off the departure delay. */ function delayOf(view: FlightLiveView, t: T): { text: string; tone: DelayTone } | null { - if (view.stage === 'past' || view.stage === 'unknown') return null; const flying = view.stage === 'airborne' || view.stage === 'landed'; return delayText(flying ? (view.arrDelay ?? view.depDelay) : view.depDelay, t); } @@ -192,13 +188,14 @@ export function useFlightLiveCard(tripId: number, reservationId: number, legInde const leg = useFlightLiveLeg(tripId, reservationId, legIndex); const attribution = useFlightLiveAttribution(tripId); // A second-level countdown is noise; the minute tick is what a traveller reads. - const now = useNow(30_000); + const now = useNow(30_000, !!leg); if (!leg) return null; const view = flightLiveView(leg, now); + // No live data to show: the flight is long over, or the feed never heard it. Nothing at all then. + if (view.stage === 'past' || view.stage === 'unknown') return null; const time = (ms: number, tz: string | null) => airportTime(ms, tz, locale, timeFormat); - const { headline, detail } = headlineOf(view, leg, t, time); - const footnote = footnoteOf(leg, view, now, t); + const { headline, detail } = headlineOf(view.stage, view, leg, t, time); return { leg, view, @@ -206,14 +203,14 @@ export function useFlightLiveCard(tripId: number, reservationId: number, legInde detail, line: detail && view.stage === 'airborne' ? t('flightLive.headlineDetail', { headline, detail }) : headline, delay: delayOf(view, t), - dep: timeCell(view.depActual, view.depPlanned, leg.origin.timezone, false, time, t), - arr: timeCell(view.arrExpected, view.arrPlanned, leg.destination.timezone, view.arrIsEstimate, time, t), + dep: timeCell(view.depActual, view.depPlanned, leg.origin.timezone, time), + arr: timeCell(view.arrExpected, view.arrPlanned, leg.destination.timezone, time), stats: statsOf(leg, view, imperial, locale, t), - footnote, // The feed is credited only for data it gave. - attribution: footnote ? attribution : null, + attribution: leg.last_seen_at ? attribution : null, gateHint: view.stage === 'soon' || view.stage === 'taxiing', live: view.stage === 'airborne' || view.stage === 'taxiing', + tone: TONE[view.stage], }; } @@ -223,6 +220,6 @@ export function useFlightLiveCard(tripId: number, reservationId: number, legInde */ export function useCurrentFlightLegIndex(tripId: number, reservationId: number): number | null { const legs = useFlightLiveLegs(tripId, reservationId); - const now = useNow(60_000); + const now = useNow(60_000, legs.length > 0); return currentLeg(legs, now)?.leg_index ?? null; } diff --git a/client/src/components/Planner/flightLive/useFlightLiveSync.ts b/client/src/components/Planner/flightLive/useFlightLiveSync.ts index 46a127e26..5ece90eff 100644 --- a/client/src/components/Planner/flightLive/useFlightLiveSync.ts +++ b/client/src/components/Planner/flightLive/useFlightLiveSync.ts @@ -1,3 +1,4 @@ +import type { FlightLiveLeg } from '@trek/shared'; import { useEffect } from 'react'; import { useFlightLiveStore, watchFlightLive } from '../../../store/flightLiveStore'; import { toMs } from '../../../utils/flightLiveModel'; @@ -7,12 +8,25 @@ const IDLE_MS = 10 * 60_000; const BEFORE_MS = 3 * 60 * 60_000; const AFTER_MS = 2 * 60 * 60_000; -/** True while one of the trip's legs is inside its watch window, where minutes matter. */ +const legsOf = (tripId: number): FlightLiveLeg[] => + Object.values(useFlightLiveStore.getState().trips[tripId]?.legs ?? {}); +const departureOf = (leg: FlightLiveLeg) => toMs(leg.departed_at) ?? toMs(leg.scheduled_departure); +const arrivalOf = (leg: FlightLiveLeg) => + toMs(leg.landed_at) ?? toMs(leg.estimated_arrival) ?? toMs(leg.scheduled_arrival); + +/** True while one of the trip's flights still lies ahead or is under way: only then is re-reading worth it. */ +function anyToFollow(tripId: number, now: number): boolean { + return legsOf(tripId).some((leg) => { + const arr = arrivalOf(leg); + return leg.phase !== 'landed' && arr != null && now <= arr + AFTER_MS; + }); +} + +/** True while one of the trip's flights is inside its watch window, where minutes matter. */ function anyActive(tripId: number, now: number): boolean { - const legs = Object.values(useFlightLiveStore.getState().trips[tripId]?.legs ?? {}); - return legs.some((leg) => { - const dep = toMs(leg.departed_at) ?? toMs(leg.scheduled_departure); - const arr = toMs(leg.landed_at) ?? toMs(leg.estimated_arrival) ?? toMs(leg.scheduled_arrival); + return legsOf(tripId).some((leg) => { + const dep = departureOf(leg); + const arr = arrivalOf(leg); return dep != null && arr != null && now >= dep - BEFORE_MS && now <= arr + AFTER_MS && leg.phase !== 'landed'; }); } @@ -21,37 +35,36 @@ function anyActive(tripId: number, now: number): boolean { * Keeps the open trip's live flight states current: one read when the trip has * flights, the server's `flight:live` pushes in between, and a quiet re-read * (every minute while a flight is near, every ten otherwise) as the safety net - * for a missed push. Nothing runs while the tab is hidden; coming back reads - * once. Mounted once per open trip by the planner, on desktop and phone alike. + * for a missed push, but only while a flight still lies ahead: a trip whose + * flights are all over is read once and left alone. Nothing runs while the tab + * is hidden; coming back reads once. Mounted once per open trip by the + * planner, on desktop and phone alike. */ export function useFlightLiveSync(tripId: number, hasFlights: boolean): void { useEffect(() => { if (!hasFlights || !Number.isFinite(tripId)) return; - const load = () => void useFlightLiveStore.getState().load(tripId); - load(); - const stopWatching = watchFlightLive(tripId); - let timer = 0; + let stopped = false; + const load = () => useFlightLiveStore.getState().load(tripId); const schedule = () => { window.clearTimeout(timer); - timer = window.setTimeout( - () => { - if (!document.hidden) load(); - schedule(); - }, - anyActive(tripId, Date.now()) ? ACTIVE_MS : IDLE_MS - ); + const now = Date.now(); + if (stopped || !anyToFollow(tripId, now)) return; + timer = window.setTimeout(tick, anyActive(tripId, now) ? ACTIVE_MS : IDLE_MS); }; - schedule(); + const tick = () => { + if (document.hidden) schedule(); + else void load().then(schedule); + }; + void load().then(schedule); + const stopWatching = watchFlightLive(tripId); const onVisible = () => { - if (!document.hidden) { - load(); - schedule(); - } + if (!document.hidden) void load().then(schedule); }; document.addEventListener('visibilitychange', onVisible); return () => { + stopped = true; window.clearTimeout(timer); stopWatching(); document.removeEventListener('visibilitychange', onVisible); diff --git a/client/src/mobile/screens/admin/MAdminSettingsSection.tsx b/client/src/mobile/screens/admin/MAdminSettingsSection.tsx index fe5fc25e3..61997bd12 100644 --- a/client/src/mobile/screens/admin/MAdminSettingsSection.tsx +++ b/client/src/mobile/screens/admin/MAdminSettingsSection.tsx @@ -188,24 +188,13 @@ export default function MAdminSettingsSection({ admin, t }: MAdminSettingsSectio {/* Live flight status: open ADS-B data, no key, on by default (desktop parity). */} - - - void handleToggleAuthSetting('flight_live_enabled', v, setFlightLive)} - /> - } - /> - + void handleToggleAuthSetting('flight_live_enabled', v, setFlightLive)} + /> {/* Allowed file types */} @@ -440,3 +429,23 @@ export default function MAdminSettingsSection({ admin, t }: MAdminSettingsSectio
) } + +/** The live flight status switch, locked with a word when the server environment holds it. */ +function FlightLiveCard({ t, managed, on, locked, onChange }: { + t: TranslationFn + managed: boolean + on: boolean + locked: boolean + onChange: (on: boolean) => void +}) { + return ( + + + } + /> + + ) +} diff --git a/client/src/mobile/screens/trip/MFlightLiveStrip.tsx b/client/src/mobile/screens/trip/MFlightLiveStrip.tsx index 19689f35f..5d3ca9bb2 100644 --- a/client/src/mobile/screens/trip/MFlightLiveStrip.tsx +++ b/client/src/mobile/screens/trip/MFlightLiveStrip.tsx @@ -9,24 +9,6 @@ const DELAY_COLOR: Record = { const LIVE = 'var(--m-st-info)'; -/** The status dot: pulsing blue while the aircraft moves, green once landed, faint otherwise. */ -function Dot({ live, landed, size }: { live: boolean; landed: boolean; size: string }) { - return ( - - {live && ( - - )} - - - ); -} - interface MFlightLiveStripProps { tripId: number; reservationId: number; @@ -51,7 +33,7 @@ export default function MFlightLiveStrip({ tripId, reservationId, onOpen, classN function Strip({ tripId, reservationId, legIndex, onOpen, className }: MFlightLiveStripProps & { legIndex: number }) { const card = useFlightLiveCard(tripId, reservationId, legIndex); - if (!card || card.view.stage === 'past' || card.view.stage === 'upcoming') return null; + if (!card || card.view.stage === 'upcoming') return null; const { view } = card; return (