From 0bf4e23815ffdf91da123737da905731606bb3c3 Mon Sep 17 00:00:00 2001 From: gnezim Date: Sun, 19 Apr 2026 14:18:23 +0300 Subject: [PATCH] Port Angular's closest-flight auto-select + scroll-into-view behavior MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Angular's route/departure/arrival search result list picks a 'current flight' on load and auto-expands + scrolls it into view — the flight whose dep/arr time is closest to 'now' for today's searches, or the first/last flight when the search is for a future/past day. React was always rendering the list scrolled to the top, so on today's route search the user sees flights from 00:30 onwards instead of landing on whatever is departing right now. - Add features/online-board/closestFlight.ts with a React-flavored port of find-closest-flight.ts (plus a today-guard that reuses the same 'yyyymmdd' shape the URL parser produces). - FlightList takes an optional initialCurrentFlightId, attaches a ref to each card, and scrollIntoView's it on mount / list change. - FlightCard takes an initialExpanded prop and seeds its useState so the selected flight lands expanded, matching the Angular 'expanded: true' assignment after setCurrentFlight. - OnlineBoardSearchPage computes the id via findClosestFlightId using the current params (type + date) and forwards it to FlightList. --- src/features/online-board/closestFlight.ts | 97 +++++++++++++++++++ .../components/OnlineBoardSearchPage.tsx | 14 +++ src/ui/flights/FlightCard.tsx | 8 +- src/ui/flights/FlightList.tsx | 45 +++++++-- 4 files changed, 155 insertions(+), 9 deletions(-) create mode 100644 src/features/online-board/closestFlight.ts diff --git a/src/features/online-board/closestFlight.ts b/src/features/online-board/closestFlight.ts new file mode 100644 index 00000000..fd3d5962 --- /dev/null +++ b/src/features/online-board/closestFlight.ts @@ -0,0 +1,97 @@ +/** + * Ported from Angular's find-closest-flight utility. Picks the flight + * whose departure (or arrival, for arrival-view) time is closest to + * "now" on today's searches, or the first/last flight for future/past + * days. The result gets auto-expanded and scrolled into view on the + * search results card, matching Angular behavior. + * + * @module + */ + +import type { ISimpleFlight, IFlightLeg } from "./types.js"; + +function firstLeg(flight: ISimpleFlight): IFlightLeg { + return flight.routeType === "Direct" ? flight.leg : flight.legs[0]!; +} + +function lastLeg(flight: ISimpleFlight): IFlightLeg { + return flight.routeType === "Direct" + ? flight.leg + : flight.legs[flight.legs.length - 1]!; +} + +function pickTime(flight: ISimpleFlight, isArrival: boolean): string | null { + const leg = isArrival ? lastLeg(flight) : firstLeg(flight); + const times = isArrival ? leg.arrival.times : leg.departure.times; + const dep = (times as { scheduledDeparture?: { local?: string } }).scheduledDeparture; + const arr = (times as { scheduledArrival?: { local?: string } }).scheduledArrival; + const actualOff = (times as { actualBlockOff?: { local?: string } }).actualBlockOff; + const actualOn = (times as { actualBlockOn?: { local?: string } }).actualBlockOn; + const latest = + (times as { latestDeparture?: { local?: string }; latestArrival?: { local?: string } }) + [isArrival ? "latestArrival" : "latestDeparture"]; + if (isArrival) return actualOn?.local ?? latest?.local ?? arr?.local ?? null; + return actualOff?.local ?? latest?.local ?? dep?.local ?? null; +} + +function parseTimeMs(iso: string | null): number | null { + if (!iso) return null; + const ms = Date.parse(iso); + return Number.isNaN(ms) ? null : ms; +} + +/** + * Returns `true` when `yyyymmdd` (e.g. '20260419') refers to today's + * calendar day in the browser's local time. + */ +function isTodayYyyymmdd(yyyymmdd: string, now: Date = new Date()): boolean { + if (yyyymmdd.length !== 8) return false; + const todayYyyymmdd = + String(now.getFullYear()) + + String(now.getMonth() + 1).padStart(2, "0") + + String(now.getDate()).padStart(2, "0"); + return yyyymmdd === todayYyyymmdd; +} + +export interface ClosestOptions { + /** 'yyyyMMdd' — the search date */ + searchDate: string; + /** `true` when the list is an arrival view (use arrival times) */ + isArrival: boolean; + /** Override current time for deterministic tests. */ + now?: Date; +} + +/** + * @returns the id of the flight whose time is closest to `now`, or the + * boundary flight when the search is not for today. Returns `null` + * when the list is empty. + */ +export function findClosestFlightId( + flights: ISimpleFlight[], + opts: ClosestOptions, +): string | null { + if (!flights.length) return null; + const now = opts.now ?? new Date(); + const nowMs = now.getTime(); + + if (!isTodayYyyymmdd(opts.searchDate, now)) { + // For future days, show the first flight; for past days, the last. + const firstMs = parseTimeMs(pickTime(flights[0]!, opts.isArrival)); + if (firstMs !== null && nowMs < firstMs) return flights[0]!.id; + return flights[flights.length - 1]!.id; + } + + let best: string | null = flights[0]?.id ?? null; + let bestAbsDiff = Number.POSITIVE_INFINITY; + for (const f of flights) { + const ms = parseTimeMs(pickTime(f, opts.isArrival)); + if (ms === null) continue; + const abs = Math.abs(ms - nowMs); + if (abs < bestAbsDiff) { + bestAbsDiff = abs; + best = f.id; + } + } + return best; +} diff --git a/src/features/online-board/components/OnlineBoardSearchPage.tsx b/src/features/online-board/components/OnlineBoardSearchPage.tsx index e53b427c..8ccb5f38 100644 --- a/src/features/online-board/components/OnlineBoardSearchPage.tsx +++ b/src/features/online-board/components/OnlineBoardSearchPage.tsx @@ -17,6 +17,7 @@ import { useCallback, useEffect } from "react"; import { useNavigate, useParams } from "@modern-js/runtime/router"; import { useTranslation } from "@/i18n/provider.js"; import { FlightList } from "@/ui/flights/FlightList.js"; +import { findClosestFlightId } from "../closestFlight.js"; import { PageLayout } from "@/ui/layout/PageLayout.js"; import { PageTabs } from "@/ui/layout/PageTabs.js"; import { SearchHistory } from "@/ui/layout/SearchHistory.js"; @@ -331,6 +332,18 @@ export const OnlineBoardSearchPage: FC = ({ // Use live flights when connected, otherwise fetched flights const displayFlights = connectionStatus === "live" ? liveFlights : flights; + // Port of Angular's findClosestFlight — on today's search, picks the + // flight with the smallest abs time-diff from 'now' (expands + scrolls + // it on mount). For future/past days, picks the first/last. + const initialCurrentFlightId = (() => { + if (!displayFlights.length || !params.date) return null; + const isArrival = params.type === "arrival"; + return findClosestFlightId(displayFlights, { + searchDate: params.date, + isArrival, + }); + })(); + // JSON-LD for search results (rendered once we have flights) const searchDescription = `Online board ${params.type} search results`; const jsonLd = displayFlights.length > 0 @@ -442,6 +455,7 @@ export const OnlineBoardSearchPage: FC = ({ flights={displayFlights} loading={loading} onFlightClick={handleFlightClick} + initialCurrentFlightId={initialCurrentFlightId} /> )} diff --git a/src/ui/flights/FlightCard.tsx b/src/ui/flights/FlightCard.tsx index e80638a6..b04fb8ee 100644 --- a/src/ui/flights/FlightCard.tsx +++ b/src/ui/flights/FlightCard.tsx @@ -25,6 +25,11 @@ export interface FlightCardProps { * fires onViewDetails. Matches Angular's board-flight-header behaviour. */ expandable?: boolean; + /** + * Opens the inline panel on mount — used by the 'closest flight' + * auto-selection Angular ships on search results. + */ + initialExpanded?: boolean; /** Fired when the user clicks 'Детали рейса' in the expanded panel. */ onViewDetails?: () => void; } @@ -67,6 +72,7 @@ export const FlightCard: FC = ({ flight, onClick, expandable, + initialExpanded, onViewDetails, }) => { const { t } = useTranslation(); @@ -85,7 +91,7 @@ export const FlightCard: FC = ({ departureLeg.equipment?.aircraft?.scheduled?.title ?? null; - const [expanded, setExpanded] = useState(false); + const [expanded, setExpanded] = useState(Boolean(initialExpanded)); const rowClickable = expandable || Boolean(onClick); const toggleExpanded = (): void => { if (expandable) { diff --git a/src/ui/flights/FlightList.tsx b/src/ui/flights/FlightList.tsx index 8ef68c15..05da04db 100644 --- a/src/ui/flights/FlightList.tsx +++ b/src/ui/flights/FlightList.tsx @@ -1,4 +1,4 @@ -import type { FC } from "react"; +import { type FC, useEffect, useRef } from "react"; import { useTranslation } from "@/i18n/provider.js"; import type { ISimpleFlight } from "@/features/online-board/types.js"; import { FlightCard } from "./FlightCard.js"; @@ -14,6 +14,12 @@ export interface FlightListProps { skeletonCount?: number; /** Click handler — makes each card act as a link to the details page */ onFlightClick?: (flight: ISimpleFlight) => void; + /** + * Id of a flight to auto-expand and scroll into view on mount / list + * change. Matches Angular's 'closest flight' behavior (today → closest + * to now; other days → first/last). + */ + initialCurrentFlightId?: string | null; } /** @@ -27,8 +33,20 @@ export const FlightList: FC = ({ loading = false, skeletonCount = 5, onFlightClick, + initialCurrentFlightId, }) => { const { t } = useTranslation(); + const cardRefs = useRef>(new Map()); + + useEffect(() => { + if (!initialCurrentFlightId) return; + const el = cardRefs.current.get(initialCurrentFlightId); + // jsdom doesn't implement scrollIntoView, so guard the call. + if (el && typeof el.scrollIntoView === "function") { + el.scrollIntoView({ block: "center", behavior: "smooth" }); + } + }, [initialCurrentFlightId, flights]); + if (loading) { return ; } @@ -44,14 +62,25 @@ export const FlightList: FC = ({ return (
{flights.map((flight) => ( - onFlightClick(flight) } - : {})} - /> + ref={(el) => { + if (el) { + cardRefs.current.set(flight.id, el); + } else { + cardRefs.current.delete(flight.id); + } + }} + > + onFlightClick(flight) } + : {})} + /> +
))} );