feat(map): enhance globe projection handling and improve altitude color representation (#14)

* feat(map): enhance globe projection handling and improve altitude color representation

- Implemented elevation-aware pixel projection for globe mode in `projectLngLatElevationPixelDelta`.
- Refactored north-up animation in `CameraController` to use `setBearing` for smoother transitions.
- Added native GeoJSON support for globe zoom in `FlightLayers`, including dynamic opacity adjustments based on zoom levels.
- Introduced globe-specific pitch and projection settings in `Map` component, ensuring consistent rendering.
- Enhanced UI control panel with a visual separator for better organization.
- Minor formatting adjustments in `altitudeToColor` function for improved readability.

* feat(map): refactor elevation-aware projection handling for improved accuracy

* feat(map): add dark terrain profile support and enhance map styling

* feat: implement trail stitching for merging historical and live flight data

- Added a new module `trail-stitching.ts` to handle the merging of sparse historical track data with high-frequency live trail data.
- Introduced constants for thresholds and parameters to improve code readability and maintainability.
- Implemented a main function `stitchHistoricalTrail` that processes flight tracks, applies smoothing, and merges live tail data.
- Included utility functions for spherical interpolation and cubic easing for altitude transitions.
- Ensured the final path is cleaned of spikes and sharp corners for a smoother representation.

* feat: add centripetal Catmull-Rom spline interpolation for 3D flight trails

- Implemented `catmullRomSpline3D` function to interpolate waypoints into a smooth 3D path.
- Added helper functions for segment density calculation, safe linear interpolation, and endpoint reflection.
- Included support for variable tension based on heading changes to enhance smoothness.
- Introduced utility functions for linear interpolation between elevated points.

* feat(map): enhance layer visibility handling for flight and selection layers

* feat: enhance control panel with new tabs and settings

- Added "Changelog" and "About" tabs to the control panel.
- Introduced new icons for the added tabs using lucide-react.
- Updated the styling of the control panel buttons and dialog.
- Improved accessibility with aria-labels for buttons.

feat: integrate hero banner in flight card

- Added a HeroBanner component to display aircraft photos in the FlightCard.
- Implemented loading and error states for the photo display.
- Enhanced the layout and styling of the FlightCard for better user experience.

fix: update keyboard shortcuts for search functionality

- Added shortcut "⌘K" to open search from anywhere in the application.
- Adjusted keyboard shortcut handling to prevent conflicts with input fields.

fix: optimize flight tracking cache management

- Introduced a maximum cache size for flight tracking to prevent memory growth.
- Implemented a cache eviction strategy for stale entries.

feat: add great-circle utilities for geographical calculations

- Implemented functions for calculating haversine distance, great-circle interpolation, and densifying paths.
- Added functionality to handle antimeridian crossings in geographical paths.

refactor: streamline map styles and terrain handling

- Consolidated terrain DEM source for both terrain mesh and hillshade.
- Adjusted hillshade layer properties for better performance and visual fidelity.

fix: improve bounding box calculations for flight queries

- Enhanced longitude calculations to account for converging meridians at higher latitudes.
- Ensured bounding box calculations are accurate across different latitudes.

* feat(map): refine globe mode functionality and update trail settings
This commit is contained in:
kew
2026-03-11 00:54:51 +05:30
committed by GitHub
parent 3a10da0486
commit 147b69b944
49 changed files with 8662 additions and 3927 deletions

3
.gitignore vendored
View File

@ -45,3 +45,6 @@ next-env.d.ts
# local documentation
docs.txt
ROADMAP.local.md
# heap analysis
scripts/

View File

@ -1,5 +1,25 @@
import type { NextConfig } from "next";
const isDev = process.env.NODE_ENV === "development";
// Content Security Policy — allows only the external resources Aeris actually uses.
// https://nextjs.org/docs/app/guides/content-security-policy
const cspHeader = `
default-src 'self';
script-src 'self' 'unsafe-inline' https://www.googletagmanager.com${isDev ? " 'unsafe-eval'" : ""};
style-src 'self' 'unsafe-inline';
img-src 'self' blob: data: https: ;
font-src 'self';
connect-src 'self' data: https://opensky-network.org https://*.basemaps.cartocdn.com https://basemaps.cartocdn.com https://server.arcgisonline.com https://s3.amazonaws.com https://tile.opentopomap.org https://www.google-analytics.com https://www.googletagmanager.com https://api.github.com https://hexdb.io;
worker-src 'self' blob:;
child-src blob:;
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
upgrade-insecure-requests;
`;
const nextConfig: NextConfig = {
transpilePackages: [
"@deck.gl/core",
@ -25,6 +45,10 @@ const nextConfig: NextConfig = {
{
source: "/(.*)",
headers: [
{
key: "Content-Security-Policy",
value: cspHeader.replace(/\s{2,}/g, " ").trim(),
},
{ key: "X-Content-Type-Options", value: "nosniff" },
{ key: "X-Frame-Options", value: "DENY" },
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },

View File

@ -12,11 +12,11 @@
"lint": "eslint"
},
"dependencies": {
"@deck.gl/core": "^9.2.7",
"@deck.gl/core": "^9.2.11",
"@deck.gl/geo-layers": "^9.2.7",
"@deck.gl/layers": "^9.2.7",
"@deck.gl/mapbox": "^9.2.7",
"@deck.gl/mesh-layers": "^9.2.7",
"@deck.gl/layers": "^9.2.11",
"@deck.gl/mapbox": "^9.2.11",
"@deck.gl/mesh-layers": "^9.2.11",
"@deck.gl/react": "^9.2.7",
"@loaders.gl/core": "^4.3.4",
"@loaders.gl/gltf": "^4.3.4",
@ -24,6 +24,7 @@
"@luma.gl/webgl": "^9.2.6",
"@radix-ui/react-slider": "^1.3.6",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"lucide-react": "^0.564.0",
"maplibre-gl": "^5.18.0",
"motion": "^12.34.0",

436
pnpm-lock.yaml generated
View File

@ -9,23 +9,23 @@ importers:
.:
dependencies:
'@deck.gl/core':
specifier: ^9.2.7
version: 9.2.7
specifier: ^9.2.11
version: 9.2.11
'@deck.gl/geo-layers':
specifier: ^9.2.7
version: 9.2.7(@deck.gl/core@9.2.7)(@deck.gl/extensions@9.2.7(@deck.gl/core@9.2.7)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6))))(@deck.gl/layers@9.2.7(@deck.gl/core@9.2.7)(@loaders.gl/core@4.3.4)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6))))(@deck.gl/mesh-layers@9.2.7(@deck.gl/core@9.2.7)(@loaders.gl/core@4.3.4)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/gltf@9.2.6(@luma.gl/constants@9.2.6)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@loaders.gl/core@4.3.4)(@luma.gl/constants@9.2.6)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))
version: 9.2.7(@deck.gl/core@9.2.11)(@deck.gl/extensions@9.2.7(@deck.gl/core@9.2.11)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6))))(@deck.gl/layers@9.2.11(@deck.gl/core@9.2.11)(@loaders.gl/core@4.3.4)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6))))(@deck.gl/mesh-layers@9.2.11(@deck.gl/core@9.2.11)(@loaders.gl/core@4.3.4)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/gltf@9.2.6(@luma.gl/constants@9.2.6)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@loaders.gl/core@4.3.4)(@luma.gl/constants@9.2.6)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))
'@deck.gl/layers':
specifier: ^9.2.7
version: 9.2.7(@deck.gl/core@9.2.7)(@loaders.gl/core@4.3.4)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))
specifier: ^9.2.11
version: 9.2.11(@deck.gl/core@9.2.11)(@loaders.gl/core@4.3.4)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))
'@deck.gl/mapbox':
specifier: ^9.2.7
version: 9.2.7(@deck.gl/core@9.2.7)(@luma.gl/constants@9.2.6)(@luma.gl/core@9.2.6)(@math.gl/web-mercator@4.1.0)
specifier: ^9.2.11
version: 9.2.11(@deck.gl/core@9.2.11)(@luma.gl/constants@9.2.6)(@luma.gl/core@9.2.6)(@math.gl/web-mercator@4.1.0)
'@deck.gl/mesh-layers':
specifier: ^9.2.7
version: 9.2.7(@deck.gl/core@9.2.7)(@loaders.gl/core@4.3.4)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/gltf@9.2.6(@luma.gl/constants@9.2.6)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6))
specifier: ^9.2.11
version: 9.2.11(@deck.gl/core@9.2.11)(@loaders.gl/core@4.3.4)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/gltf@9.2.6(@luma.gl/constants@9.2.6)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6))
'@deck.gl/react':
specifier: ^9.2.7
version: 9.2.7(@deck.gl/core@9.2.7)(@deck.gl/widgets@9.2.7(@deck.gl/core@9.2.7)(@luma.gl/core@9.2.6))(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
version: 9.2.7(@deck.gl/core@9.2.11)(@deck.gl/widgets@9.2.7(@deck.gl/core@9.2.11)(@luma.gl/core@9.2.6))(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@loaders.gl/core':
specifier: ^4.3.4
version: 4.3.4
@ -44,6 +44,9 @@ importers:
clsx:
specifier: ^2.1.1
version: 2.1.1
cmdk:
specifier: ^1.1.1
version: 1.1.1(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
lucide-react:
specifier: ^0.564.0
version: 0.564.0(react@19.2.3)
@ -167,8 +170,8 @@ packages:
resolution: {integrity: sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==}
engines: {node: '>=6.9.0'}
'@deck.gl/core@9.2.7':
resolution: {integrity: sha512-mltYFDC2dMtAZPkAaVIadccbM3iy9jjnhLa5obFnWzPtXyc1UBr7OW50Cjy0IlQmAsgDI2BATzcw5a/p4zU8zw==}
'@deck.gl/core@9.2.11':
resolution: {integrity: sha512-lpdxXQuFSkd6ET7M6QxPI8QMhsLRY6vzLyk83sPGFb7JSb4OhrNHYt9sfIhcA/hxJW7bdBSMWWphf2GvQetVuA==}
'@deck.gl/extensions@9.2.7':
resolution: {integrity: sha512-jIsep2NByEimWlScqc/NLjpqWknLk5rd+uP8UAl7qI8CTInXV4KdzaYgujL+bE4lSV4Zlg0oMOAkbcviMKDLNw==}
@ -188,24 +191,24 @@ packages:
'@luma.gl/core': ~9.2.6
'@luma.gl/engine': ~9.2.6
'@deck.gl/layers@9.2.7':
resolution: {integrity: sha512-oGRv3s+i+Rq4qQFTfdCBx2S650K4p0gGS/bPYpURCXW0a0LQBHqN8AkKbhdos7b7Lawp1iMwkIggBZSZaNkyXg==}
'@deck.gl/layers@9.2.11':
resolution: {integrity: sha512-2FSb0Qa6YR+Rg6GWhYOGTUug3vtZ4uKcFdnrdiJoVXGyibKJMScKZIsivY0r/yQQZsaBjYqty5QuVJvdtEHxSA==}
peerDependencies:
'@deck.gl/core': ~9.2.0
'@loaders.gl/core': ^4.3.4
'@loaders.gl/core': ~4.3.4
'@luma.gl/core': ~9.2.6
'@luma.gl/engine': ~9.2.6
'@deck.gl/mapbox@9.2.7':
resolution: {integrity: sha512-kcTMavoM9RqGbDXg78U/DGlR3dCQMR5+9ctc83qy0aNP57zQ62okomnq9DVCfxvcQjYb1uMqAt3HaBespInRcA==}
'@deck.gl/mapbox@9.2.11':
resolution: {integrity: sha512-5OaFZgjyA4Vq6WjHUdcEdl0Phi8dwj8hSCErej0NetW90mctdbxwMt0gSbqcvWBowwhyj2QAhH0P2FcITjKG/A==}
peerDependencies:
'@deck.gl/core': ~9.2.0
'@luma.gl/constants': ~9.2.6
'@luma.gl/core': ~9.2.6
'@math.gl/web-mercator': ^4.1.0
'@deck.gl/mesh-layers@9.2.7':
resolution: {integrity: sha512-EpWHJ3GaCXELCsYRlabvkXxtgLQwOZYU8YPOmlKUYf+/410B2D89oNGtJinRcfM1/T9TBelBS9CHMYsL1tv9cA==}
'@deck.gl/mesh-layers@9.2.11':
resolution: {integrity: sha512-zPB7TtnPXB3tOEoOfcOkNZo7coIq/ukIQa8HIUQLLiOE8AVSQfz3kbMmMK6rUabXlQbgSw/I/j3kFSYRHg3NGg==}
peerDependencies:
'@deck.gl/core': ~9.2.0
'@luma.gl/core': ~9.2.6
@ -729,12 +732,21 @@ packages:
'@probe.gl/env@4.1.0':
resolution: {integrity: sha512-5ac2Jm2K72VCs4eSMsM7ykVRrV47w32xOGMvcgqn8vQdEMF9PRXyBGYEV9YbqRKWNKpNKmQJVi4AHM/fkCxs9w==}
'@probe.gl/env@4.1.1':
resolution: {integrity: sha512-+68seNDMVsEegRB47pFA/Ws1Fjy8agcFYXxzorKToyPcD6zd+gZ5uhwoLd7TzsSw6Ydns//2KEszWn+EnNHTbA==}
'@probe.gl/log@4.1.0':
resolution: {integrity: sha512-r4gRReNY6f+OZEMgfWEXrAE2qJEt8rX0HsDJQXUBMoc+5H47bdB7f/5HBHAmapK8UydwPKL9wCDoS22rJ0yq7Q==}
'@probe.gl/log@4.1.1':
resolution: {integrity: sha512-kcZs9BT44pL7hS1OkRGKYRXI/SN9KejUlPD+BY40DguRLzdC5tLG/28WGMyfKdn/51GT4a0p+0P8xvDn1Ez+Kg==}
'@probe.gl/stats@4.1.0':
resolution: {integrity: sha512-EI413MkWKBDVNIfLdqbeNSJTs7ToBz/KVGkwi3D+dQrSIkRI2IYbWGAU3xX+D6+CI4ls8ehxMhNpUVMaZggDvQ==}
'@probe.gl/stats@4.1.1':
resolution: {integrity: sha512-4VpAyMHOqydSvPlEyHwXaE+AkIdR03nX+Qhlxsk2D/IW4OVmDZgIsvJB1cDzyEEtcfKcnaEbfXeiPgejBceT6g==}
'@radix-ui/number@1.1.1':
resolution: {integrity: sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g==}
@ -772,6 +784,19 @@ packages:
'@types/react':
optional: true
'@radix-ui/react-dialog@1.1.15':
resolution: {integrity: sha512-TCglVRtzlffRNxRMEyR36DGBLJpeusFcgMVD9PZEzAKnUs1lKCgX5u9BmC2Yg+LL9MgZDugFFs1Vl+Jp4t/PGw==}
peerDependencies:
'@types/react': '*'
'@types/react-dom': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@types/react-dom':
optional: true
'@radix-ui/react-direction@1.1.1':
resolution: {integrity: sha512-1UEWRX6jnOA2y4H5WczZ44gOOjTEmlqv1uNW4GAJEO5+bauCBhv8snY65Iw5/VOS/ghKN9gr2KjnLKxrsvoMVw==}
peerDependencies:
@ -781,6 +806,76 @@ packages:
'@types/react':
optional: true
'@radix-ui/react-dismissable-layer@1.1.11':
resolution: {integrity: sha512-Nqcp+t5cTB8BinFkZgXiMJniQH0PsUt2k51FUhbdfeKvc4ACcG2uQniY/8+h1Yv6Kza4Q7lD7PQV0z0oicE0Mg==}
peerDependencies:
'@types/react': '*'
'@types/react-dom': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@types/react-dom':
optional: true
'@radix-ui/react-focus-guards@1.1.3':
resolution: {integrity: sha512-0rFg/Rj2Q62NCm62jZw0QX7a3sz6QCQU0LpZdNrJX8byRGaGVTqbrW9jAoIAHyMQqsNpeZ81YgSizOt5WXq0Pw==}
peerDependencies:
'@types/react': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@radix-ui/react-focus-scope@1.1.7':
resolution: {integrity: sha512-t2ODlkXBQyn7jkl6TNaw/MtVEVvIGelJDCG41Okq/KwUsJBwQ4XVZsHAVUkK4mBv3ewiAS3PGuUWuY2BoK4ZUw==}
peerDependencies:
'@types/react': '*'
'@types/react-dom': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@types/react-dom':
optional: true
'@radix-ui/react-id@1.1.1':
resolution: {integrity: sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg==}
peerDependencies:
'@types/react': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@radix-ui/react-portal@1.1.9':
resolution: {integrity: sha512-bpIxvq03if6UNwXZ+HTK71JLh4APvnXntDc6XOX8UVq4XQOVl7lwok0AvIl+b8zgCw3fSaVTZMpAPPagXbKmHQ==}
peerDependencies:
'@types/react': '*'
'@types/react-dom': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@types/react-dom':
optional: true
'@radix-ui/react-presence@1.1.5':
resolution: {integrity: sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ==}
peerDependencies:
'@types/react': '*'
'@types/react-dom': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@types/react-dom':
optional: true
'@radix-ui/react-primitive@2.1.3':
resolution: {integrity: sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ==}
peerDependencies:
@ -816,6 +911,15 @@ packages:
'@types/react':
optional: true
'@radix-ui/react-use-callback-ref@1.1.1':
resolution: {integrity: sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg==}
peerDependencies:
'@types/react': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@radix-ui/react-use-controllable-state@1.2.2':
resolution: {integrity: sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg==}
peerDependencies:
@ -834,6 +938,15 @@ packages:
'@types/react':
optional: true
'@radix-ui/react-use-escape-keydown@1.1.1':
resolution: {integrity: sha512-Il0+boE7w/XebUHyBjroE+DbByORGR9KKmITzbR7MyQ4akpORYP/ZmbhAr0DG7RmmBqoOnZdy2QlvajJ2QA59g==}
peerDependencies:
'@types/react': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@radix-ui/react-use-layout-effect@1.1.1':
resolution: {integrity: sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ==}
peerDependencies:
@ -1206,6 +1319,10 @@ packages:
argparse@2.0.1:
resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==}
aria-hidden@1.2.6:
resolution: {integrity: sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==}
engines: {node: '>=10'}
aria-query@5.3.2:
resolution: {integrity: sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==}
engines: {node: '>= 0.4'}
@ -1326,6 +1443,12 @@ packages:
resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==}
engines: {node: '>=6'}
cmdk@1.1.1:
resolution: {integrity: sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg==}
peerDependencies:
react: ^18 || ^19 || ^19.0.0-rc
react-dom: ^18 || ^19 || ^19.0.0-rc
color-convert@2.0.1:
resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==}
engines: {node: '>=7.0.0'}
@ -1407,6 +1530,9 @@ packages:
resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
engines: {node: '>=8'}
detect-node-es@1.1.0:
resolution: {integrity: sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==}
doctrine@2.1.0:
resolution: {integrity: sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==}
engines: {node: '>=0.10.0'}
@ -1681,6 +1807,10 @@ packages:
resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==}
engines: {node: '>= 0.4'}
get-nonce@1.0.1:
resolution: {integrity: sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==}
engines: {node: '>=6'}
get-proto@1.0.1:
resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==}
engines: {node: '>= 0.4'}
@ -2296,8 +2426,8 @@ packages:
potpack@2.1.0:
resolution: {integrity: sha512-pcaShQc1Shq0y+E7GqJqvZj8DTthWV1KeHGdi0Z6IAin2Oi3JnLCOfwnCo84qc+HAp52wT9nK9H7FAJp5a44GQ==}
preact@10.28.3:
resolution: {integrity: sha512-tCmoRkPQLpBeWzpmbhryairGnhW9tKV6c6gr/w+RhoRoKEJwsjzipwp//1oCpGPOchvSLaAPlpcJi9MwMmoPyA==}
preact@10.28.4:
resolution: {integrity: sha512-uKFfOHWuSNpRFVTnljsCluEFq57OKT+0QdOiQo8XWnQ/pSvg7OpX5eNOejELXJMWy+BwM2nobz0FkvzmnpCNsQ==}
prelude-ls@1.2.1:
resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==}
@ -2330,6 +2460,36 @@ packages:
react-is@16.13.1:
resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}
react-remove-scroll-bar@2.3.8:
resolution: {integrity: sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q==}
engines: {node: '>=10'}
peerDependencies:
'@types/react': '*'
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
peerDependenciesMeta:
'@types/react':
optional: true
react-remove-scroll@2.7.2:
resolution: {integrity: sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q==}
engines: {node: '>=10'}
peerDependencies:
'@types/react': '*'
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
react-style-singleton@2.2.3:
resolution: {integrity: sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==}
engines: {node: '>=10'}
peerDependencies:
'@types/react': '*'
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
react@19.2.3:
resolution: {integrity: sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==}
engines: {node: '>=0.10.0'}
@ -2610,6 +2770,26 @@ packages:
uri-js@4.4.1:
resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==}
use-callback-ref@1.3.3:
resolution: {integrity: sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg==}
engines: {node: '>=10'}
peerDependencies:
'@types/react': '*'
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
use-sidecar@1.1.3:
resolution: {integrity: sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ==}
engines: {node: '>=10'}
peerDependencies:
'@types/react': '*'
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
util-deprecate@1.0.2:
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
@ -2764,7 +2944,7 @@ snapshots:
'@babel/helper-string-parser': 7.27.1
'@babel/helper-validator-identifier': 7.28.5
'@deck.gl/core@9.2.7':
'@deck.gl/core@9.2.11':
dependencies:
'@loaders.gl/core': 4.3.4
'@loaders.gl/images': 4.3.4(@loaders.gl/core@4.3.4)
@ -2777,28 +2957,28 @@ snapshots:
'@math.gl/sun': 4.1.0
'@math.gl/types': 4.1.0
'@math.gl/web-mercator': 4.1.0
'@probe.gl/env': 4.1.0
'@probe.gl/log': 4.1.0
'@probe.gl/stats': 4.1.0
'@probe.gl/env': 4.1.1
'@probe.gl/log': 4.1.1
'@probe.gl/stats': 4.1.1
'@types/offscreencanvas': 2019.7.3
gl-matrix: 3.4.4
mjolnir.js: 3.0.0
'@deck.gl/extensions@9.2.7(@deck.gl/core@9.2.7)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))':
'@deck.gl/extensions@9.2.7(@deck.gl/core@9.2.11)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))':
dependencies:
'@deck.gl/core': 9.2.7
'@deck.gl/core': 9.2.11
'@luma.gl/constants': 9.2.6
'@luma.gl/core': 9.2.6
'@luma.gl/engine': 9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6))
'@luma.gl/shadertools': 9.2.6(@luma.gl/core@9.2.6)
'@math.gl/core': 4.1.0
'@deck.gl/geo-layers@9.2.7(@deck.gl/core@9.2.7)(@deck.gl/extensions@9.2.7(@deck.gl/core@9.2.7)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6))))(@deck.gl/layers@9.2.7(@deck.gl/core@9.2.7)(@loaders.gl/core@4.3.4)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6))))(@deck.gl/mesh-layers@9.2.7(@deck.gl/core@9.2.7)(@loaders.gl/core@4.3.4)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/gltf@9.2.6(@luma.gl/constants@9.2.6)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@loaders.gl/core@4.3.4)(@luma.gl/constants@9.2.6)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))':
'@deck.gl/geo-layers@9.2.7(@deck.gl/core@9.2.11)(@deck.gl/extensions@9.2.7(@deck.gl/core@9.2.11)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6))))(@deck.gl/layers@9.2.11(@deck.gl/core@9.2.11)(@loaders.gl/core@4.3.4)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6))))(@deck.gl/mesh-layers@9.2.11(@deck.gl/core@9.2.11)(@loaders.gl/core@4.3.4)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/gltf@9.2.6(@luma.gl/constants@9.2.6)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@loaders.gl/core@4.3.4)(@luma.gl/constants@9.2.6)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))':
dependencies:
'@deck.gl/core': 9.2.7
'@deck.gl/extensions': 9.2.7(@deck.gl/core@9.2.7)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))
'@deck.gl/layers': 9.2.7(@deck.gl/core@9.2.7)(@loaders.gl/core@4.3.4)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))
'@deck.gl/mesh-layers': 9.2.7(@deck.gl/core@9.2.7)(@loaders.gl/core@4.3.4)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/gltf@9.2.6(@luma.gl/constants@9.2.6)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6))
'@deck.gl/core': 9.2.11
'@deck.gl/extensions': 9.2.7(@deck.gl/core@9.2.11)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))
'@deck.gl/layers': 9.2.11(@deck.gl/core@9.2.11)(@loaders.gl/core@4.3.4)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))
'@deck.gl/mesh-layers': 9.2.11(@deck.gl/core@9.2.11)(@loaders.gl/core@4.3.4)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/gltf@9.2.6(@luma.gl/constants@9.2.6)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6))
'@loaders.gl/3d-tiles': 4.3.4(@loaders.gl/core@4.3.4)
'@loaders.gl/core': 4.3.4
'@loaders.gl/gis': 4.3.4(@loaders.gl/core@4.3.4)
@ -2822,9 +3002,9 @@ snapshots:
transitivePeerDependencies:
- '@luma.gl/constants'
'@deck.gl/layers@9.2.7(@deck.gl/core@9.2.7)(@loaders.gl/core@4.3.4)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))':
'@deck.gl/layers@9.2.11(@deck.gl/core@9.2.11)(@loaders.gl/core@4.3.4)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))':
dependencies:
'@deck.gl/core': 9.2.7
'@deck.gl/core': 9.2.11
'@loaders.gl/core': 4.3.4
'@loaders.gl/images': 4.3.4(@loaders.gl/core@4.3.4)
'@loaders.gl/schema': 4.3.4(@loaders.gl/core@4.3.4)
@ -2837,16 +3017,16 @@ snapshots:
'@math.gl/web-mercator': 4.1.0
earcut: 2.2.4
'@deck.gl/mapbox@9.2.7(@deck.gl/core@9.2.7)(@luma.gl/constants@9.2.6)(@luma.gl/core@9.2.6)(@math.gl/web-mercator@4.1.0)':
'@deck.gl/mapbox@9.2.11(@deck.gl/core@9.2.11)(@luma.gl/constants@9.2.6)(@luma.gl/core@9.2.6)(@math.gl/web-mercator@4.1.0)':
dependencies:
'@deck.gl/core': 9.2.7
'@deck.gl/core': 9.2.11
'@luma.gl/constants': 9.2.6
'@luma.gl/core': 9.2.6
'@math.gl/web-mercator': 4.1.0
'@deck.gl/mesh-layers@9.2.7(@deck.gl/core@9.2.7)(@loaders.gl/core@4.3.4)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/gltf@9.2.6(@luma.gl/constants@9.2.6)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6))':
'@deck.gl/mesh-layers@9.2.11(@deck.gl/core@9.2.11)(@loaders.gl/core@4.3.4)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/gltf@9.2.6(@luma.gl/constants@9.2.6)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6))':
dependencies:
'@deck.gl/core': 9.2.7
'@deck.gl/core': 9.2.11
'@loaders.gl/gltf': 4.3.4(@loaders.gl/core@4.3.4)
'@loaders.gl/schema': 4.3.4(@loaders.gl/core@4.3.4)
'@luma.gl/core': 9.2.6
@ -2856,18 +3036,18 @@ snapshots:
transitivePeerDependencies:
- '@loaders.gl/core'
'@deck.gl/react@9.2.7(@deck.gl/core@9.2.7)(@deck.gl/widgets@9.2.7(@deck.gl/core@9.2.7)(@luma.gl/core@9.2.6))(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
'@deck.gl/react@9.2.7(@deck.gl/core@9.2.11)(@deck.gl/widgets@9.2.7(@deck.gl/core@9.2.11)(@luma.gl/core@9.2.6))(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
dependencies:
'@deck.gl/core': 9.2.7
'@deck.gl/widgets': 9.2.7(@deck.gl/core@9.2.7)(@luma.gl/core@9.2.6)
'@deck.gl/core': 9.2.11
'@deck.gl/widgets': 9.2.7(@deck.gl/core@9.2.11)(@luma.gl/core@9.2.6)
react: 19.2.3
react-dom: 19.2.3(react@19.2.3)
'@deck.gl/widgets@9.2.7(@deck.gl/core@9.2.7)(@luma.gl/core@9.2.6)':
'@deck.gl/widgets@9.2.7(@deck.gl/core@9.2.11)(@luma.gl/core@9.2.6)':
dependencies:
'@deck.gl/core': 9.2.7
'@deck.gl/core': 9.2.11
'@luma.gl/core': 9.2.6
preact: 10.28.3
preact: 10.28.4
'@emnapi/core@1.8.1':
dependencies:
@ -3245,8 +3425,8 @@ snapshots:
'@luma.gl/shadertools': 9.2.6(@luma.gl/core@9.2.6)
'@math.gl/core': 4.1.0
'@math.gl/types': 4.1.0
'@probe.gl/log': 4.1.0
'@probe.gl/stats': 4.1.0
'@probe.gl/log': 4.1.1
'@probe.gl/stats': 4.1.1
'@luma.gl/gltf@9.2.6(@luma.gl/constants@9.2.6)(@luma.gl/core@9.2.6)(@luma.gl/engine@9.2.6(@luma.gl/core@9.2.6)(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6)))(@luma.gl/shadertools@9.2.6(@luma.gl/core@9.2.6))':
dependencies:
@ -3407,12 +3587,20 @@ snapshots:
'@probe.gl/env@4.1.0': {}
'@probe.gl/env@4.1.1': {}
'@probe.gl/log@4.1.0':
dependencies:
'@probe.gl/env': 4.1.0
'@probe.gl/log@4.1.1':
dependencies:
'@probe.gl/env': 4.1.1
'@probe.gl/stats@4.1.0': {}
'@probe.gl/stats@4.1.1': {}
'@radix-ui/number@1.1.1': {}
'@radix-ui/primitive@1.1.3': {}
@ -3441,12 +3629,91 @@ snapshots:
optionalDependencies:
'@types/react': 19.2.14
'@radix-ui/react-dialog@1.1.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
dependencies:
'@radix-ui/primitive': 1.1.3
'@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.3)
'@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.3)
'@radix-ui/react-dismissable-layer': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-focus-guards': 1.1.3(@types/react@19.2.14)(react@19.2.3)
'@radix-ui/react-focus-scope': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.3)
'@radix-ui/react-portal': 1.1.9(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-slot': 1.2.3(@types/react@19.2.14)(react@19.2.3)
'@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.3)
aria-hidden: 1.2.6
react: 19.2.3
react-dom: 19.2.3(react@19.2.3)
react-remove-scroll: 2.7.2(@types/react@19.2.14)(react@19.2.3)
optionalDependencies:
'@types/react': 19.2.14
'@types/react-dom': 19.2.3(@types/react@19.2.14)
'@radix-ui/react-direction@1.1.1(@types/react@19.2.14)(react@19.2.3)':
dependencies:
react: 19.2.3
optionalDependencies:
'@types/react': 19.2.14
'@radix-ui/react-dismissable-layer@1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
dependencies:
'@radix-ui/primitive': 1.1.3
'@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.3)
'@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-use-callback-ref': 1.1.1(@types/react@19.2.14)(react@19.2.3)
'@radix-ui/react-use-escape-keydown': 1.1.1(@types/react@19.2.14)(react@19.2.3)
react: 19.2.3
react-dom: 19.2.3(react@19.2.3)
optionalDependencies:
'@types/react': 19.2.14
'@types/react-dom': 19.2.3(@types/react@19.2.14)
'@radix-ui/react-focus-guards@1.1.3(@types/react@19.2.14)(react@19.2.3)':
dependencies:
react: 19.2.3
optionalDependencies:
'@types/react': 19.2.14
'@radix-ui/react-focus-scope@1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
dependencies:
'@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.3)
'@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-use-callback-ref': 1.1.1(@types/react@19.2.14)(react@19.2.3)
react: 19.2.3
react-dom: 19.2.3(react@19.2.3)
optionalDependencies:
'@types/react': 19.2.14
'@types/react-dom': 19.2.3(@types/react@19.2.14)
'@radix-ui/react-id@1.1.1(@types/react@19.2.14)(react@19.2.3)':
dependencies:
'@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.3)
react: 19.2.3
optionalDependencies:
'@types/react': 19.2.14
'@radix-ui/react-portal@1.1.9(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
dependencies:
'@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.3)
react: 19.2.3
react-dom: 19.2.3(react@19.2.3)
optionalDependencies:
'@types/react': 19.2.14
'@types/react-dom': 19.2.3(@types/react@19.2.14)
'@radix-ui/react-presence@1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
dependencies:
'@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.3)
'@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.3)
react: 19.2.3
react-dom: 19.2.3(react@19.2.3)
optionalDependencies:
'@types/react': 19.2.14
'@types/react-dom': 19.2.3(@types/react@19.2.14)
'@radix-ui/react-primitive@2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
dependencies:
'@radix-ui/react-slot': 1.2.3(@types/react@19.2.14)(react@19.2.3)
@ -3482,6 +3749,12 @@ snapshots:
optionalDependencies:
'@types/react': 19.2.14
'@radix-ui/react-use-callback-ref@1.1.1(@types/react@19.2.14)(react@19.2.3)':
dependencies:
react: 19.2.3
optionalDependencies:
'@types/react': 19.2.14
'@radix-ui/react-use-controllable-state@1.2.2(@types/react@19.2.14)(react@19.2.3)':
dependencies:
'@radix-ui/react-use-effect-event': 0.0.2(@types/react@19.2.14)(react@19.2.3)
@ -3497,6 +3770,13 @@ snapshots:
optionalDependencies:
'@types/react': 19.2.14
'@radix-ui/react-use-escape-keydown@1.1.1(@types/react@19.2.14)(react@19.2.3)':
dependencies:
'@radix-ui/react-use-callback-ref': 1.1.1(@types/react@19.2.14)(react@19.2.3)
react: 19.2.3
optionalDependencies:
'@types/react': 19.2.14
'@radix-ui/react-use-layout-effect@1.1.1(@types/react@19.2.14)(react@19.2.3)':
dependencies:
react: 19.2.3
@ -3834,6 +4114,10 @@ snapshots:
argparse@2.0.1: {}
aria-hidden@1.2.6:
dependencies:
tslib: 2.8.1
aria-query@5.3.2: {}
array-buffer-byte-length@1.0.2:
@ -3982,6 +4266,18 @@ snapshots:
clsx@2.1.1: {}
cmdk@1.1.1(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3):
dependencies:
'@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.3)
'@radix-ui/react-dialog': 1.1.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.3)
'@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
react: 19.2.3
react-dom: 19.2.3(react@19.2.3)
transitivePeerDependencies:
- '@types/react'
- '@types/react-dom'
color-convert@2.0.1:
dependencies:
color-name: 1.1.4
@ -4057,6 +4353,8 @@ snapshots:
detect-libc@2.1.2: {}
detect-node-es@1.1.0: {}
doctrine@2.1.0:
dependencies:
esutils: 2.0.3
@ -4481,6 +4779,8 @@ snapshots:
hasown: 2.0.2
math-intrinsics: 1.1.0
get-nonce@1.0.1: {}
get-proto@1.0.1:
dependencies:
dunder-proto: 1.0.1
@ -5063,7 +5363,7 @@ snapshots:
potpack@2.1.0: {}
preact@10.28.3: {}
preact@10.28.4: {}
prelude-ls@1.2.1: {}
@ -5090,6 +5390,33 @@ snapshots:
react-is@16.13.1: {}
react-remove-scroll-bar@2.3.8(@types/react@19.2.14)(react@19.2.3):
dependencies:
react: 19.2.3
react-style-singleton: 2.2.3(@types/react@19.2.14)(react@19.2.3)
tslib: 2.8.1
optionalDependencies:
'@types/react': 19.2.14
react-remove-scroll@2.7.2(@types/react@19.2.14)(react@19.2.3):
dependencies:
react: 19.2.3
react-remove-scroll-bar: 2.3.8(@types/react@19.2.14)(react@19.2.3)
react-style-singleton: 2.2.3(@types/react@19.2.14)(react@19.2.3)
tslib: 2.8.1
use-callback-ref: 1.3.3(@types/react@19.2.14)(react@19.2.3)
use-sidecar: 1.1.3(@types/react@19.2.14)(react@19.2.3)
optionalDependencies:
'@types/react': 19.2.14
react-style-singleton@2.2.3(@types/react@19.2.14)(react@19.2.3):
dependencies:
get-nonce: 1.0.1
react: 19.2.3
tslib: 2.8.1
optionalDependencies:
'@types/react': 19.2.14
react@19.2.3: {}
readable-stream@2.3.8:
@ -5485,6 +5812,21 @@ snapshots:
dependencies:
punycode: 2.3.1
use-callback-ref@1.3.3(@types/react@19.2.14)(react@19.2.3):
dependencies:
react: 19.2.3
tslib: 2.8.1
optionalDependencies:
'@types/react': 19.2.14
use-sidecar@1.1.3(@types/react@19.2.14)(react@19.2.3):
dependencies:
detect-node-es: 1.1.0
react: 19.2.3
tslib: 2.8.1
optionalDependencies:
'@types/react': 19.2.14
util-deprecate@1.0.2: {}
wgsl_reflect@1.2.3: {}

View File

@ -0,0 +1,68 @@
import { NextRequest, NextResponse } from "next/server";
const JETAPI_BASE = "https://www.jetapi.dev/api";
const FETCH_TIMEOUT_MS = 12_000;
const REG_REGEX = /^[A-Z0-9-]{2,10}$/i;
export async function GET(request: NextRequest): Promise<NextResponse> {
const reg = request.nextUrl.searchParams.get("reg")?.trim();
if (!reg || !REG_REGEX.test(reg)) {
return NextResponse.json(
{ error: "Missing or invalid 'reg' parameter" },
{ status: 400, headers: { "Cache-Control": "no-store" } },
);
}
const params = new URLSearchParams({
reg,
photos: "10",
flights: "0",
});
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
try {
const upstream = await fetch(`${JETAPI_BASE}?${params.toString()}`, {
signal: controller.signal,
headers: { Accept: "application/json" },
});
clearTimeout(timer);
if (!upstream.ok) {
return NextResponse.json(
{ error: "Upstream error" },
{
status: upstream.status >= 500 ? 502 : upstream.status,
headers: { "Cache-Control": "no-store" },
},
);
}
const data: unknown = await upstream.json();
return NextResponse.json(data, {
status: 200,
headers: {
"Cache-Control":
"public, max-age=1800, s-maxage=1800, stale-while-revalidate=3600",
},
});
} catch (err) {
clearTimeout(timer);
if (err instanceof DOMException && err.name === "AbortError") {
return NextResponse.json(
{ error: "Upstream timeout" },
{ status: 504, headers: { "Cache-Control": "no-store" } },
);
}
return NextResponse.json(
{ error: "Proxy error" },
{ status: 502, headers: { "Cache-Control": "no-store" } },
);
}
}

View File

@ -81,3 +81,65 @@ body {
scroll-behavior: auto !important;
}
}
/* ── cmdk styles ─────────────────────────────────────────────────────── */
.aeris-cmdk [cmdk-input] {
border: none;
outline: none;
background: transparent;
}
.aeris-cmdk [cmdk-group-heading] {
padding: 6px 12px 4px;
font-size: 10px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.08em;
color: rgb(255 255 255 / 0.15);
user-select: none;
}
.aeris-cmdk [cmdk-list] {
overscroll-behavior: contain;
}
.aeris-cmdk [cmdk-group] + [cmdk-group] {
padding-top: 4px;
}
.aeris-cmdk [cmdk-empty] {
display: flex;
}
.aeris-cmdk .search-item {
position: relative;
display: flex;
align-items: center;
gap: 10px;
border-radius: 12px;
padding: 8px 12px;
cursor: pointer;
transition: background-color 0.12s ease;
outline: none;
user-select: none;
}
.aeris-cmdk .search-item[data-selected="true"] {
background: rgb(255 255 255 / 0.05);
}
.aeris-cmdk
[cmdk-item][data-selected="true"]
.group-data-\[selected\=true\]\/item\:opacity-100 {
opacity: 1;
}
.aeris-cmdk .search-item[data-disabled="true"] {
opacity: 0.5;
cursor: not-allowed;
}
.aeris-cmdk .search-item:active:not([data-disabled="true"]) {
background: rgb(255 255 255 / 0.07);
}

View File

@ -0,0 +1,72 @@
import { AIRPORTS } from "@/lib/airports";
import { airportToCity } from "@/lib/airports";
import type { City } from "@/lib/cities";
import type { FlightState } from "@/lib/opensky";
import { DEFAULT_CITY } from "@/components/flight-tracker-utils";
const HIGH_TRAFFIC_IATA = [
"ATL",
"DXB",
"LHR",
"HND",
"DFW",
"DEN",
"IST",
"LAX",
"CDG",
"AMS",
"FRA",
"MAD",
"JFK",
"SIN",
"ORD",
"SFO",
"MIA",
"LAS",
"MUC",
"CLT",
] as const;
const HUB_PICK_PROBABILITY = 0.75;
const HIGH_TRAFFIC_IATA_SET = new Set<string>(HIGH_TRAFFIC_IATA);
const HIGH_TRAFFIC_AIRPORTS = AIRPORTS.filter((airport) =>
HIGH_TRAFFIC_IATA_SET.has(airport.iata.toUpperCase()),
);
function chooseRandom<T>(items: readonly T[]): T | null {
if (items.length === 0) return null;
return items[Math.floor(Math.random() * items.length)] ?? null;
}
export function pickRandomAirportCity(excludeIata?: string): City {
const exclude = excludeIata?.toUpperCase();
const filteredHubs = exclude
? HIGH_TRAFFIC_AIRPORTS.filter(
(airport) => airport.iata.toUpperCase() !== exclude,
)
: HIGH_TRAFFIC_AIRPORTS;
const filteredAirports = exclude
? AIRPORTS.filter((airport) => airport.iata.toUpperCase() !== exclude)
: AIRPORTS;
const useHubs =
filteredHubs.length > 0 && Math.random() < HUB_PICK_PROBABILITY;
const source = useHubs ? filteredHubs : filteredAirports;
const randomAirport = chooseRandom(source);
if (!randomAirport) return DEFAULT_CITY;
return airportToCity(randomAirport);
}
export function cityFromFlight(flight: FlightState): City | null {
if (flight.longitude == null || flight.latitude == null) return null;
const code = flight.icao24.toUpperCase();
return {
id: `trk-${flight.icao24}`,
name: `Flight ${code}`,
country: flight.originCountry || "Unknown",
iata: code.slice(0, 3),
coordinates: [flight.longitude, flight.latitude],
radius: 2,
};
}

View File

@ -0,0 +1,119 @@
import { CITIES, type City } from "@/lib/cities";
import { findByIata, airportToCity } from "@/lib/airports";
import { MAP_STYLES, DEFAULT_STYLE, type MapStyle } from "@/lib/map-styles";
export { DEFAULT_STYLE };
export const DEFAULT_CITY_ID = "sfo";
export const STYLE_STORAGE_KEY = "aeris:mapStyle";
export const DEFAULT_CITY =
CITIES.find((c) => c.id === DEFAULT_CITY_ID) ?? CITIES[0];
export const GITHUB_REPO_URL = "https://github.com/kewonit/aeris";
export const GITHUB_REPO_API = "https://api.github.com/repos/kewonit/aeris";
export const ICAO24_REGEX = /^[0-9a-f]{6}$/i;
export const subscribeNoop = () => () => {};
let _cachedInitialCity: City | null = null;
export function resolveInitialCity(): City {
if (_cachedInitialCity) return _cachedInitialCity;
try {
const params = new URLSearchParams(window.location.search);
const code = params.get("city")?.trim().toUpperCase();
if (!code) {
_cachedInitialCity = DEFAULT_CITY;
return DEFAULT_CITY;
}
const preset = CITIES.find(
(c) => c.iata.toUpperCase() === code || c.id === code.toLowerCase(),
);
if (preset) {
_cachedInitialCity = preset;
return preset;
}
const airport = findByIata(code);
if (airport) {
_cachedInitialCity = airportToCity(airport);
return _cachedInitialCity;
}
_cachedInitialCity = DEFAULT_CITY;
return DEFAULT_CITY;
} catch {
_cachedInitialCity = DEFAULT_CITY;
return DEFAULT_CITY;
}
}
export function syncCityToUrl(city: City): void {
if (typeof window === "undefined") return;
try {
const url = new URL(window.location.href);
url.searchParams.set("city", city.iata);
url.searchParams.delete("from");
url.searchParams.delete("to");
url.searchParams.delete("fpv");
window.history.replaceState(null, "", url.toString());
} catch {
/* ignore */
}
}
export function syncFpvToUrl(icao24: string | null, activeCity?: City): void {
if (typeof window === "undefined") return;
try {
const url = new URL(window.location.href);
if (icao24) {
url.searchParams.set("fpv", icao24);
url.searchParams.delete("city");
url.searchParams.delete("from");
url.searchParams.delete("to");
} else {
url.searchParams.delete("fpv");
if (activeCity) {
url.searchParams.set("city", activeCity.iata);
}
}
window.history.replaceState(null, "", url.toString());
} catch {
/* ignore */
}
}
export function resolveInitialFpv(): string | null {
try {
const params = new URLSearchParams(window.location.search);
const raw = params.get("fpv")?.trim().toLowerCase();
return raw && /^[0-9a-f]{6}$/.test(raw) ? raw : null;
} catch {
return null;
}
}
export function loadMapStyle(): MapStyle {
try {
const id = localStorage.getItem(STYLE_STORAGE_KEY);
if (!id) return DEFAULT_STYLE;
return MAP_STYLES.find((s) => s.id === id) ?? DEFAULT_STYLE;
} catch {
return DEFAULT_STYLE;
}
}
export function saveMapStyle(style: MapStyle): void {
if (typeof window === "undefined") return;
try {
localStorage.setItem(STYLE_STORAGE_KEY, style.id);
} catch {
/* blocked */
}
}
export function formatStarCount(value: number): string {
if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}m`;
if (value >= 1_000) return `${(value / 1_000).toFixed(1)}k`;
return `${value}`;
}

View File

@ -8,7 +8,7 @@ import {
useRef,
useSyncExternalStore,
} from "react";
import { motion, AnimatePresence } from "motion/react";
import { AnimatePresence } from "motion/react";
import { ErrorBoundary } from "@/components/error-boundary";
import { Map as MapView } from "@/components/map/map";
import { CameraController } from "@/components/map/camera-controller";
@ -16,7 +16,6 @@ import { AirportLayer } from "@/components/map/airport-layer";
import { FlightLayers } from "@/components/map/flight-layers";
import { FlightCard } from "@/components/ui/flight-card";
import { FpvHud } from "@/components/ui/fpv-hud";
import { KeyboardShortcutsHelp } from "@/components/ui/keyboard-shortcuts-help";
import { ControlPanel } from "@/components/ui/control-panel";
import { AltitudeLegend } from "@/components/ui/altitude-legend";
import { CameraControls } from "@/components/ui/camera-controls";
@ -27,191 +26,36 @@ import { useKeyboardShortcuts } from "@/hooks/use-keyboard-shortcuts";
import { useFlights } from "@/hooks/use-flights";
import { useTrailHistory } from "@/hooks/use-trail-history";
import { useFlightTrack } from "@/hooks/use-flight-track";
import { MAP_STYLES, DEFAULT_STYLE, type MapStyle } from "@/lib/map-styles";
import { CITIES, type City } from "@/lib/cities";
import { AIRPORTS, findByIata, airportToCity } from "@/lib/airports";
import { useMergedTrails } from "@/hooks/use-merged-trails";
import { useFlightMonitors } from "@/hooks/use-flight-monitors";
import type { MapStyle } from "@/lib/map-styles";
import type { City } from "@/lib/cities";
import {
fetchFlightByIcao24,
fetchFlightByCallsign,
type FlightState,
} from "@/lib/opensky";
import { snapLngToReference, unwrapLngPath } from "@/lib/geo";
import { formatCallsign } from "@/lib/flight-utils";
import type { PickingInfo } from "@deck.gl/core";
import { Github, Star, Keyboard } from "lucide-react";
const DEFAULT_CITY_ID = "sfo";
const STYLE_STORAGE_KEY = "aeris:mapStyle";
const DEFAULT_CITY = CITIES.find((c) => c.id === DEFAULT_CITY_ID) ?? CITIES[0];
const GITHUB_REPO_URL = "https://github.com/kewonit/aeris";
const GITHUB_REPO_API = "https://api.github.com/repos/kewonit/aeris";
const HIGH_TRAFFIC_IATA = [
"ATL",
"DXB",
"LHR",
"HND",
"DFW",
"DEN",
"IST",
"LAX",
"CDG",
"AMS",
"FRA",
"MAD",
"JFK",
"SIN",
"ORD",
"SFO",
"MIA",
"LAS",
"MUC",
"CLT",
] as const;
const HUB_PICK_PROBABILITY = 0.75;
const HIGH_TRAFFIC_IATA_SET = new Set<string>(HIGH_TRAFFIC_IATA);
const HIGH_TRAFFIC_AIRPORTS = AIRPORTS.filter((airport) =>
HIGH_TRAFFIC_IATA_SET.has(airport.iata.toUpperCase()),
);
const ICAO24_REGEX = /^[0-9a-f]{6}$/i;
const subscribeNoop = () => () => {};
let _cachedInitialCity: City | null = null;
function resolveInitialCity(): City {
if (_cachedInitialCity) return _cachedInitialCity;
try {
const params = new URLSearchParams(window.location.search);
const code = params.get("city")?.trim().toUpperCase();
if (!code) {
_cachedInitialCity = DEFAULT_CITY;
return DEFAULT_CITY;
}
const preset = CITIES.find(
(c) => c.iata.toUpperCase() === code || c.id === code.toLowerCase(),
);
if (preset) {
_cachedInitialCity = preset;
return preset;
}
const airport = findByIata(code);
if (airport) {
_cachedInitialCity = airportToCity(airport);
return _cachedInitialCity;
}
_cachedInitialCity = DEFAULT_CITY;
return DEFAULT_CITY;
} catch {
_cachedInitialCity = DEFAULT_CITY;
return DEFAULT_CITY;
}
}
function syncCityToUrl(city: City): void {
if (typeof window === "undefined") return;
try {
const url = new URL(window.location.href);
url.searchParams.set("city", city.iata);
url.searchParams.delete("from");
url.searchParams.delete("to");
url.searchParams.delete("fpv");
window.history.replaceState(null, "", url.toString());
} catch {
/* ignore */
}
}
function syncFpvToUrl(icao24: string | null, activeCity?: City): void {
if (typeof window === "undefined") return;
try {
const url = new URL(window.location.href);
if (icao24) {
url.searchParams.set("fpv", icao24);
url.searchParams.delete("city");
url.searchParams.delete("from");
url.searchParams.delete("to");
} else {
url.searchParams.delete("fpv");
if (activeCity) {
url.searchParams.set("city", activeCity.iata);
}
}
window.history.replaceState(null, "", url.toString());
} catch {
/* ignore */
}
}
function resolveInitialFpv(): string | null {
try {
const params = new URLSearchParams(window.location.search);
const raw = params.get("fpv")?.trim().toLowerCase();
return raw && /^[0-9a-f]{6}$/.test(raw) ? raw : null;
} catch {
return null;
}
}
function loadMapStyle(): MapStyle {
try {
const id = localStorage.getItem(STYLE_STORAGE_KEY);
if (!id) return DEFAULT_STYLE;
return MAP_STYLES.find((s) => s.id === id) ?? DEFAULT_STYLE;
} catch {
return DEFAULT_STYLE;
}
}
function saveMapStyle(style: MapStyle): void {
if (typeof window === "undefined") return;
try {
localStorage.setItem(STYLE_STORAGE_KEY, style.id);
} catch {
/* blocked */
}
}
function chooseRandom<T>(items: readonly T[]): T | null {
if (items.length === 0) return null;
return items[Math.floor(Math.random() * items.length)] ?? null;
}
function pickRandomAirportCity(excludeIata?: string): City {
const exclude = excludeIata?.toUpperCase();
const filteredHubs = exclude
? HIGH_TRAFFIC_AIRPORTS.filter(
(airport) => airport.iata.toUpperCase() !== exclude,
)
: HIGH_TRAFFIC_AIRPORTS;
const filteredAirports = exclude
? AIRPORTS.filter((airport) => airport.iata.toUpperCase() !== exclude)
: AIRPORTS;
const useHubs =
filteredHubs.length > 0 && Math.random() < HUB_PICK_PROBABILITY;
const source = useHubs ? filteredHubs : filteredAirports;
const randomAirport = chooseRandom(source);
if (!randomAirport) return DEFAULT_CITY;
return airportToCity(randomAirport);
}
function cityFromFlight(flight: FlightState): City | null {
if (flight.longitude == null || flight.latitude == null) return null;
const code = flight.icao24.toUpperCase();
return {
id: `trk-${flight.icao24}`,
name: `Flight ${code}`,
country: flight.originCountry || "Unknown",
iata: code.slice(0, 3),
coordinates: [flight.longitude, flight.latitude],
radius: 2,
};
}
import { Github, Star } from "lucide-react";
import {
DEFAULT_CITY,
DEFAULT_STYLE,
GITHUB_REPO_URL,
ICAO24_REGEX,
subscribeNoop,
resolveInitialCity,
syncCityToUrl,
syncFpvToUrl,
resolveInitialFpv,
loadMapStyle,
saveMapStyle,
formatStarCount,
} from "@/components/flight-tracker-utils";
import {
pickRandomAirportCity,
cityFromFlight,
} from "@/components/flight-tracker-random";
function FlightTrackerInner() {
const hydratedCity = useSyncExternalStore(
@ -228,8 +72,6 @@ function FlightTrackerInner() {
const [cityOverride, setCityOverride] = useState<City | undefined>();
const [styleOverride, setStyleOverride] = useState<MapStyle | undefined>();
const [selectedIcao24, setSelectedIcao24] = useState<string | null>(null);
const [showHelp, setShowHelp] = useState(false);
const [repoStars, setRepoStars] = useState<number | null>(null);
const [followIcao24, setFollowIcao24] = useState<string | null>(null);
const [fpvIcao24, setFpvIcao24] = useState<string | null>(null);
@ -263,6 +105,7 @@ function FlightTrackerInner() {
setStyleOverride(style);
saveMapStyle(style);
}, []);
const { flights, loading, rateLimited, retryIn } = useFlights(
activeCity,
fpvIcao24,
@ -272,7 +115,6 @@ function FlightTrackerInner() {
const displayFlights = flights;
const displayTrails = useTrailHistory(displayFlights);
// Fetch /tracks only for explicit click-selection (never FPV).
const selectedFlightForTrack = useMemo(() => {
if (!selectedIcao24) return null;
return displayFlights.find((f) => f.icao24 === selectedIcao24) ?? null;
@ -288,250 +130,13 @@ function FlightTrackerInner() {
enabled: shouldFetchSelectedTrack,
});
const mergedTrails = useMemo(() => {
if (!selectedIcao24 || !selectedTrack) return displayTrails;
const flight =
displayFlights.find((f) => f.icao24 === selectedIcao24) ?? null;
const livePos: [number, number] | null =
flight && flight.longitude != null && flight.latitude != null
? [flight.longitude, flight.latitude]
: null;
const trackPositions: [number, number][] = [];
const trackAltitudes: Array<number | null> = [];
for (const p of selectedTrack.path) {
if (p.longitude == null || p.latitude == null) continue;
trackPositions.push([p.longitude, p.latitude]);
trackAltitudes.push(p.baroAltitude ?? null);
}
// Unwrap longitudes to avoid dateline/world-wrap glitches.
if (trackPositions.length >= 2) {
const unwrapped = unwrapLngPath(trackPositions);
trackPositions.splice(0, trackPositions.length, ...unwrapped);
}
const livePosAdjusted: [number, number] | null =
livePos && trackPositions.length > 0
? [
snapLngToReference(
livePos[0],
trackPositions[trackPositions.length - 1][0],
),
livePos[1],
]
: livePos;
const lastWaypointTime =
selectedTrack.path[selectedTrack.path.length - 1]?.time;
const nowSec =
selectedTrackFetchedAtMs > 0
? Math.floor(selectedTrackFetchedAtMs / 1000)
: 0;
const lastWaypointAgeSec =
typeof lastWaypointTime === "number" && Number.isFinite(lastWaypointTime)
? Math.max(0, nowSec - lastWaypointTime)
: 0;
const speedMps =
flight && Number.isFinite(flight.velocity) && flight.velocity! > 30
? Math.max(0, flight.velocity!)
: 140;
const expectedDeg = (speedMps * lastWaypointAgeSec) / 111_320;
// Guard against wrong tracks (tolerate sparse/laggy waypoints).
if (livePosAdjusted && trackPositions.length >= 2) {
const searchWindow = 70;
const start = Math.max(0, trackPositions.length - searchWindow);
let bestDistSq = Number.POSITIVE_INFINITY;
for (let i = start; i < trackPositions.length; i++) {
const p = trackPositions[i];
const dx = p[0] - livePosAdjusted[0];
const dy = p[1] - livePosAdjusted[1];
const d2 = dx * dx + dy * dy;
if (d2 < bestDistSq) bestDistSq = d2;
}
// Tracks can be sparse; scale tolerance by speed and waypoint age.
const lowAltitude =
flight && Number.isFinite(flight.baroAltitude)
? flight.baroAltitude! < 6_000
: false;
const maxAllowedDeg = Math.min(
lowAltitude ? 2.8 : 6,
Math.max(lowAltitude ? 0.75 : 0.9, expectedDeg * 1.35 + 0.22),
);
if (bestDistSq > maxAllowedDeg * maxAllowedDeg) {
return displayTrails;
}
}
// Merge the high-frequency live tail for recent turns.
const existingTrail =
displayTrails.find((t) => t.icao24 === selectedIcao24) ?? null;
if (existingTrail && existingTrail.path.length >= 2) {
const tailCount = 18;
const start = Math.max(0, existingTrail.path.length - tailCount);
const rawTailPath = existingTrail.path.slice(start);
const tailAlt = existingTrail.altitudes.slice(start);
// Unwrap tail points to be continuous with the historical track.
const tailPath: [number, number][] = [];
let refLng =
trackPositions.length > 0
? trackPositions[trackPositions.length - 1][0]
: rawTailPath[0][0];
for (const [lng, lat] of rawTailPath) {
const nextLng = snapLngToReference(lng, refLng);
tailPath.push([nextLng, lat]);
refLng = nextLng;
}
// Merge where the two data sources overlap near the end.
const MERGE_SNAP_DEG = 0.06;
const CONNECT_BRIDGE_DEG = 0.07;
const MAX_CONNECT_GAP_DEG =
flight &&
Number.isFinite(flight.baroAltitude) &&
flight.baroAltitude! < 6_000
? 1.25
: 3.5;
const firstTail = tailPath[0];
const searchWindow = 70;
const searchStart = Math.max(0, trackPositions.length - searchWindow);
let bestIndex = -1;
let bestDistSq = Number.POSITIVE_INFINITY;
for (let i = searchStart; i < trackPositions.length; i++) {
const p = trackPositions[i];
const dx = p[0] - firstTail[0];
const dy = p[1] - firstTail[1];
const d2 = dx * dx + dy * dy;
if (d2 < bestDistSq) {
bestDistSq = d2;
bestIndex = i;
}
}
if (bestIndex >= 0 && bestDistSq <= MERGE_SNAP_DEG * MERGE_SNAP_DEG) {
// Snap to overlap, then append the live tail.
trackPositions.splice(bestIndex + 1);
trackAltitudes.splice(bestIndex + 1);
const join = trackPositions[trackPositions.length - 1];
if (join) {
tailPath[0] = join;
const joinAlt = trackAltitudes[trackAltitudes.length - 1] ?? null;
tailAlt[0] = joinAlt ?? tailAlt[0] ?? null;
}
} else {
// No overlap: disconnect stale history or insert a short bridge when close.
const last = trackPositions[trackPositions.length - 1];
const lastAlt = trackAltitudes[trackAltitudes.length - 1] ?? null;
if (last) {
const dx = last[0] - firstTail[0];
const dy = last[1] - firstTail[1];
const gap = Math.sqrt(dx * dx + dy * dy);
const shouldDisconnect =
gap > 0.25 ||
(lastWaypointAgeSec > 900 && gap > 0.06) ||
(lastWaypointAgeSec > 300 && gap > 0.1);
if (shouldDisconnect) {
trackPositions.splice(0, trackPositions.length, ...tailPath);
trackAltitudes.splice(0, trackAltitudes.length, ...tailAlt);
tailPath.length = 0;
tailAlt.length = 0;
} else {
if (gap > MAX_CONNECT_GAP_DEG) {
tailPath.length = 0;
} else if (gap > CONNECT_BRIDGE_DEG) {
const steps = Math.max(6, Math.min(24, Math.ceil(gap / 0.15)));
const firstTailAlt = tailAlt[0] ?? null;
for (let s = 1; s < steps; s++) {
const t = s / steps;
trackPositions.push([
last[0] + (firstTail[0] - last[0]) * t,
last[1] + (firstTail[1] - last[1]) * t,
]);
if (lastAlt == null && firstTailAlt == null) {
trackAltitudes.push(null);
} else {
const a0 = lastAlt ?? firstTailAlt ?? 0;
const a1 = firstTailAlt ?? lastAlt ?? a0;
trackAltitudes.push(a0 + (a1 - a0) * t);
}
}
} else {
tailPath[0] = last;
tailAlt[0] = lastAlt ?? tailAlt[0] ?? null;
}
}
}
}
// Append tail points, skipping consecutive duplicates.
for (let i = 0; i < tailPath.length; i++) {
const pos = tailPath[i];
const alt = tailAlt[i] ?? null;
const last = trackPositions[trackPositions.length - 1];
if (last && last[0] === pos[0] && last[1] === pos[1]) continue;
trackPositions.push(pos);
trackAltitudes.push(alt);
}
}
// Ensure the trail reaches the aircraft.
if (livePosAdjusted) {
const last = trackPositions[trackPositions.length - 1];
if (
!last ||
last[0] !== livePosAdjusted[0] ||
last[1] !== livePosAdjusted[1]
) {
trackPositions.push(livePosAdjusted);
trackAltitudes.push(flight?.baroAltitude ?? null);
}
}
if (trackPositions.length < 2) return displayTrails;
const out = displayTrails.map((t) => {
if (t.icao24 !== selectedIcao24) return t;
const baroAltitude =
trackAltitudes[trackAltitudes.length - 1] ?? t.baroAltitude ?? null;
return {
...t,
path: trackPositions,
altitudes: trackAltitudes,
baroAltitude,
fullHistory: true,
};
});
// If the selected aircraft didn't have an in-memory trail yet, add one.
if (!out.some((t) => t.icao24 === selectedIcao24)) {
out.push({
icao24: selectedIcao24,
path: trackPositions,
altitudes: trackAltitudes,
baroAltitude: trackAltitudes[trackAltitudes.length - 1] ?? null,
fullHistory: true,
});
}
return out;
}, [
const mergedTrails = useMergedTrails(
selectedIcao24,
selectedTrack,
selectedTrackFetchedAtMs,
displayTrails,
displayFlights,
]);
);
const selectedFlight = useMemo(() => {
if (!selectedIcao24) return null;
@ -560,166 +165,27 @@ function FlightTrackerInner() {
syncFpvToUrl(fpvIcao24, activeCity);
}, [fpvIcao24, activeCity]);
const fpvLookupDoneRef = useRef(false);
useEffect(() => {
const pending = pendingFpvRef.current;
if (!pending || fpvIcao24) return;
const match = displayFlights.find(
(f) => f.icao24.toLowerCase() === pending,
);
if (match && match.longitude != null && match.latitude != null) {
if (match.onGround) {
pendingFpvRef.current = null;
syncFpvToUrl(null, activeCity);
setSelectedIcao24(match.icao24);
return;
}
pendingFpvRef.current = null;
fpvLookupDoneRef.current = false;
setFpvSeedCenter({ lng: match.longitude, lat: match.latitude });
setFpvIcao24(pending);
setFollowIcao24(null);
return;
}
if (!fpvLookupDoneRef.current && displayFlights.length > 0) {
fpvLookupDoneRef.current = true;
const controller = new AbortController();
fetchFlightByIcao24(pending, controller.signal)
.then((result) => {
if (
result.flight &&
result.flight.longitude != null &&
result.flight.latitude != null &&
!result.flight.onGround &&
pendingFpvRef.current === pending
) {
const focusCity = cityFromFlight(result.flight);
if (focusCity) {
setCityOverride(focusCity);
}
setFpvSeedCenter({
lng: result.flight.longitude,
lat: result.flight.latitude,
});
pendingFpvRef.current = null;
setFpvIcao24(pending);
setFollowIcao24(null);
} else if (pendingFpvRef.current === pending) {
pendingFpvRef.current = null;
syncFpvToUrl(null, activeCity);
if (result.flight) {
setSelectedIcao24(result.flight.icao24);
}
}
})
.catch(() => {
if (pendingFpvRef.current === pending) {
pendingFpvRef.current = null;
}
});
return () => controller.abort();
}
}, [displayFlights, fpvIcao24, activeCity]);
const { repoStars } = useFlightMonitors({
pendingFpvRef,
fpvIcao24,
fpvFlight,
followIcao24,
followFlight,
selectedIcao24,
selectedFlight,
displayFlights,
activeCity,
rateLimited,
setSelectedIcao24,
setFpvIcao24,
setFollowIcao24,
setCityOverride,
setFpvSeedCenter,
});
const fpvFlightOrCached = fpvFlight;
const fpvMissCountRef = useRef(0);
useEffect(() => {
if (!fpvIcao24) {
fpvMissCountRef.current = 0;
return;
}
if (fpvFlight) {
fpvMissCountRef.current = 0;
if (fpvFlight.onGround) {
const exitIcao = fpvIcao24;
const timer = setTimeout(() => {
setSelectedIcao24(exitIcao);
setFpvIcao24(null);
}, 0);
return () => clearTimeout(timer);
}
} else {
if (!rateLimited) {
fpvMissCountRef.current += 1;
}
if (fpvMissCountRef.current >= 3) {
const exitIcao = fpvIcao24;
const timer = setTimeout(() => {
setSelectedIcao24(exitIcao);
setFpvIcao24(null);
}, 0);
return () => clearTimeout(timer);
}
}
}, [fpvIcao24, fpvFlight, rateLimited]);
const followMissCountRef = useRef(0);
useEffect(() => {
if (!followIcao24) {
followMissCountRef.current = 0;
return;
}
if (followFlight) {
followMissCountRef.current = 0;
} else {
followMissCountRef.current += 1;
if (followMissCountRef.current >= 3) {
const timer = setTimeout(() => setFollowIcao24(null), 0);
return () => clearTimeout(timer);
}
}
}, [followIcao24, followFlight]);
const displayFlight = selectedFlight;
const missingSinceRef = useRef<number | null>(null);
useEffect(() => {
if (!selectedIcao24) {
missingSinceRef.current = null;
return;
}
if (selectedFlight) {
missingSinceRef.current = null;
return;
}
const now = Date.now();
if (missingSinceRef.current == null) {
missingSinceRef.current = now;
return;
}
if (now - missingSinceRef.current >= 60_000) {
const timer = setTimeout(() => setSelectedIcao24(null), 0);
missingSinceRef.current = null;
return () => clearTimeout(timer);
}
}, [selectedIcao24, selectedFlight, displayFlights]);
useEffect(() => {
let mounted = true;
async function loadRepoStars() {
try {
const res = await fetch(GITHUB_REPO_API, { cache: "no-store" });
if (!res.ok) return;
const data = (await res.json()) as { stargazers_count?: number };
if (mounted && typeof data.stargazers_count === "number") {
setRepoStars(data.stargazers_count);
}
} catch {
/* silent fallback */
}
}
loadRepoStars();
return () => {
mounted = false;
};
}, []);
const handleClick = useCallback(
(info: PickingInfo<FlightState> | null) => {
if (fpvIcao24) return;
@ -796,7 +262,7 @@ function FlightTrackerInner() {
}, []);
const handleToggleHelp = useCallback(() => {
setShowHelp((prev) => !prev);
window.dispatchEvent(new CustomEvent("aeris:open-shortcuts"));
}, []);
const handleToggleFpvKey = useCallback(() => {
@ -885,7 +351,12 @@ function FlightTrackerInner() {
return (
<main className="relative h-dvh w-screen overflow-hidden bg-black">
<MapView mapStyle={mapStyle.style} isDark={mapStyle.dark}>
<MapView
mapStyle={mapStyle.style}
terrainProfile={mapStyle.terrainProfile}
isDark={mapStyle.dark}
globeMode={settings.globeMode}
>
<CameraController
city={activeCity}
followFlight={followFlight}
@ -907,6 +378,7 @@ function FlightTrackerInner() {
trailDistance={settings.trailDistance}
showShadows={settings.showShadows}
showAltitudeColors={settings.showAltitudeColors}
globeMode={settings.globeMode}
fpvIcao24={fpvIcao24}
fpvPositionRef={fpvPositionRef}
/>
@ -937,22 +409,6 @@ function FlightTrackerInner() {
{!fpvIcao24 && (
<div className="pointer-events-auto absolute right-3 top-3 flex items-center gap-1.5 sm:right-4 sm:top-4 sm:gap-2">
<motion.button
onClick={handleToggleHelp}
className="hidden h-9 w-9 items-center justify-center rounded-xl backdrop-blur-2xl transition-colors sm:flex"
style={{
borderWidth: 1,
borderColor: "rgb(var(--ui-fg) / 0.06)",
backgroundColor: "rgb(var(--ui-fg) / 0.03)",
color: "rgb(var(--ui-fg) / 0.5)",
}}
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
aria-label="Keyboard shortcuts"
title="Keyboard shortcuts (?)"
>
<Keyboard className="h-4 w-4" />
</motion.button>
<a
href={GITHUB_REPO_URL}
target="_blank"
@ -1016,21 +472,20 @@ function FlightTrackerInner() {
)}
{!fpvIcao24 && (
<div className="pointer-events-auto absolute bottom-[env(safe-area-inset-bottom,0px)] right-3 mb-3 flex flex-col items-end gap-2 sm:bottom-4 sm:right-4 sm:mb-0">
<CameraControls />
<AltitudeLegend />
<MapAttribution styleId={mapStyle.id} />
<div className="pointer-events-none absolute bottom-[env(safe-area-inset-bottom,0px)] right-3 mb-3 flex flex-col items-end gap-2 sm:bottom-4 sm:right-4 sm:mb-0">
<div className="pointer-events-auto">
<CameraControls />
</div>
<div className="pointer-events-auto">
<AltitudeLegend />
</div>
<div className="pointer-events-auto">
<MapAttribution styleId={mapStyle.id} />
</div>
</div>
)}
</div>
{!fpvIcao24 && (
<KeyboardShortcutsHelp
open={showHelp}
onClose={() => setShowHelp(false)}
/>
)}
<AnimatePresence>
{fpvIcao24 && fpvFlightOrCached && (
<FpvHud flight={fpvFlightOrCached} onExit={handleExitFpv} />
@ -1061,9 +516,3 @@ function Brand({ isDark }: { isDark: boolean }) {
</span>
);
}
function formatStarCount(value: number): string {
if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}m`;
if (value >= 1_000) return `${(value / 1_000).toFixed(1)}k`;
return `${value}`;
}

View File

@ -0,0 +1,234 @@
// ── Category Styling ───────────────────────────────────────────────────
export const CATEGORY_TINT: Record<number, [number, number, number]> = {
2: [100, 235, 180],
3: [120, 225, 235],
4: [255, 210, 120],
5: [255, 185, 110],
6: [255, 160, 120],
7: [255, 120, 200],
8: [140, 220, 160],
9: [170, 210, 255],
10: [220, 170, 255],
11: [255, 150, 180],
12: [180, 230, 160],
14: [195, 165, 255],
};
export function categorySizeMultiplier(category: number | null): number {
switch (category) {
case 2:
return 0.88;
case 3:
return 0.96;
case 4:
return 1.08;
case 5:
return 1.18;
case 6:
return 1.28;
case 7:
return 1.04;
case 8:
return 0.86;
case 9:
case 12:
return 0.8;
case 10:
return 1.15;
case 14:
return 0.72;
default:
return 1;
}
}
export function tintAircraftColor(
base: [number, number, number, number],
category: number | null,
): [number, number, number, number] {
const tint = category !== null ? CATEGORY_TINT[category] : undefined;
if (!tint) return base;
return [
Math.round(base[0] * 0.58 + tint[0] * 0.42),
Math.round(base[1] * 0.58 + tint[1] * 0.42),
Math.round(base[2] * 0.58 + tint[2] * 0.42),
base[3],
];
}
// ── Selection pulse timing ─────────────────────────────────────────────
export const PULSE_PERIOD_MS = 7000;
export const RING_PERIOD_MS = 5500;
// ── Canvas Atlas Generators ────────────────────────────────────────────
export function createHaloAtlas(): HTMLCanvasElement {
const size = 256;
const canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext("2d")!;
ctx.clearRect(0, 0, size, size);
const c = size / 2;
for (let r = 0; r < c; r++) {
const norm = r / c;
let alpha = 0;
if (norm < 0.18) {
alpha = 0;
} else if (norm < 0.35) {
const t = (norm - 0.18) / 0.17;
alpha = t * t * 0.7;
} else if (norm < 0.55) {
alpha = 0.7 - ((norm - 0.35) / 0.2) * 0.3;
} else {
const t = (norm - 0.55) / 0.45;
alpha = 0.4 * (1 - t) * (1 - t);
}
if (alpha < 0.003) continue;
ctx.strokeStyle = `rgba(255,255,255,${alpha})`;
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.arc(c, c, r, 0, Math.PI * 2);
ctx.stroke();
}
return canvas;
}
export function createSoftRingAtlas(): HTMLCanvasElement {
const size = 256;
const canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext("2d")!;
ctx.clearRect(0, 0, size, size);
const c = size / 2;
const ringCenter = c * 0.75;
const ringWidth = c * 0.18;
for (let r = 0; r < c; r++) {
const dist = Math.abs(r - ringCenter);
const falloff = Math.max(0, 1 - (dist / ringWidth) ** 2);
const alpha = falloff * 0.85;
if (alpha < 0.005) continue;
ctx.strokeStyle = `rgba(255,255,255,${alpha})`;
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.arc(c, c, r, 0, Math.PI * 2);
ctx.stroke();
}
return canvas;
}
export function createAircraftAtlas(): HTMLCanvasElement {
const size = 128;
const canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext("2d")!;
ctx.clearRect(0, 0, size, size);
ctx.fillStyle = "#ffffff";
ctx.beginPath();
ctx.moveTo(64, 6);
ctx.lineTo(71, 19);
ctx.lineTo(71, 33);
ctx.lineTo(100, 44);
ctx.lineTo(106, 52);
ctx.lineTo(80, 53);
ctx.lineTo(72, 56);
ctx.lineTo(72, 88);
ctx.lineTo(90, 101);
ctx.lineTo(88, 108);
ctx.lineTo(69, 99);
ctx.lineTo(69, 121);
ctx.lineTo(64, 126);
ctx.lineTo(59, 121);
ctx.lineTo(59, 99);
ctx.lineTo(40, 108);
ctx.lineTo(38, 101);
ctx.lineTo(56, 88);
ctx.lineTo(56, 56);
ctx.lineTo(48, 53);
ctx.lineTo(22, 52);
ctx.lineTo(28, 44);
ctx.lineTo(57, 33);
ctx.lineTo(57, 19);
ctx.closePath();
ctx.fill();
ctx.globalCompositeOperation = "destination-out";
ctx.beginPath();
ctx.moveTo(64, 13);
ctx.lineTo(67, 19);
ctx.lineTo(64, 24);
ctx.lineTo(61, 19);
ctx.closePath();
ctx.fill();
ctx.globalCompositeOperation = "source-over";
return canvas;
}
// ── Icon Mappings ──────────────────────────────────────────────────────
export const HALO_MAPPING = {
halo: {
x: 0,
y: 0,
width: 256,
height: 256,
anchorX: 128,
anchorY: 128,
mask: true,
},
};
export const RING_MAPPING = {
ring: {
x: 0,
y: 0,
width: 256,
height: 256,
anchorX: 128,
anchorY: 128,
mask: true,
},
};
export const AIRCRAFT_ICON_MAPPING = {
aircraft: {
x: 0,
y: 0,
width: 128,
height: 128,
anchorX: 64,
anchorY: 64,
mask: true,
},
};
// ── Cached Atlas Data URLs ─────────────────────────────────────────────
let _haloCache: string | undefined;
export function getHaloUrl(): string {
if (typeof document === "undefined") return "";
if (!_haloCache) _haloCache = createHaloAtlas().toDataURL();
return _haloCache;
}
let _ringCache: string | undefined;
export function getRingUrl(): string {
if (typeof document === "undefined") return "";
if (!_ringCache) _ringCache = createSoftRingAtlas().toDataURL();
return _ringCache;
}
let _atlasCache: string | undefined;
export function getAircraftAtlasUrl(): string {
if (typeof document === "undefined") return "";
if (!_atlasCache) _atlasCache = createAircraftAtlas().toDataURL();
return _atlasCache;
}

View File

@ -1,5 +1,4 @@
import type maplibregl from "maplibre-gl";
import { MercatorCoordinate } from "maplibre-gl";
import maplibregl from "maplibre-gl";
export const FPV_DISTANCE_ZOOM_OFFSET = 1.1;
@ -32,42 +31,76 @@ export function fpvZoomForAltitude(altMeters: number): number {
return Math.max(10.1, Math.min(16.2, zoom));
}
/**
* Project a geographic position at a given elevation to a screenspace
* pixel offset from the map's visual centre.
*
* Uses MapLibre's internal transform.locationToScreenPoint with a synthetic
* terrain provider so the correct projection (Globe, Mercator, or the
* automatic transition between them) handles elevation natively.
*
* There is no public MapLibre API for elevation-aware screen projection
* (map.project() is 2D only). This internal access is tested against
* MapLibre GL JS v5.18.x. A public-API fallback (without elevation) is
* provided for resilience against future internal refactors.
*/
export function projectLngLatElevationPixelDelta(
map: maplibregl.Map,
lng: number,
lat: number,
elevationMeters: number,
): { dx: number; dy: number } | null {
type Transform3DLike = {
_pixelMatrix3D?: unknown;
centerPoint?: { x: number; y: number };
coordinatePoint: (
coord: MercatorCoordinate,
elevation: number,
pixelMatrix3D: unknown,
) => { x: number; y: number } | null;
// MapLibre's transform has separate Globe and Mercator implementations of
// locationToScreenPoint(lnglat, terrain). Both support elevation when a
// terrain-like provider is supplied:
// Mercator: coordinatePoint(coord, elevation, _pixelMatrix3D)
// Globe: scales surface point by (1 + elevation/earthRadius), then projects
// By providing a duck-typed provider that returns our altitude, we get
// elevation-aware projection in every mode without touching internals.
type TransformLike = {
locationToScreenPoint: (
lnglat: maplibregl.LngLat,
terrain: unknown,
) => { x: number; y: number };
};
const tr = (map as unknown as { transform?: Transform3DLike }).transform;
if (!tr || typeof tr.coordinatePoint !== "function") return null;
const tr = (map as unknown as { transform?: TransformLike }).transform;
const pixelMatrix3D = tr._pixelMatrix3D;
const centerPoint = tr.centerPoint;
if (!pixelMatrix3D || !centerPoint) return null;
const canvas = map.getCanvas();
const cx = canvas.clientWidth / 2;
const cy = canvas.clientHeight / 2;
let p: { x: number; y: number } | null = null;
try {
p = tr.coordinatePoint(
MercatorCoordinate.fromLngLat({ lng, lat }),
elevationMeters,
pixelMatrix3D,
);
} catch {
return null;
// Try elevation-aware internal API first
if (tr && typeof tr.locationToScreenPoint === "function") {
const fakeTerrain = {
getElevationForLngLat: () => elevationMeters,
getElevationForLngLatZoom: () => elevationMeters,
};
try {
const lnglat = new maplibregl.LngLat(lng, lat);
const screenPt = tr.locationToScreenPoint(lnglat, fakeTerrain);
if (Number.isFinite(screenPt.x) && Number.isFinite(screenPt.y)) {
return { dx: screenPt.x - cx, dy: screenPt.y - cy };
}
} catch {
// Point may be behind the globe horizon — fall through to public API
}
}
if (!p || !Number.isFinite(p.x) || !Number.isFinite(p.y)) return null;
return { dx: p.x - centerPoint.x, dy: p.y - centerPoint.y };
// Fallback: public map.project() without elevation awareness.
// This gives correct 2D placement but ignores altitude offset.
try {
const projected = map.project(new maplibregl.LngLat(lng, lat));
if (Number.isFinite(projected.x) && Number.isFinite(projected.y)) {
return { dx: projected.x - cx, dy: projected.y - cy };
}
} catch {
// Point may be behind the globe horizon
}
return null;
}
export function setMapInteractionsEnabled(

View File

@ -2,22 +2,14 @@
import { useEffect, useRef, type MutableRefObject } from "react";
import { useMap } from "./map";
import {
FPV_DISTANCE_ZOOM_OFFSET,
fpvZoomForAltitude,
lerp,
lerpLng,
normalizeLng,
projectLngLatElevationPixelDelta,
setMapInteractionsEnabled,
smoothstep,
} from "./camera-controller-utils";
import { smoothstep } from "./camera-controller-utils";
import { useSettings } from "@/hooks/use-settings";
import type { City } from "@/lib/cities";
import type { FlightState } from "@/lib/opensky";
import { useFpvCamera } from "./use-fpv-camera";
import { useKeyboardCamera } from "./use-keyboard-camera";
import { useOrbitCamera } from "./use-orbit-camera";
const IDLE_TIMEOUT_MS = 5_000;
const ORBIT_EASE_IN_MS = 2000;
const DEFAULT_ZOOM = 9.2;
const DEFAULT_PITCH = 49;
const DEFAULT_BEARING = 27.4;
@ -25,29 +17,6 @@ const FOLLOW_ZOOM = 10.5;
const FOLLOW_PITCH = 55;
const FOLLOW_EASE_MS = 1200;
const FPV_FLY_DURATION = 1600;
const FPV_PITCH = 65;
const FPV_CENTER_ALPHA = 0.16;
const FPV_BEARING_ALPHA = 0.1;
const FPV_ZOOM_ALPHA = 0.06;
const FPV_IDLE_RECENTER_MS = 1200;
const FPV_EASE_IN_MS = 600;
const CAMERA_ACCEL = 2.5;
const CAMERA_DECEL = 4.0;
const ZOOM_SPEED = 1.2;
const PITCH_SPEED = 28;
const BEARING_SPEED = 55;
const MINIMUM_IMPULSE_DURATION_MS = 180;
type CameraActionType = "zoom" | "pitch" | "bearing";
type ActionState = {
direction: number;
velocity: number;
held: boolean;
impulseEnd: number;
};
type FpvPosition = { lng: number; lat: number; alt: number; track: number };
export function CameraController({
@ -82,6 +51,7 @@ export function CameraController({
fpvFlightRef.current = fpvFlight;
}, [fpvFlight]);
// City flyTo
useEffect(() => {
if (!map || !isLoaded || !city) return;
if (city.id === prevCityRef.current) return;
@ -97,6 +67,7 @@ export function CameraController({
});
}, [map, isLoaded, city]);
// Follow flight init
useEffect(() => {
if (!map || !isLoaded) return;
@ -128,6 +99,7 @@ export function CameraController({
});
}, [map, isLoaded, followFlight]);
// Follow flight continuous update
useEffect(() => {
if (!map || !isLoaded || !followFlight) return;
if (followFlight.longitude == null || followFlight.latitude == null) return;
@ -151,251 +123,46 @@ export function CameraController({
followFlight?.trueTrack,
]);
useEffect(() => {
if (!map || !isLoaded) {
if (isFpvActiveRef.current) {
isFpvActiveRef.current = false;
}
return;
}
const fpv = fpvFlightRef.current;
const fpvKey = fpv?.icao24 ?? null;
if (fpvKey === prevFpvRef.current) return;
const wasFpv = prevFpvRef.current !== null;
prevFpvRef.current = fpvKey;
if (!fpv || fpv.longitude == null || fpv.latitude == null) {
isFpvActiveRef.current = false;
if (wasFpv) {
setMapInteractionsEnabled(map, true);
}
if (wasFpv) {
map.flyTo({
center: city.coordinates,
zoom: DEFAULT_ZOOM,
pitch: DEFAULT_PITCH,
bearing: DEFAULT_BEARING,
duration: 1800,
essential: true,
});
}
return;
}
isFpvActiveRef.current = true;
setMapInteractionsEnabled(map, true);
const bearing = Number.isFinite(fpv.trueTrack)
? fpv.trueTrack!
: map.getBearing();
const safeAltitude = Number.isFinite(fpv.baroAltitude)
? fpv.baroAltitude!
: 5000;
const zoom = fpvZoomForAltitude(safeAltitude) - FPV_DISTANCE_ZOOM_OFFSET;
let fpvOffsetX = 0;
let fpvOffsetY = 0;
map.flyTo({
center: [normalizeLng(fpv.longitude), fpv.latitude],
zoom,
pitch: FPV_PITCH,
bearing,
duration: FPV_FLY_DURATION,
essential: true,
});
let frameId: number | null = null;
let startupTimer: ReturnType<typeof setTimeout> | null = null;
let prevBearing = bearing;
let lastInteractionTime = 0; // 0 = no interaction yet → track immediately
let recenterStartTime = 0;
let programmaticMove = false;
function onUserInteraction() {
if (programmaticMove) return;
lastInteractionTime = performance.now();
recenterStartTime = 0;
}
const onMapInteraction = (e: unknown) => {
if (programmaticMove) return;
const evt = e as { originalEvent?: Event };
if (!evt?.originalEvent) return;
onUserInteraction();
};
const interactionEventTypes = [
"movestart",
"move",
"zoomstart",
"zoom",
"rotatestart",
"rotate",
"pitchstart",
"pitch",
] as const;
for (const t of interactionEventTypes) {
map.on(t, onMapInteraction);
}
function keepInFrame() {
if (!isFpvActiveRef.current || !map) {
frameId = null;
return;
}
const interpPos = fpvPosRef.current?.current ?? null;
const live = fpvFlightRef.current;
const posLng = interpPos?.lng ?? live?.longitude ?? null;
const posLat = interpPos?.lat ?? live?.latitude ?? null;
const posAlt = interpPos?.alt ?? live?.baroAltitude ?? 5000;
const posTrack = interpPos?.track ?? live?.trueTrack ?? null;
if (posLng == null || posLat == null) {
frameId = requestAnimationFrame(keepInFrame);
return;
}
if (
!Number.isFinite(posLng) ||
!Number.isFinite(posLat) ||
Math.abs(posLat) > 90
) {
frameId = requestAnimationFrame(keepInFrame);
return;
}
const now = performance.now();
const idleMs =
lastInteractionTime === 0
? FPV_IDLE_RECENTER_MS + 1
: now - lastInteractionTime;
const isIdle = idleMs > FPV_IDLE_RECENTER_MS;
let trackingStrength = 0;
if (isIdle) {
if (recenterStartTime === 0) {
recenterStartTime = now;
}
const easeElapsed = now - recenterStartTime;
const t = Math.min(easeElapsed / FPV_EASE_IN_MS, 1);
trackingStrength = smoothstep(t);
}
const liveBearing =
posTrack !== null && Number.isFinite(posTrack) ? posTrack : prevBearing;
const bearingDelta = ((liveBearing - prevBearing + 540) % 360) - 180;
prevBearing = prevBearing + bearingDelta * FPV_BEARING_ALPHA;
if (trackingStrength > 0.001) {
const safeAlt = Number.isFinite(posAlt) ? posAlt : 5000;
const targetZoom =
fpvZoomForAltitude(safeAlt) - FPV_DISTANCE_ZOOM_OFFSET;
const currentZoom = map.getZoom();
const zoomAlpha = FPV_ZOOM_ALPHA * trackingStrength;
const smoothZoom = lerp(currentZoom, targetZoom, zoomAlpha);
const currentPitch = map.getPitch();
const targetLng = normalizeLng(posLng);
const targetLat = posLat;
const center = map.getCenter();
const centerAlpha = FPV_CENTER_ALPHA * trackingStrength;
const canvas = map.getCanvas();
const canvasW = Math.max(1, canvas.clientWidth);
const canvasH = Math.max(1, canvas.clientHeight);
const elevationMeters = Math.max(safeAlt * 5, 200);
const deltaPx = projectLngLatElevationPixelDelta(
map,
targetLng,
targetLat,
elevationMeters,
);
if (deltaPx) {
const desiredX = fpvOffsetX - deltaPx.dx;
const desiredY = fpvOffsetY - deltaPx.dy;
const offsetAlpha = 0.08 * trackingStrength;
fpvOffsetX = lerp(fpvOffsetX, desiredX, offsetAlpha);
fpvOffsetY = lerp(fpvOffsetY, desiredY, offsetAlpha);
} else {
const decayAlpha = 0.1 * trackingStrength;
fpvOffsetX = lerp(fpvOffsetX, 0, decayAlpha);
fpvOffsetY = lerp(fpvOffsetY, 0, decayAlpha);
}
const maxScale = Math.min(1.5, Math.max(1, elevationMeters / 15_000));
const maxOffset = 0.45 * maxScale * Math.min(canvasW, canvasH);
fpvOffsetX = Math.max(-maxOffset, Math.min(maxOffset, fpvOffsetX));
fpvOffsetY = Math.max(-maxOffset, Math.min(maxOffset, fpvOffsetY));
const currentBearing = map.getBearing();
const bearingToCurrent =
((prevBearing - currentBearing + 540) % 360) - 180;
const newMapBearing =
currentBearing +
bearingToCurrent * FPV_BEARING_ALPHA * trackingStrength;
const pitchAlpha = 0.05 * trackingStrength;
const newPitch = lerp(currentPitch, FPV_PITCH, pitchAlpha);
programmaticMove = true;
try {
map.easeTo({
center: [
lerpLng(center.lng, targetLng, centerAlpha),
lerp(center.lat, targetLat, centerAlpha),
],
bearing: newMapBearing,
zoom: smoothZoom,
pitch: newPitch,
offset: [fpvOffsetX, fpvOffsetY],
duration: 0,
animate: false,
essential: true,
});
} finally {
programmaticMove = false;
}
}
frameId = requestAnimationFrame(keepInFrame);
}
startupTimer = setTimeout(() => {
startupTimer = null;
frameId = requestAnimationFrame(keepInFrame);
}, FPV_FLY_DURATION + 300);
return () => {
if (startupTimer) clearTimeout(startupTimer);
if (frameId != null) cancelAnimationFrame(frameId);
for (const t of interactionEventTypes) {
map.off(t, onMapInteraction);
}
if (map && isFpvActiveRef.current) {
setMapInteractionsEnabled(map, true);
isFpvActiveRef.current = false;
}
};
}, [map, isLoaded, fpvFlight?.icao24, city]);
// FPV camera hook
useFpvCamera(
map,
isLoaded,
fpvFlight,
city,
fpvFlightRef,
fpvPosRef,
isFpvActiveRef,
prevFpvRef,
);
// North-up & reset-view
useEffect(() => {
if (!map || !isLoaded || !city) return;
let northUpRafId: number | undefined;
const onNorthUp = () => {
if (isFpvActiveRef.current) return;
map.easeTo({
bearing: 0,
duration: 650,
essential: true,
});
if (northUpRafId != null) cancelAnimationFrame(northUpRafId);
const startBearing = map.getBearing();
const delta = ((0 - startBearing + 540) % 360) - 180;
if (Math.abs(delta) < 0.5) {
map.setBearing(0);
return;
}
const duration = 650;
const start = performance.now();
function animateBearing() {
const t = Math.min((performance.now() - start) / duration, 1);
const eased = smoothstep(t);
map!.setBearing(startBearing + delta * eased);
if (t < 1) {
northUpRafId = requestAnimationFrame(animateBearing);
} else {
northUpRafId = undefined;
}
}
northUpRafId = requestAnimationFrame(animateBearing);
};
const onResetView = (event: Event) => {
@ -416,233 +183,33 @@ export function CameraController({
window.addEventListener("aeris:reset-view", onResetView);
return () => {
if (northUpRafId != null) cancelAnimationFrame(northUpRafId);
window.removeEventListener("aeris:north-up", onNorthUp);
window.removeEventListener("aeris:reset-view", onResetView);
};
}, [map, isLoaded, city]);
useEffect(() => {
if (!map || !isLoaded) return;
// Keyboard camera hook
useKeyboardCamera(
map,
isLoaded,
isFpvActiveRef,
isInteractingRef,
idleTimerRef,
);
const actions = new Map<CameraActionType, ActionState>();
let frameId: number | null = null;
let lastTime = 0;
function getOrCreate(
type: CameraActionType,
direction: number,
): ActionState {
let s = actions.get(type);
if (!s) {
s = { direction, velocity: 0, held: false, impulseEnd: 0 };
actions.set(type, s);
}
return s;
}
function maxSpeed(type: CameraActionType): number {
if (type === "zoom") return ZOOM_SPEED;
if (type === "pitch") return PITCH_SPEED;
return BEARING_SPEED;
}
function applyDelta(type: CameraActionType, delta: number) {
if (type === "zoom") {
const z = map!.getZoom() + delta;
map!.setZoom(
Math.min(Math.max(z, map!.getMinZoom()), map!.getMaxZoom()),
);
} else if (type === "pitch") {
const p = map!.getPitch() + delta;
map!.setPitch(Math.min(Math.max(p, 0), map!.getMaxPitch()));
} else {
map!.setBearing(map!.getBearing() + delta);
}
}
function tick(now: number) {
const dt = lastTime ? Math.min((now - lastTime) / 1000, 0.1) : 0.016;
lastTime = now;
let anyActive = false;
for (const [type, state] of actions) {
const wantSpeed = state.held || now < state.impulseEnd;
if (wantSpeed) {
state.velocity = Math.min(
state.velocity + CAMERA_ACCEL * dt * maxSpeed(type),
maxSpeed(type),
);
} else {
state.velocity = Math.max(
state.velocity - CAMERA_DECEL * dt * maxSpeed(type),
0,
);
}
if (state.velocity > 0.001) {
applyDelta(type, state.direction * state.velocity * dt);
anyActive = true;
} else {
state.velocity = 0;
if (!state.held) {
actions.delete(type);
if (type === "bearing") {
isInteractingRef.current = false;
}
}
}
}
frameId = anyActive ? requestAnimationFrame(tick) : null;
}
function ensureLoop() {
if (frameId == null) {
lastTime = 0;
frameId = requestAnimationFrame(tick);
}
}
const onStart = (e: Event) => {
if (isFpvActiveRef.current) return;
const { type, direction } = (e as CustomEvent).detail as {
type: CameraActionType;
direction: number;
};
const state = getOrCreate(type, direction);
state.direction = direction;
state.held = true;
state.impulseEnd = performance.now() + MINIMUM_IMPULSE_DURATION_MS;
if (type === "bearing") {
isInteractingRef.current = true;
if (idleTimerRef.current) clearTimeout(idleTimerRef.current);
}
ensureLoop();
};
const onStop = (e: Event) => {
const { type } = (e as CustomEvent).detail as { type: CameraActionType };
const state = actions.get(type);
if (state) state.held = false;
};
window.addEventListener("aeris:camera-start", onStart);
window.addEventListener("aeris:camera-stop", onStop);
return () => {
window.removeEventListener("aeris:camera-start", onStart);
window.removeEventListener("aeris:camera-stop", onStop);
if (frameId != null) cancelAnimationFrame(frameId);
};
}, [map, isLoaded]);
useEffect(() => {
if (
!map ||
!isLoaded ||
!city ||
!settings.autoOrbit ||
followFlight ||
fpvFlight
) {
if (orbitFrameRef.current) cancelAnimationFrame(orbitFrameRef.current);
if (idleTimerRef.current) clearTimeout(idleTimerRef.current);
return;
}
const prefersReducedMotion =
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;
if (prefersReducedMotion) return;
const directionMultiplier =
settings.orbitDirection === "clockwise" ? 1 : -1;
const speed = settings.orbitSpeed * directionMultiplier;
function startOrbit() {
if (!map || isInteractingRef.current) return;
const resumeStart = performance.now();
function tick() {
if (!map || isInteractingRef.current) return;
const resumeElapsed = performance.now() - resumeStart;
const t = Math.min(resumeElapsed / ORBIT_EASE_IN_MS, 1);
const easeFactor = smoothstep(t);
const bearing = map.getBearing() + speed * easeFactor;
map.setBearing(bearing % 360);
orbitFrameRef.current = requestAnimationFrame(tick);
}
orbitFrameRef.current = requestAnimationFrame(tick);
}
function stopOrbit() {
if (orbitFrameRef.current) {
cancelAnimationFrame(orbitFrameRef.current);
orbitFrameRef.current = null;
}
}
function resetIdleTimer() {
isInteractingRef.current = true;
stopOrbit();
if (idleTimerRef.current) clearTimeout(idleTimerRef.current);
idleTimerRef.current = setTimeout(() => {
isInteractingRef.current = false;
startOrbit();
}, IDLE_TIMEOUT_MS);
}
const events = ["mousedown", "wheel", "touchstart"] as const;
const container = map.getContainer();
events.forEach((e) =>
container.addEventListener(e, resetIdleTimer, { passive: true }),
);
const onMoveStart = () => {
if (isInteractingRef.current) stopOrbit();
};
map.on("movestart", onMoveStart);
const onCameraStop = (e: Event) => {
const { type } = (e as CustomEvent).detail ?? {};
if (type === "bearing") {
if (idleTimerRef.current) clearTimeout(idleTimerRef.current);
idleTimerRef.current = setTimeout(() => {
isInteractingRef.current = false;
startOrbit();
}, IDLE_TIMEOUT_MS);
}
};
window.addEventListener("aeris:camera-stop", onCameraStop);
idleTimerRef.current = setTimeout(() => {
isInteractingRef.current = false;
startOrbit();
}, IDLE_TIMEOUT_MS);
return () => {
stopOrbit();
if (idleTimerRef.current) clearTimeout(idleTimerRef.current);
events.forEach((e) => container.removeEventListener(e, resetIdleTimer));
map.off("movestart", onMoveStart);
window.removeEventListener("aeris:camera-stop", onCameraStop);
};
}, [
// Auto-orbit hook
useOrbitCamera(
map,
isLoaded,
city,
followFlight,
fpvFlight,
settings.autoOrbit,
settings.orbitSpeed,
settings.orbitDirection,
]);
settings,
isInteractingRef,
orbitFrameRef,
idleTimerRef,
);
return null;
}

View File

@ -0,0 +1,570 @@
import type { FlightState } from "@/lib/opensky";
import type { TrailEntry } from "@/hooks/use-trail-history";
import {
snapLngToReference,
unwrapLngPath,
greatCircleIntermediate,
gcDistanceDeg,
} from "@/lib/geo";
import { roundSharpCorners2D } from "@/lib/trail-smoothing";
import type { ElevatedPoint, Snapshot } from "./flight-layer-constants";
import {
STARTUP_TRAIL_POLLS,
STARTUP_TRAIL_STEP_SEC,
TELEPORT_THRESHOLD,
TRAIL_SMOOTHING_ITERATIONS,
} from "./flight-layer-constants";
// ── Startup Trail ──────────────────────────────────────────────────────
export function buildStartupFallbackTrail(f: FlightState): [number, number][] {
if (f.longitude == null || f.latitude == null) return [];
const heading =
((Number.isFinite(f.trueTrack) ? f.trueTrack! : 0) * Math.PI) / 180;
const speed = Number.isFinite(f.velocity) ? f.velocity! : 200;
const degPerSecond = speed / 111_320;
const path: [number, number][] = [];
for (let i = STARTUP_TRAIL_POLLS; i >= 1; i--) {
const distDeg = Math.min(degPerSecond * STARTUP_TRAIL_STEP_SEC * i, 0.08);
path.push([
f.longitude - Math.sin(heading) * distDeg,
f.latitude - Math.cos(heading) * distDeg,
]);
}
path.push([f.longitude, f.latitude]);
return path;
}
// ── Interpolation Math ─────────────────────────────────────────────────
export function lerpAngle(a: number, b: number, t: number): number {
const delta = ((b - a + 540) % 360) - 180;
return a + delta * t;
}
export function trackFromDelta(
dx: number,
dy: number,
fallback: number,
): number {
if (dx * dx + dy * dy < 1e-10) return fallback;
return ((Math.atan2(dx, dy) * 180) / Math.PI + 360) % 360;
}
export function smoothStep(t: number): number {
return t * t * (3 - 2 * t);
}
// ── Distance Helpers ───────────────────────────────────────────────────
export function horizontalDistanceFromLngLat(
aLng: number,
aLat: number,
bLng: number,
bLat: number,
): number {
const avgLatRad = ((aLat + bLat) * 0.5 * Math.PI) / 180;
const metersPerDegLon = 111_320 * Math.max(0.2, Math.cos(avgLatRad));
const dx = (bLng - aLng) * metersPerDegLon;
const dy = (bLat - aLat) * 111_320;
return Math.hypot(dx, dy);
}
export function horizontalDistanceMeters(a: Snapshot, b: Snapshot): number {
return horizontalDistanceFromLngLat(a.lng, a.lat, b.lng, b.lat);
}
// ── Path Trimming ──────────────────────────────────────────────────────
export function trimAfterLargeJump(
path: [number, number][],
altitudes: Array<number | null>,
maxJumpDeg: number,
): { path: [number, number][]; altitudes: Array<number | null> } {
if (path.length < 2) return { path, altitudes };
const maxJumpSq = maxJumpDeg * maxJumpDeg;
let start = 0;
for (let i = path.length - 2; i >= 0; i--) {
const a = path[i];
const b = path[i + 1];
const dx = b[0] - a[0];
const dy = b[1] - a[1];
if (dx * dx + dy * dy > maxJumpSq) {
start = i + 1;
break;
}
}
if (start > 0) {
start = Math.min(start, path.length - 2);
return {
path: path.slice(start),
altitudes: altitudes.slice(start),
};
}
return { path, altitudes };
}
// ── Elevated Path Smoothing ────────────────────────────────────────────
export function smoothElevatedPath(
points: ElevatedPoint[],
iterations: number = TRAIL_SMOOTHING_ITERATIONS,
): ElevatedPoint[] {
if (points.length < 3 || iterations <= 0) return points;
let current = points;
for (let iter = 0; iter < iterations; iter++) {
if (current.length < 3) break;
const next: ElevatedPoint[] = [current[0]];
for (let i = 0; i < current.length - 1; i++) {
const a = current[i];
const b = current[i + 1];
next.push([
a[0] * 0.75 + b[0] * 0.25,
a[1] * 0.75 + b[1] * 0.25,
a[2] * 0.75 + b[2] * 0.25,
]);
next.push([
a[0] * 0.25 + b[0] * 0.75,
a[1] * 0.25 + b[1] * 0.75,
a[2] * 0.25 + b[2] * 0.75,
]);
}
next.push(current[current.length - 1]);
current = next;
}
return current;
}
export function densifyElevatedPath(
points: ElevatedPoint[],
subdivisions: number = 2,
): ElevatedPoint[] {
if (points.length < 2 || subdivisions <= 1) return points;
// Threshold in degrees above which we use great-circle interpolation
// instead of linear. ~0.5° ≈ 55 km at the equator.
const GC_THRESHOLD_DEG = 0.4;
const out: ElevatedPoint[] = [];
for (let i = 0; i < points.length - 1; i++) {
const a = points[i];
const b = points[i + 1];
out.push(a);
const dist = gcDistanceDeg(a[0], a[1], b[0], b[1]);
const useGC = dist > GC_THRESHOLD_DEG;
// For longer segments, add extra subdivisions proportional to distance
const effectiveSubs = useGC
? Math.max(subdivisions, Math.min(16, Math.ceil(dist / 0.3)))
: subdivisions;
for (let j = 1; j < effectiveSubs; j++) {
const t = j / effectiveSubs;
if (useGC) {
const [lng, lat] = greatCircleIntermediate(a[0], a[1], b[0], b[1], t);
const alt = a[2] + (b[2] - a[2]) * t;
out.push([lng, lat, alt]);
} else {
out.push([
a[0] + (b[0] - a[0]) * t,
a[1] + (b[1] - a[1]) * t,
a[2] + (b[2] - a[2]) * t,
]);
}
}
}
out.push(points[points.length - 1]);
return out;
}
// ── Numeric & Planar Smoothing ─────────────────────────────────────────
export function smoothNumericSeries(values: number[]): number[] {
if (values.length < 3) return values;
const out = [...values];
for (let i = 1; i < values.length - 1; i++) {
out[i] = values[i - 1] * 0.2 + values[i] * 0.6 + values[i + 1] * 0.2;
}
return out;
}
/**
* Multi-pass altitude smoothing with a wider kernel to prevent
* near-vertical "wall" artifacts on climb/descent trails.
* The wider kernel (0.3/0.4/0.3) and multiple passes spread steep
* altitude transitions over more trail points, producing a gradual
* climb/descent gradient that looks natural with elevation exaggeration.
*/
export function smoothAnimationAltitudes(
values: number[],
passes: number = 3,
): number[] {
if (values.length < 3 || passes <= 0) return values;
let result = values;
for (let p = 0; p < passes; p++) {
const next = [...result];
for (let i = 1; i < result.length - 1; i++) {
next[i] = result[i - 1] * 0.3 + result[i] * 0.4 + result[i + 1] * 0.3;
}
result = next;
}
return result;
}
/** Remove points that create sharp reversals (V-spikes) in a 2D path. */
export function removePlanarSpikes(
points: [number, number][],
): [number, number][] {
if (points.length < 3) return points;
const keep: boolean[] = new Array(points.length).fill(true);
const COS_THRESHOLD = -0.5; // reject turns sharper than 120°
for (let pass = 0; pass < 2; pass++) {
let changed = false;
for (let i = 1; i < points.length - 1; i++) {
if (!keep[i]) continue;
let prevIdx = i - 1;
while (prevIdx >= 0 && !keep[prevIdx]) prevIdx--;
if (prevIdx < 0) continue;
let nextIdx = i + 1;
while (nextIdx < points.length && !keep[nextIdx]) nextIdx++;
if (nextIdx >= points.length) continue;
const dx1 = points[i][0] - points[prevIdx][0];
const dy1 = points[i][1] - points[prevIdx][1];
const dx2 = points[nextIdx][0] - points[i][0];
const dy2 = points[nextIdx][1] - points[i][1];
const len1 = Math.sqrt(dx1 * dx1 + dy1 * dy1);
const len2 = Math.sqrt(dx2 * dx2 + dy2 * dy2);
if (len1 < 1e-10 || len2 < 1e-10) continue;
const cos = (dx1 * dx2 + dy1 * dy2) / (len1 * len2);
if (cos < COS_THRESHOLD) {
keep[i] = false;
changed = true;
}
}
if (!changed) break;
}
if (keep.every(Boolean)) return points;
return points.filter((_, i) => keep[i]);
}
export function smoothPlanarPath(
points: [number, number][],
): [number, number][] {
if (points.length < 3) return points;
let current: [number, number][] = removePlanarSpikes(points);
current = roundSharpCorners2D(current, 15);
for (let pass = 0; pass < 6; pass++) {
const next = [...current];
for (let i = 1; i < current.length - 1; i++) {
next[i] = [
current[i - 1][0] * 0.2 + current[i][0] * 0.6 + current[i + 1][0] * 0.2,
current[i - 1][1] * 0.2 + current[i][1] * 0.6 + current[i + 1][1] * 0.2,
];
}
current = next;
}
return current;
}
// ── Trail Ahead Trimming ───────────────────────────────────────────────
export function trimPathAheadOfAircraft(
points: ElevatedPoint[],
aircraft: ElevatedPoint,
): ElevatedPoint[] {
if (points.length < 2) return [aircraft];
const px = aircraft[0];
const py = aircraft[1];
let bestIndex = points.length - 2;
let bestDistanceSq = Number.POSITIVE_INFINITY;
const searchStart = Math.max(0, points.length - 40);
for (let i = searchStart; i < points.length - 1; i++) {
const a = points[i];
const b = points[i + 1];
const dx = b[0] - a[0];
const dy = b[1] - a[1];
const denom = dx * dx + dy * dy;
const t =
denom > 1e-12
? Math.max(
0,
Math.min(1, ((px - a[0]) * dx + (py - a[1]) * dy) / denom),
)
: 0;
const qx = a[0] + dx * t;
const qy = a[1] + dy * t;
const distSq = (px - qx) * (px - qx) + (py - qy) * (py - qy);
if (distSq < bestDistanceSq) {
bestDistanceSq = distSq;
bestIndex = i;
}
}
const trimmed = points.slice(0, bestIndex + 1);
trimmed.push([px, py, aircraft[2]]);
return trimmed;
}
// ── Visible Trail Point Builder (extracted from component) ─────────────
export function buildVisibleTrailPoints(
trail: TrailEntry,
animFlight: FlightState | undefined,
trailDistance: number,
smoothingIterations: number,
denseSubdivisions: number,
): ElevatedPoint[] {
const isFullHistory = trail.fullHistory === true;
const historyPoints = isFullHistory
? trail.path.length
: Math.max(2, Math.round(trailDistance));
let pathSlice =
isFullHistory || trail.path.length <= historyPoints
? trail.path
: trail.path.slice(trail.path.length - historyPoints);
let altitudeSlice =
isFullHistory || trail.altitudes.length <= historyPoints
? trail.altitudes
: trail.altitudes.slice(trail.altitudes.length - historyPoints);
if (isFullHistory) {
const MAX_FULL_HISTORY_POINTS = 2000;
if (pathSlice.length > MAX_FULL_HISTORY_POINTS) {
const stride = pathSlice.length / MAX_FULL_HISTORY_POINTS;
const nextPath: [number, number][] = [];
const nextAlt: Array<number | null> = [];
for (let i = 0; i < MAX_FULL_HISTORY_POINTS - 1; i++) {
const idx = Math.floor(i * stride);
nextPath.push(pathSlice[idx]);
nextAlt.push(altitudeSlice[idx] ?? null);
}
nextPath.push(pathSlice[pathSlice.length - 1]);
nextAlt.push(altitudeSlice[altitudeSlice.length - 1] ?? null);
pathSlice = nextPath;
altitudeSlice = nextAlt;
}
}
if (altitudeSlice.length !== pathSlice.length) {
const last = altitudeSlice[altitudeSlice.length - 1] ?? null;
if (altitudeSlice.length < pathSlice.length) {
altitudeSlice = [...altitudeSlice];
while (altitudeSlice.length < pathSlice.length) {
altitudeSlice.push(last);
}
} else {
altitudeSlice = altitudeSlice.slice(
altitudeSlice.length - pathSlice.length,
);
}
}
const unwrappedPath = unwrapLngPath(pathSlice);
const maxJumpDeg = isFullHistory ? 3.0 : TELEPORT_THRESHOLD;
const trimmed = trimAfterLargeJump(unwrappedPath, altitudeSlice, maxJumpDeg);
pathSlice = trimmed.path;
altitudeSlice = trimmed.altitudes;
const smoothPathSlice = isFullHistory
? pathSlice
: smoothPlanarPath(pathSlice);
const rawAltitudes = altitudeSlice.map(
(a) => a ?? trail.baroAltitude ?? animFlight?.baroAltitude ?? 0,
);
const altitudeMeters = isFullHistory
? rawAltitudes
: smoothAnimationAltitudes(rawAltitudes, 3);
const basePath = smoothPathSlice.map((p, i) => [
p[0],
p[1],
Math.max(0, altitudeMeters[i] ?? trail.baroAltitude ?? 0),
]) as ElevatedPoint[];
const denseBasePath = densifyElevatedPath(
basePath,
isFullHistory ? 1 : denseSubdivisions,
);
if (
animFlight &&
animFlight.longitude != null &&
animFlight.latitude != null &&
denseBasePath.length > 1
) {
const refLng = denseBasePath[denseBasePath.length - 1][0];
const snappedLng = snapLngToReference(animFlight.longitude, refLng);
const clipped = trimPathAheadOfAircraft(denseBasePath, [
snappedLng,
animFlight.latitude,
Math.max(0, animFlight.baroAltitude ?? 0),
]);
const smoothed =
clipped.length < 4
? clipped
: smoothElevatedPath(clipped, isFullHistory ? 1 : smoothingIterations);
return smoothed.map((p) => [p[0], p[1], Math.max(0, p[2])]);
}
const smoothed =
denseBasePath.length < 4
? denseBasePath
: smoothElevatedPath(
denseBasePath,
isFullHistory ? 1 : smoothingIterations,
);
return smoothed.map((p) => [p[0], p[1], Math.max(0, p[2])]);
}
// ── Pitch Calculation (extracted from component) ───────────────────────
export function computePitchByIcao(
interpolated: FlightState[],
trailByIcao: Map<string, TrailEntry>,
currSnapshots: Map<string, Snapshot>,
prevSnapshots: Map<string, Snapshot>,
): Map<string, number> {
const pitchByIcao = new Map<string, number>();
for (const f of interpolated) {
const curr = currSnapshots.get(f.icao24);
const prev = prevSnapshots.get(f.icao24);
const trendTrail = trailByIcao.get(f.icao24);
const trendPitch =
trendTrail && trendTrail.path.length >= 2
? (() => {
const end = trendTrail.path.length - 1;
const start = Math.max(0, end - 7);
const startAlt =
trendTrail.altitudes[start] ??
trendTrail.altitudes[end] ??
f.baroAltitude ??
0;
const endAlt =
trendTrail.altitudes[end] ?? f.baroAltitude ?? startAlt;
const [sLng, sLat] = trendTrail.path[start];
const [eLng, eLat] = trendTrail.path[end];
const hMeters = horizontalDistanceFromLngLat(
sLng,
sLat,
eLng,
eLat,
);
if (hMeters < 1) return 0;
return (-Math.atan2(endAlt - startAlt, hMeters) * 180) / Math.PI;
})()
: 0;
const risePitch =
curr && prev
? (() => {
const hMeters = horizontalDistanceMeters(prev, curr);
if (hMeters < 1) return 0;
const deltaAltitudeMeters = curr.alt - prev.alt;
return (-Math.atan2(deltaAltitudeMeters, hMeters) * 180) / Math.PI;
})()
: 0;
const speed = Number.isFinite(f.velocity) ? f.velocity! : 0;
const verticalRate = Number.isFinite(f.verticalRate) ? f.verticalRate! : 0;
const kinematicPitch =
speed > 0 ? (-Math.atan2(verticalRate, speed) * 180) / Math.PI : 0;
const blendedPitch =
trendPitch * 0.5 + risePitch * 0.38 + kinematicPitch * 0.12;
const amplifiedPitch = blendedPitch * 1.55;
const clampedPitch = Math.max(-40, Math.min(40, amplifiedPitch));
pitchByIcao.set(f.icao24, clampedPitch);
}
return pitchByIcao;
}
// ── Flight Interpolation (extracted from RAF loop) ─────────────────────
export function computeInterpolatedFlights(
currentFlights: FlightState[],
prevSnapshots: Map<string, Snapshot>,
currSnapshots: Map<string, Snapshot>,
tPos: number,
tAngle: number,
rawT: number,
animDuration: number,
): FlightState[] {
return currentFlights.map((f) => {
if (f.longitude == null || f.latitude == null) return f;
const curr = currSnapshots.get(f.icao24);
if (!curr) return f;
const prev = prevSnapshots.get(f.icao24);
if (!prev) {
return {
...f,
longitude: curr.lng,
latitude: curr.lat,
baroAltitude: curr.alt,
trueTrack: Number.isFinite(f.trueTrack) ? f.trueTrack! : curr.track,
};
}
const dx = curr.lng - prev.lng;
const dy = curr.lat - prev.lat;
if (dx * dx + dy * dy > TELEPORT_THRESHOLD * TELEPORT_THRESHOLD) {
return f;
}
if (rawT <= 1) {
const blendedTrack = lerpAngle(prev.track, curr.track, tAngle);
return {
...f,
longitude: prev.lng + dx * tPos,
latitude: prev.lat + dy * tPos,
baroAltitude: prev.alt + (curr.alt - prev.alt) * tPos,
trueTrack: trackFromDelta(dx, dy, blendedTrack),
};
}
const heading = (curr.track * Math.PI) / 180;
const speed = Number.isFinite(f.velocity) ? f.velocity! : 200;
const extraSec = ((rawT - 1) * animDuration) / 1000;
const extraDeg = Math.min((speed * extraSec) / 111_320, 0.03);
const moveDx = Math.sin(heading) * extraDeg;
const moveDy = Math.cos(heading) * extraDeg;
return {
...f,
longitude: curr.lng + moveDx,
latitude: curr.lat + moveDy,
baroAltitude: curr.alt,
trueTrack: trackFromDelta(moveDx, moveDy, curr.track),
};
});
}

View File

@ -0,0 +1,355 @@
import { IconLayer, PathLayer } from "@deck.gl/layers";
import { altitudeToColor, altitudeToElevation } from "@/lib/flight-utils";
import type { FlightState } from "@/lib/opensky";
import type { TrailEntry } from "@/hooks/use-trail-history";
import type { ElevatedPoint } from "./flight-layer-constants";
import {
TRAIL_BELOW_AIRCRAFT_METERS,
TRAIL_SMOOTHING_ITERATIONS,
SELECTION_FADE_MS,
} from "./flight-layer-constants";
import {
PULSE_PERIOD_MS,
RING_PERIOD_MS,
HALO_MAPPING,
RING_MAPPING,
} from "./aircraft-appearance";
import {
buildStartupFallbackTrail,
buildVisibleTrailPoints,
smoothStep,
} from "./flight-animation-helpers";
// ── Slope limiter (post-elevation-exaggeration) ────────────────────────
/**
* Maximum elevation-change-per-degree ratio for rendered trail paths.
* One degree of latitude ≈ 111 km. A ratio of 80 000 means
* max visual slope ≈ 80 km rise per 111 km horizontal ≈ ~36°.
*/
const MAX_ELEV_GRADIENT = 80_000;
/**
* Caps the vertical gradient of an already-elevation-exaggerated trail
* so that steep climbs/descents don't look like near-vertical walls.
* Forward-backward averaging preserves the trail endpoints while
* preventing any single segment from exceeding MAX_ELEV_GRADIENT.
*/
function limitTrailSlope(
pts: [number, number, number][],
): [number, number, number][] {
if (pts.length < 2) return pts;
const n = pts.length;
const fwd = pts.map((p) => p[2]);
for (let i = 1; i < n; i++) {
const dx = pts[i][0] - pts[i - 1][0];
const dy = pts[i][1] - pts[i - 1][1];
const dH = Math.sqrt(dx * dx + dy * dy);
const maxDz = Math.max(dH * MAX_ELEV_GRADIENT, 30);
const dz = fwd[i] - fwd[i - 1];
if (Math.abs(dz) > maxDz) {
fwd[i] = fwd[i - 1] + Math.sign(dz) * maxDz;
}
}
const bwd = pts.map((p) => p[2]);
for (let i = n - 2; i >= 0; i--) {
const dx = pts[i + 1][0] - pts[i][0];
const dy = pts[i + 1][1] - pts[i][1];
const dH = Math.sqrt(dx * dx + dy * dy);
const maxDz = Math.max(dH * MAX_ELEV_GRADIENT, 30);
const dz = bwd[i] - bwd[i + 1];
if (Math.abs(dz) > maxDz) {
bwd[i] = bwd[i + 1] + Math.sign(dz) * maxDz;
}
}
return pts.map((p, i) => {
// Preserve endpoints so trail connects to aircraft and origin
if (i === 0 || i === n - 1) return p;
return [p[0], p[1], Math.max(0, (fwd[i] + bwd[i]) / 2)];
});
}
// ── Trail layer builder ────────────────────────────────────────────────
export interface TrailLayerParams {
interpolated: FlightState[];
interpolatedMap: Map<string, FlightState>;
currentTrails: TrailEntry[];
trailDistance: number;
trailThickness: number;
altColors: boolean;
defaultColor: [number, number, number, number];
elapsed: number;
globeFade: number;
currentZoom: number;
visible?: boolean;
}
export function buildTrailLayers(params: TrailLayerParams) {
const {
interpolated,
interpolatedMap,
currentTrails,
trailDistance,
trailThickness,
altColors,
defaultColor,
elapsed,
globeFade,
currentZoom,
visible = true,
} = params;
const trailMap = new Map(currentTrails.map((t) => [t.icao24, t]));
const handledIds = new Set<string>();
const trailData: TrailEntry[] = [];
const denseSubdivisions = 2;
const smoothingIters =
interpolated.length > 220 ? 2 : TRAIL_SMOOTHING_ITERATIONS;
const visibleTrailCache = new Map<string, ElevatedPoint[]>();
const getVisibleTrailPoints = (
trail: TrailEntry,
animFlight: FlightState | undefined,
): ElevatedPoint[] => {
const cached = visibleTrailCache.get(trail.icao24);
if (cached) return cached;
const computed = buildVisibleTrailPoints(
trail,
animFlight,
trailDistance,
smoothingIters,
denseSubdivisions,
);
visibleTrailCache.set(trail.icao24, computed);
return computed;
};
for (const f of interpolated) {
if (f.longitude == null || f.latitude == null) continue;
const existing = trailMap.get(f.icao24);
handledIds.add(f.icao24);
if (existing && existing.path.length >= 2) {
trailData.push(existing);
continue;
}
const startupPath = buildStartupFallbackTrail(f);
trailData.push({
icao24: f.icao24,
path: startupPath,
altitudes: startupPath.map(
() => existing?.baroAltitude ?? f.baroAltitude,
),
baroAltitude: existing?.baroAltitude ?? f.baroAltitude,
});
}
for (const d of currentTrails) {
if (!handledIds.has(d.icao24)) trailData.push(d);
}
return new PathLayer<TrailEntry>({
id: "flight-trails",
visible,
data: trailData,
opacity: globeFade,
updateTriggers: {
getPath: [elapsed, trailDistance],
getColor: [elapsed, altColors, trailDistance],
},
getPath: (d) => {
const animFlight = interpolatedMap.get(d.icao24);
// Scale elevation exaggeration by zoom:
// At globe zoom (<5) altitude spikes look absurd, so reduce.
// At city zoom (>8) full exaggeration is needed for visual depth.
const elevScale =
currentZoom < 5
? 0.15 + (currentZoom / 5) * 0.35
: currentZoom < 8
? 0.5 + ((currentZoom - 5) / 3) * 0.5
: 1.0;
const raw = getVisibleTrailPoints(d, animFlight).map(
(p) =>
[
p[0],
p[1],
Math.max(
0,
(altitudeToElevation(p[2]) - TRAIL_BELOW_AIRCRAFT_METERS) *
elevScale,
),
] as [number, number, number],
);
return limitTrailSlope(raw);
},
getColor: (d) => {
const animFlight = interpolatedMap.get(d.icao24);
const visiblePoints = getVisibleTrailPoints(d, animFlight);
const len = visiblePoints.length;
const isFullHist = d.fullHistory === true;
return visiblePoints.map((point, i) => {
const tVal = len > 1 ? i / (len - 1) : 1;
const fade = isFullHist
? 0.35 + 0.65 * Math.pow(tVal, 1.1)
: 0.15 + 0.85 * Math.pow(tVal, 1.4);
const base = altColors ? altitudeToColor(point[2]) : defaultColor;
const alpha = isFullHist
? Math.round(55 + fade * 165)
: Math.round(60 + fade * 160);
return [base[0], base[1], base[2], alpha];
}) as [number, number, number, number][];
},
getWidth: trailThickness,
widthUnits: "pixels",
widthMinPixels: Math.max(1, trailThickness * 0.6),
widthMaxPixels: Math.max(2, trailThickness * 1.8),
wrapLongitude: true,
billboard: true,
capRounded: true,
jointRounded: true,
});
}
// ── Selection pulse layer builder ──────────────────────────────────────
export interface SelectionPulseParams {
selectionChangeTime: number;
selectedId: string | null;
prevId: string | null;
interpolated: FlightState[];
elapsed: number;
globeFade: number;
currentZoom: number;
haloUrl: string;
ringUrl: string;
layersVisible?: boolean;
}
export interface SelectionPulseResult {
layers: IconLayer[];
shouldClearPrev: boolean;
}
// Dummy position used for invisible layers to keep deck.gl layer state alive
const EMPTY_PULSE_DATA: { position: [number, number, number] }[] = [];
export function buildSelectionPulseLayers(
params: SelectionPulseParams,
): SelectionPulseResult {
const {
selectionChangeTime,
selectedId,
prevId,
interpolated,
elapsed,
globeFade,
currentZoom,
haloUrl,
ringUrl,
layersVisible = true,
} = params;
// Zoom-dependent elevation scale (matches trail/aircraft scaling)
const elevScale =
currentZoom < 5
? 0.15 + (currentZoom / 5) * 0.35
: currentZoom < 8
? 0.5 + ((currentZoom - 5) / 3) * 0.5
: 1.0;
const layers: IconLayer[] = [];
const fadeElapsed = performance.now() - selectionChangeTime;
const fadeT = Math.min(fadeElapsed / SELECTION_FADE_MS, 1);
const fadeIn = smoothStep(fadeT);
const fadeOut = 1 - fadeIn;
let shouldClearPrev = false;
if (!prevId || prevId === selectedId || fadeOut <= 0.01) {
if (fadeT >= 1) shouldClearPrev = true;
}
// Build stable layers for both "sel" and "prev" prefixes.
// Always emit all 8 IDs; use `visible` to toggle rather than omitting layers.
const prefixes = ["sel", "prev"] as const;
for (const prefix of prefixes) {
const isSelected = prefix === "sel";
const targetId = isSelected ? selectedId : prevId;
const op = isSelected ? fadeIn : fadeOut;
const flight = targetId
? interpolated.find((f) => f.icao24 === targetId)
: undefined;
const hasPosition =
flight && flight.longitude != null && flight.latitude != null;
const active = layersVisible && !!targetId && hasPosition && op > 0.01;
const pos: [number, number, number] = hasPosition
? [
flight!.longitude!,
flight!.latitude!,
altitudeToElevation(flight!.baroAltitude) * elevScale,
]
: [0, 0, 0];
const data = active ? [{ position: pos }] : EMPTY_PULSE_DATA;
const breathT = (elapsed % PULSE_PERIOD_MS) / PULSE_PERIOD_MS;
const breath = Math.sin(breathT * Math.PI * 2);
const softBreath = smoothStep(smoothStep((breath + 1) / 2)) * 2 - 1;
const haloSize = 75 + 8 * softBreath;
const haloAlpha = Math.round((18 + 8 * softBreath) * op);
layers.push(
new IconLayer({
id: `${prefix}-halo`,
visible: active && haloAlpha > 0,
data,
opacity: globeFade,
getPosition: (d: { position: [number, number, number] }) => d.position,
getIcon: () => "halo",
getSize: haloSize,
getColor: [70, 160, 240, haloAlpha],
iconAtlas: haloUrl,
iconMapping: HALO_MAPPING,
billboard: true,
sizeUnits: "pixels",
sizeScale: 1,
}),
);
const ringOffsets = [0, RING_PERIOD_MS / 3, (RING_PERIOD_MS * 2) / 3];
ringOffsets.forEach((offset, i) => {
const t = ((elapsed + offset) % RING_PERIOD_MS) / RING_PERIOD_MS;
const eased = 1 - (1 - t) ** 5;
const ringSize = 30 + 60 * eased;
const fade = 1 - t;
const ringAlpha = Math.round(70 * fade * fade * fade * fade * op);
layers.push(
new IconLayer({
id: `${prefix}-ring-${i}`,
visible: active && ringAlpha >= 2,
data,
opacity: globeFade,
getPosition: (d: { position: [number, number, number] }) =>
d.position,
getIcon: () => "ring",
getSize: ringSize,
getColor: [70, 165, 235, ringAlpha],
iconAtlas: ringUrl,
iconMapping: RING_MAPPING,
billboard: true,
sizeUnits: "pixels",
sizeScale: 1,
}),
);
});
}
return { layers, shouldClearPrev };
}

View File

@ -0,0 +1,73 @@
import { type MapboxOverlay } from "@deck.gl/mapbox";
import { type PickingInfo } from "@deck.gl/core";
import type { FlightState } from "@/lib/opensky";
import type { TrailEntry } from "@/hooks/use-trail-history";
import type { MutableRefObject } from "react";
// ── Overlay type augmentation ──────────────────────────────────────────
export type DeckGLOverlay = MapboxOverlay & {
pickObject?(opts: {
x: number;
y: number;
radius: number;
}): PickingInfo | null;
};
// ── Animation & rendering constants ────────────────────────────────────
export const DEFAULT_ANIM_DURATION_MS = 30_000;
export const MIN_ANIM_DURATION_MS = 8_000;
export const MAX_ANIM_DURATION_MS = 45_000;
export const TELEPORT_THRESHOLD = 0.3;
export const TRAIL_BELOW_AIRCRAFT_METERS = 40;
export const STARTUP_TRAIL_POLLS = 3;
export const STARTUP_TRAIL_STEP_SEC = 12;
export const TRACK_DAMPING = 0.18;
export const TRAIL_SMOOTHING_ITERATIONS = 3;
export const AIRCRAFT_SCENEGRAPH_URL = "/models/airplane.glb";
export const AIRCRAFT_PX_PER_UNIT = 0.3;
export const BASE_AIRCRAFT_SIZE = 25;
export const AIRCRAFT_PICK_RADIUS_PX = 14;
export const SELECTION_FADE_MS = 600;
// Globe/Mercator hard-switch: dots below this zoom, flights above.
export const GLOBE_SWITCH_ZOOM = 5.8;
export const GLOBE_FADE_ZOOM_FLOOR = GLOBE_SWITCH_ZOOM - 0.05;
export const GLOBE_FADE_ZOOM_CEIL = GLOBE_SWITCH_ZOOM + 0.05;
export const GLOBE_NATIVE_ZOOM_CEIL = GLOBE_SWITCH_ZOOM;
// GeoJSON globe dot layer timing
export const GEOJSON_THROTTLE_MS = 1500;
export const GEOJSON_DEBOUNCE_MS = 200;
// ── Shared types ───────────────────────────────────────────────────────
export type Snapshot = {
lng: number;
lat: number;
alt: number;
track: number;
};
export type ElevatedPoint = [number, number, number];
export type FlightLayerProps = {
flights: FlightState[];
trails: TrailEntry[];
onClick: (info: PickingInfo<FlightState> | null) => void;
selectedIcao24: string | null;
showTrails: boolean;
trailThickness: number;
trailDistance: number;
showShadows: boolean;
showAltitudeColors: boolean;
globeMode?: boolean;
fpvIcao24?: string | null;
fpvPositionRef?: MutableRefObject<{
lng: number;
lat: number;
alt: number;
track: number;
} | null>;
};

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
"use client";
import maplibregl from "maplibre-gl";
import maplibregl, { setMaxParallelImageRequests } from "maplibre-gl";
import "maplibre-gl/dist/maplibre-gl.css";
import {
createContext,
@ -14,7 +14,23 @@ import {
type ReactNode,
} from "react";
import { cn } from "@/lib/utils";
import { DEFAULT_STYLE, type MapStyleSpec } from "@/lib/map-styles";
import {
createTerrainDemSource,
DEFAULT_STYLE,
DARK_TERRAIN_HILLSHADE_LAYER,
DARK_TERRAIN_SKY,
DARK_TERRAIN_SPEC,
TERRAIN_DEM_SOURCE_ID,
TERRAIN_HILLSHADE_LAYER_ID,
type MapStyleSpec,
type TerrainProfile,
} from "@/lib/map-styles";
// Increase parallel tile requests for faster DEM + base tile loading.
// Default is 6; 16 allows terrain tiles to saturate HTTP/2 connections.
setMaxParallelImageRequests(16);
const GLOBE_MAX_PITCH = 80;
type MapContextValue = {
map: maplibregl.Map | null;
@ -34,7 +50,9 @@ type MapProps = {
children?: ReactNode;
className?: string;
mapStyle?: MapStyleSpec;
terrainProfile?: TerrainProfile;
isDark?: boolean;
globeMode?: boolean;
center?: [number, number];
zoom?: number;
pitch?: number;
@ -50,7 +68,9 @@ export const Map = forwardRef<MapRef, MapProps>(function Map(
children,
className,
mapStyle = DEFAULT_STYLE.style,
terrainProfile = "none",
isDark = true,
globeMode = false,
center = [0, 20],
zoom = 2.5,
pitch = 49,
@ -66,20 +86,32 @@ export const Map = forwardRef<MapRef, MapProps>(function Map(
useImperativeHandle(ref, () => mapInstance as maplibregl.Map, [mapInstance]);
// Ref that allows style-load callbacks to see the latest value without re-running effects
const isDarkRef = useRef(isDark);
isDarkRef.current = isDark;
const globeModeRef = useRef(globeMode);
globeModeRef.current = globeMode;
// ── Map creation ──────────────────────────────────────────────────
useEffect(() => {
if (!containerRef.current) return;
const safePitch = Math.min(pitch, GLOBE_MAX_PITCH);
const map = new maplibregl.Map({
container: containerRef.current,
style: DEFAULT_STYLE.style as maplibregl.StyleSpecification | string,
center,
zoom,
pitch,
pitch: safePitch,
bearing,
minZoom,
maxZoom,
maxPitch: 85,
maxPitch: GLOBE_MAX_PITCH,
attributionControl: false,
cancelPendingTileRequestsWhileZooming: true,
maxTileCacheZoomLevels: 3, // fewer cached zoom levels = less memory for DEM tiles
renderWorldCopies: false,
});
@ -94,39 +126,54 @@ export const Map = forwardRef<MapRef, MapProps>(function Map(
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const isDarkRef = useRef(isDark);
isDarkRef.current = isDark;
// Inject globe projection into every style change when globe mode is on.
// In Mercator mode, skip projection injection entirely.
useEffect(() => {
if (!mapInstance || !isLoaded) return;
mapInstance.setStyle(mapStyle as maplibregl.StyleSpecification | string);
const onStyleLoad = () => {
if (typeof mapStyle === "object" && "terrain" in mapStyle) {
const spec = mapStyle as Record<string, unknown>;
try {
mapInstance.setTerrain(
spec.terrain as maplibregl.TerrainSpecification,
);
} catch {
/* terrain source not yet loaded */
}
} else {
try {
mapInstance.setTerrain(null);
} catch {
/* no terrain to remove */
}
}
mapInstance.setStyle(
mapStyle as maplibregl.StyleSpecification | string,
{
transformStyle: (_prev, next) => {
const style = next as MutableStyleSpecification;
if (globeMode) {
style.projection = { type: "globe" };
if (!style.sky) {
style.sky = {
"atmosphere-blend": [
"interpolate",
["linear"],
["zoom"],
0,
1,
5,
0,
],
};
}
}
if (terrainProfile === "dark" && !globeMode) {
applyDarkTerrainStyle(style);
style.sky = DARK_TERRAIN_SKY as Record<string, unknown>;
}
return style;
},
} as maplibregl.StyleSwapOptions & { transformStyle: unknown },
);
// Set projection imperatively so it takes effect immediately.
mapInstance.once("style.load", () => {
mapInstance.setProjection({ type: globeMode ? "globe" : "mercator" });
addAerowayLayers(mapInstance, isDarkRef.current);
};
mapInstance.once("style.load", onStyleLoad);
});
return () => {
mapInstance.off("style.load", onStyleLoad);
mapInstance.off("style.load", () => {});
};
}, [mapInstance, isLoaded, mapStyle]);
}, [mapInstance, isLoaded, mapStyle, terrainProfile, globeMode]);
const ctx = useMemo(
() => ({ map: mapInstance, isLoaded }),
@ -147,6 +194,42 @@ export const Map = forwardRef<MapRef, MapProps>(function Map(
Map.displayName = "Map";
type MutableStyleSpecification = maplibregl.StyleSpecification & {
projection?: maplibregl.ProjectionSpecification;
sky?: Record<string, unknown>;
sources?: Record<string, unknown>;
layers?: maplibregl.LayerSpecification[];
terrain?: maplibregl.TerrainSpecification;
};
function applyDarkTerrainStyle(style: MutableStyleSpecification): void {
const sources = (style.sources ??=
{}) as maplibregl.StyleSpecification["sources"];
// Single DEM source shared by both terrain mesh and hillshade layer.
// This halves tile downloads vs. having two separate sources.
if (!sources[TERRAIN_DEM_SOURCE_ID]) {
sources[TERRAIN_DEM_SOURCE_ID] =
createTerrainDemSource() as maplibregl.SourceSpecification;
}
style.terrain = DARK_TERRAIN_SPEC as maplibregl.TerrainSpecification;
const layers = (style.layers ??= []);
if (!layers.some((layer) => layer.id === TERRAIN_HILLSHADE_LAYER_ID)) {
const firstSymbolIndex = layers.findIndex(
(layer) => layer.type === "symbol",
);
const insertIndex =
firstSymbolIndex === -1 ? layers.length : firstSymbolIndex;
layers.splice(
insertIndex,
0,
DARK_TERRAIN_HILLSHADE_LAYER as maplibregl.LayerSpecification,
);
}
}
function findVectorSource(map: maplibregl.Map): string | null {
const style = map.getStyle();
if (!style?.sources) return null;

View File

@ -0,0 +1,275 @@
"use client";
import { useEffect, type MutableRefObject } from "react";
import type maplibregl from "maplibre-gl";
import {
FPV_DISTANCE_ZOOM_OFFSET,
fpvZoomForAltitude,
lerp,
lerpLng,
normalizeLng,
projectLngLatElevationPixelDelta,
setMapInteractionsEnabled,
smoothstep,
} from "./camera-controller-utils";
import type { City } from "@/lib/cities";
import type { FlightState } from "@/lib/opensky";
const DEFAULT_ZOOM = 9.2;
const DEFAULT_PITCH = 49;
const DEFAULT_BEARING = 27.4;
const FPV_FLY_DURATION = 1600;
const FPV_PITCH = 65;
const FPV_CENTER_ALPHA = 0.16;
const FPV_BEARING_ALPHA = 0.1;
const FPV_ZOOM_ALPHA = 0.06;
const FPV_IDLE_RECENTER_MS = 1200;
const FPV_EASE_IN_MS = 600;
type FpvPosition = { lng: number; lat: number; alt: number; track: number };
export function useFpvCamera(
map: maplibregl.Map | null,
isLoaded: boolean,
fpvFlight: FlightState | null,
city: City,
fpvFlightRef: MutableRefObject<FlightState | null>,
fpvPosRef: MutableRefObject<MutableRefObject<FpvPosition | null> | undefined>,
isFpvActiveRef: MutableRefObject<boolean>,
prevFpvRef: MutableRefObject<string | null>,
) {
useEffect(() => {
if (!map || !isLoaded) {
if (isFpvActiveRef.current) {
isFpvActiveRef.current = false;
}
return;
}
const fpv = fpvFlightRef.current;
const fpvKey = fpv?.icao24 ?? null;
if (fpvKey === prevFpvRef.current) return;
const wasFpv = prevFpvRef.current !== null;
prevFpvRef.current = fpvKey;
if (!fpv || fpv.longitude == null || fpv.latitude == null) {
isFpvActiveRef.current = false;
if (wasFpv) {
setMapInteractionsEnabled(map, true);
}
if (wasFpv) {
map.flyTo({
center: city.coordinates,
zoom: DEFAULT_ZOOM,
pitch: DEFAULT_PITCH,
bearing: DEFAULT_BEARING,
duration: 1800,
essential: true,
});
}
return;
}
isFpvActiveRef.current = true;
setMapInteractionsEnabled(map, true);
const bearing = Number.isFinite(fpv.trueTrack)
? fpv.trueTrack!
: map.getBearing();
const safeAltitude = Number.isFinite(fpv.baroAltitude)
? fpv.baroAltitude!
: 5000;
const zoom = fpvZoomForAltitude(safeAltitude) - FPV_DISTANCE_ZOOM_OFFSET;
let fpvOffsetX = 0;
let fpvOffsetY = 0;
map.flyTo({
center: [normalizeLng(fpv.longitude), fpv.latitude],
zoom,
pitch: FPV_PITCH,
bearing,
duration: FPV_FLY_DURATION,
essential: true,
});
let frameId: number | null = null;
let startupTimer: ReturnType<typeof setTimeout> | null = null;
let prevBearing = bearing;
let lastInteractionTime = 0;
let recenterStartTime = 0;
let programmaticMove = false;
function onUserInteraction() {
if (programmaticMove) return;
lastInteractionTime = performance.now();
recenterStartTime = 0;
}
const onMapInteraction = (e: unknown) => {
if (programmaticMove) return;
const evt = e as { originalEvent?: Event };
if (!evt?.originalEvent) return;
onUserInteraction();
};
const interactionEventTypes = [
"movestart",
"move",
"zoomstart",
"zoom",
"rotatestart",
"rotate",
"pitchstart",
"pitch",
] as const;
for (const t of interactionEventTypes) {
map.on(t, onMapInteraction);
}
function keepInFrame() {
if (!isFpvActiveRef.current || !map) {
frameId = null;
return;
}
const interpPos = fpvPosRef.current?.current ?? null;
const live = fpvFlightRef.current;
const posLng = interpPos?.lng ?? live?.longitude ?? null;
const posLat = interpPos?.lat ?? live?.latitude ?? null;
const posAlt = interpPos?.alt ?? live?.baroAltitude ?? 5000;
const posTrack = interpPos?.track ?? live?.trueTrack ?? null;
if (posLng == null || posLat == null) {
frameId = requestAnimationFrame(keepInFrame);
return;
}
if (
!Number.isFinite(posLng) ||
!Number.isFinite(posLat) ||
Math.abs(posLat) > 90
) {
frameId = requestAnimationFrame(keepInFrame);
return;
}
const now = performance.now();
const idleMs =
lastInteractionTime === 0
? FPV_IDLE_RECENTER_MS + 1
: now - lastInteractionTime;
const isIdle = idleMs > FPV_IDLE_RECENTER_MS;
let trackingStrength = 0;
if (isIdle) {
if (recenterStartTime === 0) {
recenterStartTime = now;
}
const easeElapsed = now - recenterStartTime;
const t = Math.min(easeElapsed / FPV_EASE_IN_MS, 1);
trackingStrength = smoothstep(t);
}
const liveBearing =
posTrack !== null && Number.isFinite(posTrack) ? posTrack : prevBearing;
const bearingDelta = ((liveBearing - prevBearing + 540) % 360) - 180;
prevBearing = prevBearing + bearingDelta * FPV_BEARING_ALPHA;
if (trackingStrength > 0.001) {
const safeAlt = Number.isFinite(posAlt) ? posAlt : 5000;
const targetZoom =
fpvZoomForAltitude(safeAlt) - FPV_DISTANCE_ZOOM_OFFSET;
const currentZoom = map.getZoom();
const zoomAlpha = FPV_ZOOM_ALPHA * trackingStrength;
const smoothZoom = lerp(currentZoom, targetZoom, zoomAlpha);
const currentPitch = map.getPitch();
const targetLng = normalizeLng(posLng);
const targetLat = posLat;
const center = map.getCenter();
const centerAlpha = FPV_CENTER_ALPHA * trackingStrength;
const canvas = map.getCanvas();
const canvasW = Math.max(1, canvas.clientWidth);
const canvasH = Math.max(1, canvas.clientHeight);
const elevationMeters = Math.max(safeAlt * 5, 200);
const deltaPx = projectLngLatElevationPixelDelta(
map,
targetLng,
targetLat,
elevationMeters,
);
if (deltaPx) {
const desiredX = fpvOffsetX - deltaPx.dx;
const desiredY = fpvOffsetY - deltaPx.dy;
const offsetAlpha = 0.08 * trackingStrength;
fpvOffsetX = lerp(fpvOffsetX, desiredX, offsetAlpha);
fpvOffsetY = lerp(fpvOffsetY, desiredY, offsetAlpha);
} else {
const decayAlpha = 0.1 * trackingStrength;
fpvOffsetX = lerp(fpvOffsetX, 0, decayAlpha);
fpvOffsetY = lerp(fpvOffsetY, 0, decayAlpha);
}
const maxScale = Math.min(1.5, Math.max(1, elevationMeters / 15_000));
const maxOffset = 0.45 * maxScale * Math.min(canvasW, canvasH);
fpvOffsetX = Math.max(-maxOffset, Math.min(maxOffset, fpvOffsetX));
fpvOffsetY = Math.max(-maxOffset, Math.min(maxOffset, fpvOffsetY));
const currentBearing = map.getBearing();
const bearingToCurrent =
((prevBearing - currentBearing + 540) % 360) - 180;
const newMapBearing =
currentBearing +
bearingToCurrent * FPV_BEARING_ALPHA * trackingStrength;
const pitchAlpha = 0.05 * trackingStrength;
const newPitch = lerp(currentPitch, FPV_PITCH, pitchAlpha);
programmaticMove = true;
try {
map.easeTo({
center: [
lerpLng(center.lng, targetLng, centerAlpha),
lerp(center.lat, targetLat, centerAlpha),
],
bearing: newMapBearing,
zoom: smoothZoom,
pitch: newPitch,
offset: [fpvOffsetX, fpvOffsetY],
duration: 0,
animate: false,
essential: true,
});
} finally {
programmaticMove = false;
}
}
frameId = requestAnimationFrame(keepInFrame);
}
startupTimer = setTimeout(() => {
startupTimer = null;
frameId = requestAnimationFrame(keepInFrame);
}, FPV_FLY_DURATION + 300);
return () => {
if (startupTimer) clearTimeout(startupTimer);
if (frameId != null) cancelAnimationFrame(frameId);
for (const t of interactionEventTypes) {
map.off(t, onMapInteraction);
}
if (map && isFpvActiveRef.current) {
setMapInteractionsEnabled(map, true);
isFpvActiveRef.current = false;
}
};
}, [map, isLoaded, fpvFlight?.icao24, city]);
}

View File

@ -0,0 +1,377 @@
"use client";
import { useEffect, useRef, type MutableRefObject } from "react";
import maplibregl from "maplibre-gl";
import type { FlightState } from "@/lib/opensky";
import { altitudeToColor } from "@/lib/flight-utils";
import { type PickingInfo } from "@deck.gl/core";
import type { TrailEntry } from "@/hooks/use-trail-history";
import {
densifyGreatCircle2D,
splitAtAntimeridian,
unwrapLngPath,
} from "@/lib/geo";
import {
GLOBE_NATIVE_ZOOM_CEIL,
GLOBE_SWITCH_ZOOM,
GEOJSON_THROTTLE_MS,
GEOJSON_DEBOUNCE_MS,
} from "./flight-layer-constants";
const SOURCE_ID = "globe-aircraft-source";
const LAYER_ID = "globe-aircraft-dots";
const TRAIL_SOURCE_ID = "globe-trail-source";
const TRAIL_LAYER_ID = "globe-trail-lines";
/**
* Custom hook that manages native MapLibre GeoJSON circle + line layers for
* rendering aircraft dots AND trail lines at low globe zoom levels where
* deck.gl accuracy degrades. Native MapLibre layers follow the globe
* curvature perfectly and handle antimeridian crossings automatically.
*/
export function useGlobeDots(
map: maplibregl.Map | null,
isLoaded: boolean,
flightsRef: MutableRefObject<FlightState[]>,
trailsRef: MutableRefObject<TrailEntry[]>,
dataTimestampRef: MutableRefObject<number>,
onClickRef: MutableRefObject<(info: PickingInfo<FlightState> | null) => void>,
showTrailsRef: MutableRefObject<boolean>,
) {
const lastGeoJsonUpdateRef = useRef(0);
const lastGeoJsonTimestampRef = useRef(0);
const geoJsonClearedRef = useRef(false);
const globeZoomEnteredAtRef = useRef(0);
// Set up MapLibre source, layer, and event handlers
useEffect(() => {
if (!map || !isLoaded) return;
const ensureGlobeLayers = () => {
// ── Aircraft dots ──
if (!map.getSource(SOURCE_ID)) {
map.addSource(SOURCE_ID, {
type: "geojson",
data: { type: "FeatureCollection", features: [] },
});
}
if (!map.getLayer(LAYER_ID)) {
map.addLayer({
id: LAYER_ID,
type: "circle",
source: SOURCE_ID,
paint: {
"circle-radius": [
"interpolate",
["exponential", 1.5],
["zoom"],
0,
["interpolate", ["linear"], ["get", "alt_norm"], 0, 1.2, 1, 2.0],
2,
["interpolate", ["linear"], ["get", "alt_norm"], 0, 1.8, 1, 2.8],
GLOBE_NATIVE_ZOOM_CEIL,
["interpolate", ["linear"], ["get", "alt_norm"], 0, 3.0, 1, 5.0],
],
"circle-color": ["get", "color"],
"circle-opacity": [
"interpolate",
["linear"],
["zoom"],
GLOBE_SWITCH_ZOOM - 0.05,
0.9,
GLOBE_SWITCH_ZOOM,
0,
],
"circle-stroke-color": "rgba(255, 255, 255, 0.5)",
"circle-stroke-width": [
"interpolate",
["linear"],
["zoom"],
0,
0.3,
GLOBE_SWITCH_ZOOM,
0.8,
],
"circle-blur": 0.1,
},
});
}
// ── Trail lines ──
if (!map.getSource(TRAIL_SOURCE_ID)) {
map.addSource(TRAIL_SOURCE_ID, {
type: "geojson",
data: { type: "FeatureCollection", features: [] },
});
}
if (!map.getLayer(TRAIL_LAYER_ID)) {
map.addLayer(
{
id: TRAIL_LAYER_ID,
type: "line",
source: TRAIL_SOURCE_ID,
paint: {
"line-color": ["get", "color"],
"line-width": [
"interpolate",
["linear"],
["zoom"],
0,
0.8,
2,
1.2,
GLOBE_NATIVE_ZOOM_CEIL,
1.8,
],
"line-opacity": [
"interpolate",
["linear"],
["zoom"],
GLOBE_SWITCH_ZOOM - 0.05,
0.65,
GLOBE_SWITCH_ZOOM,
0,
],
},
layout: {
"line-cap": "round",
"line-join": "round",
},
},
LAYER_ID, // render trails below dots
);
}
};
ensureGlobeLayers();
map.on("style.load", ensureGlobeLayers);
const onDotClick = (
e: maplibregl.MapMouseEvent & { features?: maplibregl.GeoJSONFeature[] },
) => {
const icao24 = e.features?.[0]?.properties?.icao24;
if (!icao24) return;
const flight = flightsRef.current.find((f) => f.icao24 === icao24);
if (flight) {
onClickRef.current({ object: flight } as PickingInfo<FlightState>);
}
};
map.on("click", LAYER_ID, onDotClick);
const onDotEnter = () => {
map.getCanvas().style.cursor = "pointer";
};
const onDotLeave = () => {
map.getCanvas().style.cursor = "";
};
map.on("mouseenter", LAYER_ID, onDotEnter);
map.on("mouseleave", LAYER_ID, onDotLeave);
return () => {
map.off("style.load", ensureGlobeLayers);
map.off("click", LAYER_ID, onDotClick);
map.off("mouseenter", LAYER_ID, onDotEnter);
map.off("mouseleave", LAYER_ID, onDotLeave);
try {
if (map.getLayer(TRAIL_LAYER_ID)) map.removeLayer(TRAIL_LAYER_ID);
if (map.getSource(TRAIL_SOURCE_ID)) map.removeSource(TRAIL_SOURCE_ID);
if (map.getLayer(LAYER_ID)) map.removeLayer(LAYER_ID);
if (map.getSource(SOURCE_ID)) map.removeSource(SOURCE_ID);
} catch {
/* map already removed */
}
};
}, [map, isLoaded, flightsRef, onClickRef]);
/**
* Called from the RAF animation loop. Updates (or clears) both the dot
* GeoJSON source and the trail line GeoJSON source based on current
* zoom level and globe mode.
*/
function updateGlobeDots(isGlobe: boolean, currentZoom: number, now: number) {
if (!map) return;
const MAX_ALTITUDE_METERS = 13000;
// Hide layers unless globe mode AND below switch zoom
const dotsVisible = isGlobe && currentZoom < GLOBE_NATIVE_ZOOM_CEIL;
try {
if (map.getLayer(LAYER_ID)) {
map.setLayoutProperty(
LAYER_ID,
"visibility",
dotsVisible ? "visible" : "none",
);
}
if (map.getLayer(TRAIL_LAYER_ID)) {
map.setLayoutProperty(
TRAIL_LAYER_ID,
"visibility",
dotsVisible ? "visible" : "none",
);
}
} catch {
/* layer may not exist yet */
}
if (isGlobe) {
if (currentZoom < GLOBE_NATIVE_ZOOM_CEIL) {
if (globeZoomEnteredAtRef.current === 0) {
globeZoomEnteredAtRef.current = now;
}
const stableMs = now - globeZoomEnteredAtRef.current;
if (stableMs >= GEOJSON_DEBOUNCE_MS) {
const dataChanged =
dataTimestampRef.current !== lastGeoJsonTimestampRef.current;
const throttleExpired =
now - lastGeoJsonUpdateRef.current > GEOJSON_THROTTLE_MS;
if (dataChanged || throttleExpired) {
// ── Update aircraft dots ──
const dotSrc = map.getSource(SOURCE_ID) as
| maplibregl.GeoJSONSource
| undefined;
if (dotSrc) {
const flights = flightsRef.current;
const features = [];
for (const f of flights) {
if (
f.longitude == null ||
f.latitude == null ||
!Number.isFinite(f.longitude) ||
!Number.isFinite(f.latitude)
)
continue;
const c = altitudeToColor(f.baroAltitude);
const altNorm = Math.min(
1,
Math.max(0, (f.baroAltitude ?? 0) / MAX_ALTITUDE_METERS),
);
features.push({
type: "Feature" as const,
geometry: {
type: "Point" as const,
coordinates: [f.longitude, f.latitude],
},
properties: {
icao24: f.icao24,
color: `rgb(${c[0]},${c[1]},${c[2]})`,
alt_norm: altNorm,
},
});
}
dotSrc.setData({ type: "FeatureCollection", features });
}
// ── Update trail lines ──
const trailSrc = map.getSource(TRAIL_SOURCE_ID) as
| maplibregl.GeoJSONSource
| undefined;
if (trailSrc) {
// Respect the showTrails user setting
if (!showTrailsRef.current) {
trailSrc.setData({ type: "FeatureCollection", features: [] });
} else {
const trails = trailsRef.current;
const trailFeatures: GeoJSON.Feature[] = [];
for (const trail of trails) {
if (trail.path.length < 2) continue;
// Get the trail color from the most recent altitude
const lastAlt =
trail.baroAltitude ??
trail.altitudes[trail.altitudes.length - 1] ??
0;
const c = altitudeToColor(lastAlt);
const color = `rgba(${c[0]},${c[1]},${c[2]},0.7)`;
// Limit to last N points for performance at globe zoom
const maxPts = 60;
const rawPath =
trail.path.length > maxPts
? trail.path.slice(trail.path.length - maxPts)
: trail.path;
// Unwrap longitudes for continuity
const unwrapped = unwrapLngPath(rawPath);
// Densify along great-circle arcs so trails curve
// properly on the globe (segments > 0.3° get subdivided)
const densified = densifyGreatCircle2D(unwrapped, 0.3, 16);
// Normalize longitudes back to [-180, 180] range
const normalized: [number, number][] = densified.map(
([lng, lat]) => {
let normLng = lng;
while (normLng > 180) normLng -= 360;
while (normLng < -180) normLng += 360;
return [normLng, lat];
},
);
// Split at antimeridian crossings for MapLibre
const segments = splitAtAntimeridian(normalized);
for (const seg of segments) {
if (seg.length < 2) continue;
trailFeatures.push({
type: "Feature",
geometry: {
type: "LineString",
coordinates: seg,
},
properties: { color, icao24: trail.icao24 },
});
}
}
trailSrc.setData({
type: "FeatureCollection",
features: trailFeatures,
});
} // end showTrails check
}
lastGeoJsonUpdateRef.current = now;
lastGeoJsonTimestampRef.current = dataTimestampRef.current;
geoJsonClearedRef.current = false;
}
}
} else {
globeZoomEnteredAtRef.current = 0;
if (!geoJsonClearedRef.current) {
clearNativeSources();
}
}
} else if (!geoJsonClearedRef.current) {
clearNativeSources();
}
}
function clearNativeSources() {
if (!map) return;
try {
const dotSrc = map.getSource(SOURCE_ID) as
| maplibregl.GeoJSONSource
| undefined;
if (dotSrc) {
dotSrc.setData({ type: "FeatureCollection", features: [] });
}
const trailSrc = map.getSource(TRAIL_SOURCE_ID) as
| maplibregl.GeoJSONSource
| undefined;
if (trailSrc) {
trailSrc.setData({ type: "FeatureCollection", features: [] });
}
geoJsonClearedRef.current = true;
} catch {
/* source may be removed */
}
}
return { updateGlobeDots };
}

View File

@ -0,0 +1,146 @@
"use client";
import { useEffect, type MutableRefObject } from "react";
import type maplibregl from "maplibre-gl";
const CAMERA_ACCEL = 2.5;
const CAMERA_DECEL = 4.0;
const ZOOM_SPEED = 1.2;
const PITCH_SPEED = 28;
const BEARING_SPEED = 55;
const MINIMUM_IMPULSE_DURATION_MS = 180;
type CameraActionType = "zoom" | "pitch" | "bearing";
type ActionState = {
direction: number;
velocity: number;
held: boolean;
impulseEnd: number;
};
export function useKeyboardCamera(
map: maplibregl.Map | null,
isLoaded: boolean,
isFpvActiveRef: MutableRefObject<boolean>,
isInteractingRef: MutableRefObject<boolean>,
idleTimerRef: MutableRefObject<ReturnType<typeof setTimeout> | null>,
) {
useEffect(() => {
if (!map || !isLoaded) return;
const actions = new Map<CameraActionType, ActionState>();
let frameId: number | null = null;
let lastTime = 0;
function getOrCreate(
type: CameraActionType,
direction: number,
): ActionState {
let s = actions.get(type);
if (!s) {
s = { direction, velocity: 0, held: false, impulseEnd: 0 };
actions.set(type, s);
}
return s;
}
function maxSpeed(type: CameraActionType): number {
if (type === "zoom") return ZOOM_SPEED;
if (type === "pitch") return PITCH_SPEED;
return BEARING_SPEED;
}
function applyDelta(type: CameraActionType, delta: number) {
if (type === "zoom") {
const z = map!.getZoom() + delta;
map!.setZoom(
Math.min(Math.max(z, map!.getMinZoom()), map!.getMaxZoom()),
);
} else if (type === "pitch") {
const p = map!.getPitch() + delta;
map!.setPitch(Math.min(Math.max(p, 0), map!.getMaxPitch()));
} else {
map!.setBearing(map!.getBearing() + delta);
}
}
function tick(now: number) {
const dt = lastTime ? Math.min((now - lastTime) / 1000, 0.1) : 0.016;
lastTime = now;
let anyActive = false;
for (const [type, state] of actions) {
const wantSpeed = state.held || now < state.impulseEnd;
if (wantSpeed) {
state.velocity = Math.min(
state.velocity + CAMERA_ACCEL * dt * maxSpeed(type),
maxSpeed(type),
);
} else {
state.velocity = Math.max(
state.velocity - CAMERA_DECEL * dt * maxSpeed(type),
0,
);
}
if (state.velocity > 0.001) {
applyDelta(type, state.direction * state.velocity * dt);
anyActive = true;
} else {
state.velocity = 0;
if (!state.held) {
actions.delete(type);
if (type === "bearing") {
isInteractingRef.current = false;
}
}
}
}
frameId = anyActive ? requestAnimationFrame(tick) : null;
}
function ensureLoop() {
if (frameId == null) {
lastTime = 0;
frameId = requestAnimationFrame(tick);
}
}
const onStart = (e: Event) => {
if (isFpvActiveRef.current) return;
const { type, direction } = (e as CustomEvent).detail as {
type: CameraActionType;
direction: number;
};
const state = getOrCreate(type, direction);
state.direction = direction;
state.held = true;
state.impulseEnd = performance.now() + MINIMUM_IMPULSE_DURATION_MS;
if (type === "bearing") {
isInteractingRef.current = true;
if (idleTimerRef.current) clearTimeout(idleTimerRef.current);
}
ensureLoop();
};
const onStop = (e: Event) => {
const { type } = (e as CustomEvent).detail as { type: CameraActionType };
const state = actions.get(type);
if (state) state.held = false;
};
window.addEventListener("aeris:camera-start", onStart);
window.addEventListener("aeris:camera-stop", onStop);
return () => {
window.removeEventListener("aeris:camera-start", onStart);
window.removeEventListener("aeris:camera-stop", onStop);
if (frameId != null) cancelAnimationFrame(frameId);
};
}, [map, isLoaded]);
}

View File

@ -0,0 +1,121 @@
"use client";
import { useEffect, useRef, type MutableRefObject } from "react";
import type maplibregl from "maplibre-gl";
import { smoothstep } from "./camera-controller-utils";
import type { City } from "@/lib/cities";
import type { FlightState } from "@/lib/opensky";
import type { Settings } from "@/hooks/use-settings";
const IDLE_TIMEOUT_MS = 5_000;
const ORBIT_EASE_IN_MS = 2000;
export function useOrbitCamera(
map: maplibregl.Map | null,
isLoaded: boolean,
city: City,
followFlight: FlightState | null | undefined,
fpvFlight: FlightState | null | undefined,
settings: Settings,
isInteractingRef: MutableRefObject<boolean>,
orbitFrameRef: MutableRefObject<number | null>,
idleTimerRef: MutableRefObject<ReturnType<typeof setTimeout> | null>,
) {
// Store speed in a ref so tick() reads the latest value without effect re-runs
const speedRef = useRef(0);
useEffect(() => {
speedRef.current =
settings.orbitSpeed * (settings.orbitDirection === "clockwise" ? 1 : -1);
}, [settings.orbitSpeed, settings.orbitDirection]);
useEffect(() => {
if (
!map ||
!isLoaded ||
!city ||
!settings.autoOrbit ||
followFlight ||
fpvFlight
) {
if (orbitFrameRef.current) cancelAnimationFrame(orbitFrameRef.current);
if (idleTimerRef.current) clearTimeout(idleTimerRef.current);
return;
}
const prefersReducedMotion =
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;
if (prefersReducedMotion) return;
function startOrbit() {
if (!map || isInteractingRef.current) return;
const resumeStart = performance.now();
function tick() {
if (!map || isInteractingRef.current) return;
const resumeElapsed = performance.now() - resumeStart;
const t = Math.min(resumeElapsed / ORBIT_EASE_IN_MS, 1);
const easeFactor = smoothstep(t);
const bearing = map.getBearing() + speedRef.current * easeFactor;
map.setBearing(bearing % 360);
orbitFrameRef.current = requestAnimationFrame(tick);
}
orbitFrameRef.current = requestAnimationFrame(tick);
}
function stopOrbit() {
if (orbitFrameRef.current) {
cancelAnimationFrame(orbitFrameRef.current);
orbitFrameRef.current = null;
}
}
function resetIdleTimer() {
isInteractingRef.current = true;
stopOrbit();
if (idleTimerRef.current) clearTimeout(idleTimerRef.current);
idleTimerRef.current = setTimeout(() => {
isInteractingRef.current = false;
startOrbit();
}, IDLE_TIMEOUT_MS);
}
const events = ["mousedown", "wheel", "touchstart"] as const;
const container = map.getContainer();
events.forEach((e) =>
container.addEventListener(e, resetIdleTimer, { passive: true }),
);
const onMoveStart = () => {
if (isInteractingRef.current) stopOrbit();
};
map.on("movestart", onMoveStart);
const onCameraStop = (e: Event) => {
const { type } = (e as CustomEvent).detail ?? {};
if (type === "bearing") {
if (idleTimerRef.current) clearTimeout(idleTimerRef.current);
idleTimerRef.current = setTimeout(() => {
isInteractingRef.current = false;
startOrbit();
}, IDLE_TIMEOUT_MS);
}
};
window.addEventListener("aeris:camera-stop", onCameraStop);
idleTimerRef.current = setTimeout(() => {
isInteractingRef.current = false;
startOrbit();
}, IDLE_TIMEOUT_MS);
return () => {
stopOrbit();
if (idleTimerRef.current) clearTimeout(idleTimerRef.current);
events.forEach((e) => container.removeEventListener(e, resetIdleTimer));
map.off("movestart", onMoveStart);
window.removeEventListener("aeris:camera-stop", onCameraStop);
};
}, [map, isLoaded, city, followFlight, fpvFlight, settings.autoOrbit]);
}

View File

@ -0,0 +1,406 @@
"use client";
import { useState, useCallback, useEffect, useRef, memo } from "react";
import { createPortal } from "react-dom";
import { motion, AnimatePresence } from "motion/react";
import {
Camera,
ChevronLeft,
ChevronRight,
X,
Plane,
ImageOff,
} from "lucide-react";
import type {
NormalizedPhoto,
AircraftDetails,
} from "@/hooks/use-aircraft-photos";
const Thumbnail = memo(function Thumbnail({
photo,
index,
onClick,
}: {
photo: NormalizedPhoto;
index: number;
onClick: (index: number) => void;
}) {
const ref = useRef<HTMLButtonElement>(null);
const [loaded, setLoaded] = useState(false);
const [failed, setFailed] = useState(false);
const [visible, setVisible] = useState(false);
useEffect(() => {
const el = ref.current;
if (!el) return;
const observer = new IntersectionObserver(
([entry]) => {
if (entry?.isIntersecting) {
setVisible(true);
observer.disconnect();
}
},
{ rootMargin: "100px" },
);
observer.observe(el);
return () => observer.disconnect();
}, []);
if (failed) return null;
return (
<button
ref={ref}
type="button"
onClick={() => onClick(index)}
className="group relative h-16 w-24 shrink-0 cursor-pointer overflow-hidden rounded-lg border border-white/8 bg-white/5 transition-all hover:border-white/20 hover:brightness-110 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-white/30"
aria-label={`View photo ${index + 1}${photo.photographer ? ` by ${photo.photographer}` : ""}`}
>
{!loaded && (
<span
aria-hidden
className="absolute inset-0 animate-pulse bg-linear-to-br from-white/5 via-white/8 to-white/5"
/>
)}
{visible && (
<img
src={photo.thumbnail}
alt={`Aircraft photo ${index + 1}`}
loading="lazy"
decoding="async"
onLoad={() => setLoaded(true)}
onError={() => setFailed(true)}
className={`h-full w-full object-cover transition-opacity duration-300 ${loaded ? "opacity-100" : "opacity-0"}`}
/>
)}
<span className="pointer-events-none absolute inset-0 rounded-lg ring-1 ring-inset ring-white/5 group-hover:ring-white/15" />
</button>
);
});
export function Lightbox({
photos,
index,
onClose,
onNavigate,
}: {
photos: NormalizedPhoto[];
index: number;
onClose: () => void;
onNavigate: (index: number) => void;
}) {
const photo = photos[index];
const [loaded, setLoaded] = useState(false);
const [imgError, setImgError] = useState(false);
useEffect(() => {
setLoaded(false);
setImgError(false);
}, [index]);
const goPrev = useCallback(() => {
onNavigate(index > 0 ? index - 1 : photos.length - 1);
}, [index, photos.length, onNavigate]);
const goNext = useCallback(() => {
onNavigate(index < photos.length - 1 ? index + 1 : 0);
}, [index, photos.length, onNavigate]);
useEffect(() => {
function handleKey(e: globalThis.KeyboardEvent) {
if (e.key === "Escape") onClose();
else if (e.key === "ArrowLeft") goPrev();
else if (e.key === "ArrowRight") goNext();
}
window.addEventListener("keydown", handleKey);
return () => window.removeEventListener("keydown", handleKey);
}, [goPrev, goNext, onClose]);
if (!photo) return null;
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.3, ease: "easeOut" }}
className="fixed inset-0 z-9999 flex items-center justify-center bg-black/92 backdrop-blur-2xl"
onClick={onClose}
role="dialog"
aria-modal="true"
aria-label="Aircraft photo viewer"
>
<button
type="button"
onClick={onClose}
className="absolute right-3 top-3 z-10 flex h-11 w-11 items-center justify-center rounded-full bg-white/10 text-white/80 backdrop-blur-sm transition-all duration-200 hover:bg-white/20 hover:text-white sm:right-6 sm:top-6 sm:h-12 sm:w-12"
aria-label="Close photo viewer"
>
<X className="h-5 w-5 sm:h-6 sm:w-6" />
</button>
<span className="absolute left-3 top-3 z-10 rounded-full bg-white/10 px-4 py-2 text-sm font-semibold tabular-nums text-white/80 backdrop-blur-sm sm:left-6 sm:top-6 sm:px-5 sm:text-base">
{index + 1} / {photos.length}
</span>
<motion.div
key={index}
initial={{ opacity: 0, scale: 0.97 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.25, ease: "easeOut" }}
className="relative flex max-h-[85vh] max-w-[94vw] items-center justify-center sm:max-w-[90vw]"
onClick={(e) => e.stopPropagation()}
>
{!loaded && !imgError && (
<div className="flex h-48 w-72 items-center justify-center sm:h-64 sm:w-96">
<div className="h-9 w-9 animate-spin rounded-full border-2 border-white/20 border-t-white/60" />
</div>
)}
{imgError ? (
<div className="flex h-48 w-72 flex-col items-center justify-center gap-3 rounded-2xl border border-white/10 bg-white/5 sm:h-64 sm:w-96">
<Camera className="h-8 w-8 text-white/20" />
<p className="text-sm text-white/40">Failed to load image</p>
</div>
) : (
<img
src={photo.url}
alt={`Aircraft photo ${index + 1}${photo.photographer ? ` by ${photo.photographer}` : ""}`}
onLoad={() => setLoaded(true)}
onError={() => setImgError(true)}
className={`max-h-[85vh] max-w-[94vw] rounded-xl object-contain shadow-2xl transition-opacity duration-300 sm:max-w-[90vw] ${loaded ? "opacity-100" : "opacity-0"}`}
draggable={false}
/>
)}
</motion.div>
{photos.length > 1 && (
<>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
goPrev();
}}
className="absolute left-2 top-1/2 z-10 flex h-12 w-12 -translate-y-1/2 items-center justify-center rounded-full bg-white/10 text-white/80 backdrop-blur-sm transition-all duration-200 hover:bg-white/25 hover:text-white sm:left-6 sm:h-14 sm:w-14"
aria-label="Previous photo"
>
<ChevronLeft className="h-6 w-6 sm:h-7 sm:w-7" />
</button>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
goNext();
}}
className="absolute right-2 top-1/2 z-10 flex h-12 w-12 -translate-y-1/2 items-center justify-center rounded-full bg-white/10 text-white/80 backdrop-blur-sm transition-all duration-200 hover:bg-white/25 hover:text-white sm:right-6 sm:h-14 sm:w-14"
aria-label="Next photo"
>
<ChevronRight className="h-6 w-6 sm:h-7 sm:w-7" />
</button>
</>
)}
{(photo.photographer || photo.location || photo.dateTaken) && (
<motion.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay: 0.15 }}
className="absolute bottom-3 left-1/2 z-10 w-[92vw] max-w-lg -translate-x-1/2 sm:bottom-8"
>
<span className="flex flex-wrap items-center justify-center gap-x-3 gap-y-1 rounded-xl bg-black/60 px-5 py-3 text-sm text-white/70 backdrop-blur-sm sm:text-base">
{photo.photographer && (
<span className="font-medium text-white/85">
{photo.photographer}
</span>
)}
{photo.photographer && photo.location && (
<span className="text-white/25">|</span>
)}
{photo.location && (
<span className="text-white/55">{photo.location}</span>
)}
{(photo.photographer || photo.location) && photo.dateTaken && (
<span className="text-white/25">|</span>
)}
{photo.dateTaken && (
<span className="text-white/45">{photo.dateTaken}</span>
)}
</span>
</motion.div>
)}
</motion.div>
);
}
type AircraftPhotosProps = {
photos: NormalizedPhoto[];
loading: boolean;
aircraft: AircraftDetails | null;
error: boolean;
onPhotoClick?: (index: number) => void;
defaultExpanded?: boolean;
hideEmptyState?: boolean;
};
export function AircraftPhotos({
photos,
loading,
aircraft,
error,
onPhotoClick,
defaultExpanded = false,
hideEmptyState = false,
}: AircraftPhotosProps) {
const [expanded, setExpanded] = useState(defaultExpanded);
const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const handlePhotoClick = useCallback(
(index: number) => {
if (onPhotoClick) {
onPhotoClick(index);
} else {
setLightboxIndex(index);
}
},
[onPhotoClick],
);
const closeLightbox = useCallback(() => {
setLightboxIndex(null);
}, []);
const hasPhotos = photos.length > 0;
const hasAircraft = aircraft !== null;
const showSection = hideEmptyState
? loading || hasPhotos
: loading || hasPhotos || hasAircraft;
if (!showSection) return null;
const detailParts: string[] = [];
if (aircraft?.manufacturer) detailParts.push(aircraft.manufacturer);
if (aircraft?.type) detailParts.push(aircraft.type);
if (aircraft?.airline && !detailParts.includes(aircraft.airline)) {
detailParts.push(aircraft.airline);
}
const detailLine = detailParts.join(" · ");
return (
<>
<div className="mt-3">
<div className="h-px bg-linear-to-r from-transparent via-white/6 to-transparent" />
<button
type="button"
onClick={() => setExpanded((v) => !v)}
className="mt-2.5 flex w-full items-center gap-1.5 text-left"
aria-expanded={expanded}
aria-controls="aircraft-photo-strip"
>
<Camera className="h-3 w-3 text-white/25" />
<span className="text-[10px] font-medium tracking-wider text-white/30 uppercase">
{loading ? "Loading…" : hasPhotos ? "Photos" : "Aircraft"}
</span>
{hasPhotos && (
<span className="text-[10px] tabular-nums text-white/20">
({photos.length})
</span>
)}
{aircraft?.registration && (
<span className="ml-auto text-[10px] font-mono tracking-wider text-white/20">
{aircraft.registration}
</span>
)}
<ChevronRight
className={`h-2.5 w-2.5 text-white/20 transition-transform duration-200 ${expanded ? "rotate-90" : ""}`}
/>
</button>
<AnimatePresence initial={false}>
{expanded && (
<motion.div
id="aircraft-photo-strip"
initial={{ height: 0, opacity: 0 }}
animate={{ height: "auto", opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ duration: 0.2, ease: "easeInOut" }}
className="overflow-hidden"
>
{loading && (
<div className="mt-2 flex gap-2 overflow-hidden">
{[0, 1, 2].map((i) => (
<div
key={i}
className="h-16 w-24 shrink-0 animate-pulse rounded-lg bg-white/5"
/>
))}
</div>
)}
{!loading && hasPhotos && (
<div
ref={scrollRef}
className="mt-2 flex gap-2 overflow-x-auto pb-1 scrollbar-none"
style={{ scrollbarWidth: "none" }}
>
{photos.map((photo, i) => (
<Thumbnail
key={photo.id}
photo={photo}
index={i}
onClick={handlePhotoClick}
/>
))}
</div>
)}
{!loading && !hasPhotos && hasAircraft && (
<div className="mt-2 flex items-center gap-2 rounded-lg border border-white/6 bg-white/2 px-3 py-2.5">
<Plane className="h-3.5 w-3.5 shrink-0 text-white/20" />
<div className="min-w-0 flex-1">
{detailLine && (
<p className="truncate text-[11px] font-medium text-white/45">
{detailLine}
</p>
)}
<p className="mt-0.5 flex items-center gap-1 text-[10px] text-white/25">
<ImageOff className="h-2.5 w-2.5" />
No photos available
</p>
</div>
</div>
)}
{!loading && !hasPhotos && !hasAircraft && error && (
<div className="mt-2 flex items-center gap-2 px-1 py-1.5">
<ImageOff className="h-3 w-3 text-white/15" />
<p className="text-[10px] text-white/25">
Could not load aircraft data
</p>
</div>
)}
</motion.div>
)}
</AnimatePresence>
</div>
{!onPhotoClick &&
typeof document !== "undefined" &&
createPortal(
<AnimatePresence>
{lightboxIndex !== null && (
<Lightbox
photos={photos}
index={lightboxIndex}
onClose={closeLightbox}
onNavigate={setLightboxIndex}
/>
)}
</AnimatePresence>,
document.body,
)}
</>
);
}

View File

@ -0,0 +1,768 @@
"use client";
import { useState, useMemo, useCallback, useRef, useEffect } from "react";
import { Command } from "cmdk";
import {
Search,
X,
MapPin,
Plane,
Eye,
Loader2,
Clock,
Trash2,
Gauge,
ArrowUpRight,
Globe2,
} from "lucide-react";
import { CITIES, type City } from "@/lib/cities";
import { searchAirports, airportToCity } from "@/lib/airports";
import type { FlightState } from "@/lib/opensky";
import {
formatCallsign,
altitudeToColor,
metersToFeet,
msToKnots,
headingToCardinal,
} from "@/lib/flight-utils";
// ── Recent searches (localStorage) ─────────────────────────────────────
const RECENT_KEY = "aeris:recent-searches";
const RECENT_MAX = 4;
const RECENT_EXPIRY_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
type RecentEntry = { q: string; ts: number };
function getRecents(): string[] {
try {
const raw = localStorage.getItem(RECENT_KEY);
if (!raw) return [];
const parsed: unknown = JSON.parse(raw);
if (!Array.isArray(parsed)) return [];
const now = Date.now();
const valid = parsed
.filter(
(e): e is RecentEntry =>
typeof e === "object" &&
e !== null &&
typeof e.q === "string" &&
typeof e.ts === "number" &&
now - e.ts < RECENT_EXPIRY_MS,
)
.slice(0, RECENT_MAX);
if (valid.length !== parsed.length) {
localStorage.setItem(RECENT_KEY, JSON.stringify(valid));
}
return valid.map((e) => e.q);
} catch {
return [];
}
}
function addRecent(query: string) {
const q = query.trim();
if (!q || q.length > 100) return;
try {
const raw = localStorage.getItem(RECENT_KEY);
const prev: RecentEntry[] = raw ? (JSON.parse(raw) ?? []) : [];
const filtered = (Array.isArray(prev) ? prev : []).filter(
(e): e is RecentEntry =>
typeof e === "object" &&
e !== null &&
typeof e.q === "string" &&
e.q.toLowerCase() !== q.toLowerCase(),
);
const next = [{ q, ts: Date.now() }, ...filtered].slice(0, RECENT_MAX);
localStorage.setItem(RECENT_KEY, JSON.stringify(next));
} catch {
/* quota exceeded — ignore */
}
}
function removeRecent(query: string) {
try {
const raw = localStorage.getItem(RECENT_KEY);
const prev: RecentEntry[] = raw ? (JSON.parse(raw) ?? []) : [];
const next = (Array.isArray(prev) ? prev : []).filter(
(e): e is RecentEntry =>
typeof e === "object" &&
e !== null &&
typeof e.q === "string" &&
e.q.toLowerCase() !== query.toLowerCase(),
);
localStorage.setItem(RECENT_KEY, JSON.stringify(next));
} catch {
/* ignore */
}
}
function clearRecents() {
try {
localStorage.removeItem(RECENT_KEY);
} catch {
/* ignore */
}
}
// ── Highlight matched text safely ──────────────────────────────────────
function HighlightMatch({ text, query }: { text: string; query: string }) {
if (!query) return <>{text}</>;
const q = query.trim().toLowerCase();
if (!q) return <>{text}</>;
const idx = text.toLowerCase().indexOf(q);
if (idx === -1) return <>{text}</>;
return (
<>
{text.slice(0, idx)}
<span className="text-white/95 font-semibold">
{text.slice(idx, idx + q.length)}
</span>
{text.slice(idx + q.length)}
</>
);
}
// ── Altitude color dot ─────────────────────────────────────────────────
function AltitudeDot({ altitude }: { altitude: number | null }) {
const [r, g, b] = altitudeToColor(altitude);
return (
<span
className="inline-block h-2 w-2 rounded-full shrink-0"
style={{ backgroundColor: `rgb(${r},${g},${b})` }}
aria-label={
altitude != null
? `Altitude: ${Math.round(altitude)}m`
: "Unknown altitude"
}
/>
);
}
// ── Country code to flag emoji ─────────────────────────────────────────
function countryFlag(countryName: string): string {
const COUNTRY_ISO: Record<string, string> = {
"united states": "US",
usa: "US",
us: "US",
"united kingdom": "GB",
uk: "GB",
gb: "GB",
germany: "DE",
france: "FR",
spain: "ES",
italy: "IT",
canada: "CA",
australia: "AU",
japan: "JP",
china: "CN",
india: "IN",
brazil: "BR",
russia: "RU",
mexico: "MX",
"south korea": "KR",
netherlands: "NL",
switzerland: "CH",
sweden: "SE",
norway: "NO",
denmark: "DK",
ireland: "IE",
portugal: "PT",
austria: "AT",
belgium: "BE",
turkey: "TR",
thailand: "TH",
singapore: "SG",
malaysia: "MY",
indonesia: "ID",
philippines: "PH",
"united arab emirates": "AE",
"saudi arabia": "SA",
qatar: "QA",
israel: "IL",
"south africa": "ZA",
egypt: "EG",
"new zealand": "NZ",
argentina: "AR",
chile: "CL",
colombia: "CO",
peru: "PE",
poland: "PL",
czechia: "CZ",
"czech republic": "CZ",
romania: "RO",
greece: "GR",
finland: "FI",
vietnam: "VN",
taiwan: "TW",
"hong kong": "HK",
pakistan: "PK",
bangladesh: "BD",
ukraine: "UA",
hungary: "HU",
morocco: "MA",
nigeria: "NG",
kenya: "KE",
iceland: "IS",
luxembourg: "LU",
croatia: "HR",
serbia: "RS",
bulgaria: "BG",
slovakia: "SK",
slovenia: "SI",
estonia: "EE",
latvia: "LV",
lithuania: "LT",
malta: "MT",
cyprus: "CY",
};
const key = countryName.trim().toLowerCase();
const iso = COUNTRY_ISO[key];
if (!iso) return "";
// Convert ISO code to flag emoji using regional indicator symbols
return String.fromCodePoint(
...iso.split("").map((c) => 0x1f1e6 + c.charCodeAt(0) - 65),
);
}
// ── Main SearchContent ─────────────────────────────────────────────────
export function SearchContent({
activeCity,
onSelect,
flights,
activeFlightIcao24,
onLookupFlight,
}: {
activeCity: City;
onSelect: (city: City) => void;
flights: FlightState[];
activeFlightIcao24: string | null;
onLookupFlight: (query: string, enterFpv?: boolean) => Promise<boolean>;
}) {
const [query, setQuery] = useState("");
const [lookupBusy, setLookupBusy] = useState(false);
const [lookupError, setLookupError] = useState<string | null>(null);
const [recents, setRecents] = useState<string[]>([]);
const inputRef = useRef<HTMLInputElement>(null);
const listRef = useRef<HTMLDivElement>(null);
// Load recents on mount
useEffect(() => {
setRecents(getRecents());
}, []);
// Auto-focus with a frame delay for dialog mounting
useEffect(() => {
requestAnimationFrame(() => inputRef.current?.focus());
}, []);
// Live search results
const { featured, airports } = useMemo(() => {
const q = query.trim().toLowerCase();
if (!q)
return {
featured: CITIES,
airports: [] as ReturnType<typeof searchAirports>,
};
const featured = CITIES.filter(
(c) =>
c.name.toLowerCase().includes(q) ||
c.iata.toLowerCase().includes(q) ||
c.country.toLowerCase().includes(q),
);
const featuredIatas = new Set(CITIES.map((c) => c.iata));
const airports = searchAirports(q).filter(
(a) => !featuredIatas.has(a.iata),
);
return { featured, airports };
}, [query]);
const compactQuery = query.trim().toLowerCase().replace(/\s+/g, "");
const isIcao24Query = /^[0-9a-f]{6}$/.test(compactQuery);
const flightMatches = useMemo(() => {
if (!compactQuery) return [] as FlightState[];
return flights
.filter((flight) => {
const icao = flight.icao24.toLowerCase();
const callsign = (flight.callsign ?? "")
.trim()
.toLowerCase()
.replace(/\s+/g, "");
return icao.includes(compactQuery) || callsign.includes(compactQuery);
})
.slice(0, 15);
}, [flights, compactQuery]);
const hasResults =
featured.length > 0 || airports.length > 0 || flightMatches.length > 0;
const showRecents = !query && recents.length > 0;
// Total result count for screen reader
const totalResults = flightMatches.length + featured.length + airports.length;
// ── Actions ────────────────────────────────────────────────────────
const runLookup = useCallback(
async (enterFpv = false) => {
if (!query.trim() || lookupBusy) return;
setLookupBusy(true);
setLookupError(null);
addRecent(query.trim());
setRecents(getRecents());
try {
const found = await onLookupFlight(query, enterFpv);
if (!found) {
setLookupError(
isIcao24Query
? "Flight not found for this ICAO24 right now"
: 'No live flight match found — try a callsign like "UAL123" or ICAO24 hex',
);
}
} finally {
setLookupBusy(false);
}
},
[query, lookupBusy, onLookupFlight, isIcao24Query],
);
const openFlight = useCallback(
async (icao24: string, enterFpv = false) => {
if (lookupBusy) return;
setLookupBusy(true);
setLookupError(null);
addRecent(icao24.toUpperCase());
setRecents(getRecents());
try {
const found = await onLookupFlight(icao24, enterFpv);
if (!found) setLookupError("Unable to open the selected flight");
} finally {
setLookupBusy(false);
}
},
[lookupBusy, onLookupFlight],
);
const handleRemoveRecent = useCallback((q: string) => {
removeRecent(q);
setRecents(getRecents());
}, []);
const handleClearRecents = useCallback(() => {
clearRecents();
setRecents([]);
}, []);
// ── Custom cmdk filter ─────────────────────────────────────────────
const cmdkFilter = useCallback(
(value: string, search: string, keywords?: string[]) => {
if (!search) return 1;
const s = search.toLowerCase().replace(/\s+/g, "");
const v = value.toLowerCase();
const kw = keywords ? keywords.join(" ").toLowerCase() : "";
const combined = `${v} ${kw}`;
if (v === s) return 1;
if (v.startsWith(s)) return 0.95;
if (kw && kw.startsWith(s)) return 0.9;
const words = combined.split(/[\s·,]+/);
for (const w of words) {
if (w.startsWith(s)) return 0.8;
}
if (combined.includes(s)) return 0.6;
return 0;
},
[],
);
return (
<Command
className="flex h-full flex-col aeris-cmdk"
filter={cmdkFilter}
loop
label="Search airports, flights, and cities"
>
{/* ── Search input ──────────────────────────────────────────── */}
<div className="flex items-center gap-2.5 border-b border-white/6 mx-3 sm:mx-5 pb-3">
<Search className="h-3.5 w-3.5 shrink-0 text-white/25" />
<Command.Input
ref={inputRef}
value={query}
onValueChange={(v) => {
setQuery(v);
setLookupError(null);
}}
onKeyDown={(e) => {
if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
void runLookup(true);
}
}}
placeholder="Search airports, flights, ICAO24…"
aria-label="Search airports, flights, and cities"
className="flex-1 bg-transparent text-[14px] font-medium text-white/90 placeholder:text-white/20 outline-none"
/>
{query && (
<button
onClick={() => setQuery("")}
className="shrink-0 text-white/20 hover:text-white/40 transition-colors"
aria-label="Clear search"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
{/* ── Error banner ──────────────────────────────────────────── */}
{lookupError && (
<div className="mx-3 sm:mx-5 mt-2 flex items-start gap-2 rounded-lg border border-amber-500/15 bg-amber-500/5 px-3 py-2">
<span className="mt-px text-[11px] font-medium text-amber-300/85 leading-snug">
{lookupError}
</span>
</div>
)}
{/* ── Result list ───────────────────────────────────────────── */}
<Command.List
ref={listRef}
className="flex-1 overflow-y-auto overflow-x-hidden scrollbar-none p-2"
>
<Command.Empty className="flex flex-col items-center justify-center py-10 gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-2xl bg-white/4">
<Globe2 className="h-5 w-5 text-white/15" />
</div>
<div className="text-center space-y-1">
<p className="text-[13px] font-medium text-white/30">
No results found
</p>
<p className="text-[11px] text-white/15 max-w-55 leading-relaxed">
Try an airport code like &quot;JFK&quot;, a city name, or a flight
callsign like &quot;UAL123&quot;
</p>
</div>
</Command.Empty>
{/* ── Recent searches ───────────────────────────────────── */}
{showRecents && (
<Command.Group
heading={
<div className="flex items-center justify-between">
<span>Recent</span>
<button
onClick={handleClearRecents}
className="text-[9px] font-medium text-white/20 hover:text-white/40 transition-colors normal-case tracking-normal"
>
Clear all
</button>
</div>
}
>
{recents.map((r) => (
<Command.Item
key={`recent-${r}`}
value={`recent:${r}`}
keywords={[r]}
onSelect={() => {
setQuery(r);
inputRef.current?.focus();
}}
className="search-item"
>
<div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-white/3">
<Clock className="h-3 w-3 text-white/25" />
</div>
<span className="flex-1 truncate text-[13px] font-medium text-white/50">
{r}
</span>
<button
onClick={(e) => {
e.stopPropagation();
handleRemoveRecent(r);
}}
className="shrink-0 opacity-0 group-data-[selected=true]/item:opacity-100 text-white/20 hover:text-white/40 transition-all"
aria-label={`Remove ${r} from recent searches`}
>
<Trash2 className="h-3 w-3" />
</button>
</Command.Item>
))}
</Command.Group>
)}
{/* ── Worldwide lookup action ───────────────────────────── */}
{compactQuery && (
<Command.Group heading="Actions">
<Command.Item
value={`lookup:${query}`}
keywords={[query]}
onSelect={() => void runLookup(false)}
disabled={lookupBusy}
className="search-item"
>
<div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-white/4">
{lookupBusy ? (
<Loader2 className="h-3.5 w-3.5 animate-spin text-white/40" />
) : (
<Search className="h-3.5 w-3.5 text-white/40" />
)}
</div>
<div className="flex-1 min-w-0">
<p className="truncate text-[13px] font-medium text-white/70">
Search worldwide for &quot;{query.trim()}&quot;
</p>
<p className="text-[10px] text-white/25">
{isIcao24Query
? "ICAO24 hex lookup"
: "Callsign / flight number lookup"}
</p>
</div>
<kbd className="hidden sm:inline-flex h-5 items-center rounded border border-white/8 bg-white/4 px-1.5 text-[9px] font-semibold text-white/25">
</kbd>
</Command.Item>
<Command.Item
value={`fpv:${query}`}
keywords={[query, "fpv", "first person"]}
onSelect={() => void runLookup(true)}
disabled={lookupBusy}
className="search-item"
>
<div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-sky-500/10 border border-sky-400/15">
{lookupBusy ? (
<Loader2 className="h-3.5 w-3.5 animate-spin text-sky-300/60" />
) : (
<Eye className="h-3.5 w-3.5 text-sky-300/70" />
)}
</div>
<div className="flex-1 min-w-0">
<p className="truncate text-[13px] font-medium text-sky-200/70">
Open in FPV mode
</p>
<p className="text-[10px] text-sky-300/25">
Follow camera view
</p>
</div>
<kbd className="hidden sm:inline-flex h-5 items-center gap-0.5 rounded border border-white/8 bg-white/4 px-1.5 text-[9px] font-semibold text-white/25">
<span className="text-[8px]"></span>
</kbd>
</Command.Item>
</Command.Group>
)}
{/* ── Live flights ──────────────────────────────────────── */}
{flightMatches.length > 0 && (
<Command.Group heading="Live Flights">
{flightMatches.map((flight) => {
const cs = formatCallsign(flight.callsign);
const flag = countryFlag(flight.originCountry);
return (
<Command.Item
key={flight.icao24}
value={`flight:${flight.icao24}:${cs}`}
keywords={[flight.icao24, cs, flight.originCountry]}
onSelect={() => void openFlight(flight.icao24, false)}
className="search-item"
>
<div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-white/4">
<Plane className="h-3.5 w-3.5 text-white/40" />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5">
<p className="truncate text-[13px] font-semibold text-white/80">
<HighlightMatch text={cs} query={query} />
</p>
{activeFlightIcao24 === flight.icao24 && (
<span className="shrink-0 rounded-full bg-emerald-500/15 border border-emerald-400/20 px-1.5 py-px text-[8px] font-bold uppercase tracking-wider text-emerald-300/80">
Active
</span>
)}
</div>
<div className="flex items-center gap-1.5 text-[10px] text-white/25">
<span className="font-mono">
<HighlightMatch
text={flight.icao24.toUpperCase()}
query={query}
/>
</span>
<span className="text-white/10">·</span>
{flag && <span className="text-[10px]">{flag}</span>}
<span>{flight.originCountry}</span>
</div>
</div>
{/* Flight info chips */}
<div className="flex items-center gap-1.5 shrink-0">
{flight.baroAltitude != null && (
<span className="inline-flex items-center gap-1 rounded-md bg-white/3 px-1.5 py-0.5 text-[9px] font-medium text-white/30">
<AltitudeDot altitude={flight.baroAltitude} />
{metersToFeet(flight.baroAltitude)}
</span>
)}
{flight.velocity != null && (
<span className="inline-flex items-center gap-1 rounded-md bg-white/3 px-1.5 py-0.5 text-[9px] font-medium text-white/30">
<Gauge className="h-2.5 w-2.5 text-white/20" />
{msToKnots(flight.velocity)}
</span>
)}
{flight.trueTrack != null && (
<span className="inline-flex items-center gap-1 rounded-md bg-white/3 px-1.5 py-0.5 text-[9px] font-medium text-white/30">
<ArrowUpRight
className="h-2.5 w-2.5 text-white/20"
style={{
transform: `rotate(${flight.trueTrack - 45}deg)`,
}}
/>
{headingToCardinal(flight.trueTrack)}
</span>
)}
</div>
{/* FPV button — visible on hover/keyboard-select */}
{!flight.onGround && (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
void openFlight(flight.icao24, true);
}}
className="shrink-0 opacity-0 group-data-[selected=true]/item:opacity-100 inline-flex h-6 items-center gap-1 rounded-md border border-sky-400/20 bg-sky-500/10 px-1.5 text-[9px] font-semibold uppercase tracking-wide text-sky-300/80 transition-all hover:bg-sky-500/20"
aria-label={`Open ${cs} in FPV`}
>
<Eye className="h-2.5 w-2.5" />
FPV
</button>
)}
</Command.Item>
);
})}
</Command.Group>
)}
{/* ── Featured cities ───────────────────────────────────── */}
{featured.length > 0 && (
<Command.Group
heading={query ? "Featured Cities" : "Popular Airports"}
>
{featured.map((city) => (
<Command.Item
key={city.id}
value={`city:${city.id}:${city.name}`}
keywords={[city.name, city.iata, city.country]}
onSelect={() => onSelect(city)}
className="search-item"
>
<div
className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-lg ${
activeCity?.id === city.id ? "bg-white/8" : "bg-white/4"
}`}
>
<MapPin
className={`h-3.5 w-3.5 ${
activeCity?.id === city.id
? "text-white/60"
: "text-white/35"
}`}
/>
</div>
<div className="flex-1 min-w-0">
<p className="truncate text-[13px] font-medium text-white/80">
<HighlightMatch text={city.name} query={query} />
</p>
<p className="text-[10px] font-medium text-white/25">
<HighlightMatch text={city.iata} query={query} />
<span className="text-white/10"> · </span>
{city.country}
</p>
</div>
{activeCity?.id === city.id && (
<span className="shrink-0 rounded-full bg-white/6 px-1.5 py-px text-[8px] font-bold uppercase tracking-wider text-white/30">
Current
</span>
)}
</Command.Item>
))}
</Command.Group>
)}
{/* ── Airport results ───────────────────────────────────── */}
{airports.length > 0 && (
<Command.Group heading="Airports">
{airports.map((airport) => (
<Command.Item
key={airport.iata}
value={`airport:${airport.iata}:${airport.name}`}
keywords={[
airport.iata,
airport.city,
airport.country,
airport.name,
]}
onSelect={() => onSelect(airportToCity(airport))}
className="search-item"
>
<div
className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-lg ${
activeCity?.iata === airport.iata
? "bg-white/8"
: "bg-white/4"
}`}
>
<MapPin
className={`h-3.5 w-3.5 ${
activeCity?.iata === airport.iata
? "text-white/60"
: "text-white/35"
}`}
/>
</div>
<div className="flex-1 min-w-0">
<p className="truncate text-[13px] font-medium text-white/80">
<HighlightMatch text={airport.name} query={query} />
</p>
<p className="text-[10px] font-medium text-white/25">
<HighlightMatch text={airport.iata} query={query} />
<span className="text-white/10"> · </span>
<HighlightMatch text={airport.city} query={query} />,{" "}
{airport.country}
</p>
</div>
{activeCity?.iata === airport.iata && (
<span className="shrink-0 rounded-full bg-white/6 px-1.5 py-px text-[8px] font-bold uppercase tracking-wider text-white/30">
Current
</span>
)}
</Command.Item>
))}
</Command.Group>
)}
{/* ── SR-only result count ──────────────────────────────── */}
<div className="sr-only" aria-live="polite" role="status">
{query
? `${totalResults} result${totalResults !== 1 ? "s" : ""} found`
: `${CITIES.length} featured airports`}
</div>
{/* ── Footer hint ───────────────────────────────────────── */}
{!query && !showRecents && (
<div className="flex items-center justify-center gap-2 py-4">
<p className="text-[10px] text-white/12 font-medium">
Search 9,000+ airports worldwide
</p>
</div>
)}
</Command.List>
</Command>
);
}

View File

@ -0,0 +1,538 @@
"use client";
import type { ReactNode } from "react";
import { motion } from "motion/react";
import {
RotateCw,
Route,
Layers,
Palette,
Globe,
ArrowLeftRight,
} from "lucide-react";
import { useSettings, type OrbitDirection } from "@/hooks/use-settings";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Slider } from "@/components/ui/slider";
import { SHORTCUTS } from "@/components/ui/keyboard-shortcuts-help";
const ORBIT_SPEED_PRESETS = [
{ label: "Slow", value: 0.06 },
{ label: "Normal", value: 0.15 },
{ label: "Fast", value: 0.35 },
];
const ORBIT_SPEED_MIN = 0.02;
const ORBIT_SPEED_MAX = 0.5;
const ORBIT_SNAP_THRESHOLD = 0.025;
const TRAIL_THICKNESS_MIN = 0.5;
const TRAIL_THICKNESS_MAX = 8;
const TRAIL_DISTANCE_MIN = 12;
const TRAIL_DISTANCE_MAX = 100;
const ORBIT_DIRECTIONS: { label: string; value: OrbitDirection }[] = [
{ label: "Clockwise", value: "clockwise" },
{ label: "Counter", value: "counter-clockwise" },
];
export function SettingsContent() {
const { settings, update, reset } = useSettings();
return (
<ScrollArea className="h-full">
<div className="space-y-0.5 p-3 pt-1">
<SettingRow
icon={<RotateCw className="h-4 w-4" />}
title="Auto-orbit"
description="Camera slowly rotates around the airport"
checked={settings.autoOrbit}
onChange={(v) => update("autoOrbit", v)}
/>
{settings.autoOrbit && (
<>
<OrbitSpeedSlider
value={settings.orbitSpeed}
onChange={(v) => update("orbitSpeed", v)}
/>
<SegmentRow
icon={<ArrowLeftRight className="h-4 w-4" />}
title="Direction"
options={ORBIT_DIRECTIONS}
value={settings.orbitDirection}
onChange={(v) => update("orbitDirection", v)}
/>
</>
)}
<div className="mx-3 my-2 h-px bg-white/4" />
<SettingRow
icon={<Route className="h-4 w-4" />}
title="Flight trails"
description="Altitude-colored trails behind aircraft"
checked={settings.showTrails}
onChange={(v) => update("showTrails", v)}
/>
{settings.showTrails && (
<>
<TrailThicknessSlider
value={settings.trailThickness}
onChange={(v) => update("trailThickness", v)}
/>
<TrailDistanceSlider
value={settings.trailDistance}
onChange={(v) => update("trailDistance", v)}
/>
</>
)}
<SettingRow
icon={<Layers className="h-4 w-4" />}
title="Ground shadows"
description="Shadow projections on the map surface"
checked={settings.showShadows}
onChange={(v) => update("showShadows", v)}
/>
<SettingRow
icon={<Palette className="h-4 w-4" />}
title="Altitude colors"
description="Color aircraft and trails by altitude"
checked={settings.showAltitudeColors}
onChange={(v) => update("showAltitudeColors", v)}
/>
<div className="mx-3 my-2 h-px bg-white/4" />
<SettingRow
icon={<Globe className="h-4 w-4" />}
title="Globe mode"
description="Display earth as a 3D sphere when zoomed out"
checked={settings.globeMode}
onChange={(v) => update("globeMode", v)}
badge="BETA"
/>
<div className="mx-3 my-2 h-px bg-white/4" />
<div className="px-3 pt-2">
<button
type="button"
onClick={reset}
className="inline-flex h-8 items-center justify-center rounded-lg px-3 text-[12px] font-medium text-white/65 ring-1 ring-white/10 transition-colors hover:bg-white/5 hover:text-white/85"
>
Reset to defaults
</button>
</div>
<div className="mx-3 my-2 h-px bg-white/4" />
</div>
</ScrollArea>
);
}
export function ShortcutsContent() {
return (
<ScrollArea className="h-full">
<div className="p-3 pt-1">
<div className="space-y-1">
{SHORTCUTS.map(({ key, description }) => (
<div
key={key}
className="flex items-center justify-between gap-3 rounded-xl px-3 py-2.5 transition-colors hover:bg-white/4"
>
<span className="text-[13px] font-medium text-white/68">
{description}
</span>
<kbd className="flex h-7 min-w-7 items-center justify-center rounded-md bg-white/6 px-2 font-mono text-[11px] font-semibold text-white/74 ring-1 ring-white/8">
{key}
</kbd>
</div>
))}
</div>
</div>
</ScrollArea>
);
}
function OrbitSpeedSlider({
value,
onChange,
}: {
value: number;
onChange: (v: number) => void;
}) {
const activeLabel =
ORBIT_SPEED_PRESETS.find(
(p) => Math.abs(p.value - value) < ORBIT_SNAP_THRESHOLD,
)?.label ?? `${value.toFixed(2)}×`;
function handleChange(vals: number[]) {
let raw = vals[0];
for (const preset of ORBIT_SPEED_PRESETS) {
if (Math.abs(raw - preset.value) < ORBIT_SNAP_THRESHOLD) {
raw = preset.value;
break;
}
}
onChange(raw);
}
return (
<div className="flex w-full items-center gap-3.5 rounded-xl px-3 py-2.5 text-left">
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-white/5 text-white/35 ring-1 ring-white/6">
<RotateCw className="h-4 w-4" />
</div>
<div className="flex flex-1 min-w-0 flex-col gap-2">
<div className="flex items-center justify-between">
<p className="text-[13px] font-medium text-white/80">Orbit speed</p>
<span className="text-[11px] font-semibold text-white/40 tabular-nums">
{activeLabel}
</span>
</div>
<div className="relative">
<Slider
min={ORBIT_SPEED_MIN}
max={ORBIT_SPEED_MAX}
step={0.01}
value={[value]}
onValueChange={handleChange}
aria-label="Orbit speed"
/>
<div className="pointer-events-none absolute inset-x-0 top-1/2 -translate-y-1/2 flex justify-between px-0.5">
{ORBIT_SPEED_PRESETS.map((preset) => {
const pct =
((preset.value - ORBIT_SPEED_MIN) /
(ORBIT_SPEED_MAX - ORBIT_SPEED_MIN)) *
100;
const isActive =
Math.abs(preset.value - value) < ORBIT_SNAP_THRESHOLD;
return (
<span
key={preset.label}
className={`absolute h-1.5 w-1.5 rounded-full -translate-x-1/2 -translate-y-1/2 transition-colors ${
isActive ? "bg-white/50" : "bg-white/15"
}`}
style={{ left: `${pct}%` }}
/>
);
})}
</div>
</div>
</div>
</div>
);
}
function TrailThicknessSlider({
value,
onChange,
}: {
value: number;
onChange: (v: number) => void;
}) {
return (
<div className="flex w-full items-center gap-3.5 rounded-xl px-3 py-2.5 text-left">
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-white/5 text-white/35 ring-1 ring-white/6">
<Layers className="h-4 w-4" />
</div>
<div className="flex flex-1 min-w-0 flex-col gap-2">
<div className="flex items-center justify-between">
<p className="text-[13px] font-medium text-white/80">
Trail thickness
</p>
<span className="text-[11px] font-semibold text-white/40 tabular-nums">
{value.toFixed(1)} px
</span>
</div>
<Slider
min={TRAIL_THICKNESS_MIN}
max={TRAIL_THICKNESS_MAX}
step={0.1}
value={[value]}
onValueChange={(vals) => onChange(vals[0])}
aria-label="Trail thickness"
/>
</div>
</div>
);
}
function TrailDistanceSlider({
value,
onChange,
}: {
value: number;
onChange: (v: number) => void;
}) {
return (
<div className="flex w-full items-center gap-3.5 rounded-xl px-3 py-2.5 text-left">
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-white/5 text-white/35 ring-1 ring-white/6">
<Route className="h-4 w-4" />
</div>
<div className="flex flex-1 min-w-0 flex-col gap-2">
<div className="flex items-center justify-between">
<p className="text-[13px] font-medium text-white/80">
Trail distance
</p>
<span className="text-[11px] font-semibold text-white/40 tabular-nums">
{value} pts
</span>
</div>
<Slider
min={TRAIL_DISTANCE_MIN}
max={TRAIL_DISTANCE_MAX}
step={1}
value={[value]}
onValueChange={(vals) => onChange(vals[0])}
aria-label="Trail distance"
/>
</div>
</div>
);
}
function SettingRow({
icon,
title,
description,
checked,
onChange,
badge,
}: {
icon: ReactNode;
title: string;
description: string;
checked: boolean;
onChange: (v: boolean) => void;
badge?: string;
}) {
return (
<button
role="switch"
aria-checked={checked}
onClick={() => onChange(!checked)}
className="flex w-full items-center gap-3.5 rounded-xl px-3 py-3 text-left transition-colors hover:bg-white/4 active:bg-white/6"
>
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-white/5 text-white/35 ring-1 ring-white/6">
{icon}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5">
<p className="text-[13px] font-medium text-white/80">{title}</p>
{badge && (
<span className="inline-flex items-center rounded-md bg-indigo-500/15 px-1.5 py-0.5 text-[9px] font-bold tracking-wider text-indigo-300 ring-1 ring-indigo-400/20">
{badge}
</span>
)}
</div>
<p className="mt-0.5 text-[11px] font-medium leading-relaxed text-white/22">
{description}
</p>
</div>
<Toggle checked={checked} />
</button>
);
}
function SegmentRow<T extends string | number>({
icon,
title,
options,
value,
onChange,
}: {
icon: ReactNode;
title: string;
options: { label: string; value: T }[];
value: T;
onChange: (v: T) => void;
}) {
return (
<div className="flex w-full items-center gap-3.5 rounded-xl px-3 py-2.5 text-left">
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-white/5 text-white/35 ring-1 ring-white/6">
{icon}
</div>
<p className="flex-1 min-w-0 text-[13px] font-medium text-white/80">
{title}
</p>
<div
role="radiogroup"
aria-label={title}
className="flex shrink-0 rounded-md bg-white/4 p-0.5 ring-1 ring-white/6"
>
{options.map((opt) => {
const isActive = opt.value === value;
return (
<button
key={String(opt.value)}
role="radio"
aria-checked={isActive}
onClick={() => onChange(opt.value)}
className={`relative rounded-md px-2 py-1 text-[11px] font-semibold transition-colors ${
isActive ? "text-white/90" : "text-white/30 hover:text-white/50"
}`}
>
{isActive && (
<motion.div
layoutId={`seg-${title}`}
className="absolute inset-0 rounded-md bg-white/10"
transition={{
type: "spring",
stiffness: 500,
damping: 35,
}}
/>
)}
<span className="relative">{opt.label}</span>
</button>
);
})}
</div>
</div>
);
}
function Toggle({ checked }: { checked: boolean }) {
return (
<div
className={`relative h-5 w-9 shrink-0 rounded-full transition-colors duration-200 ${
checked ? "bg-white/20" : "bg-white/6"
}`}
>
<motion.div
animate={{ x: checked ? 17 : 2 }}
transition={{ type: "spring", stiffness: 500, damping: 30 }}
className={`absolute top-0.75 h-3.5 w-3.5 rounded-full shadow-sm transition-colors duration-200 ${
checked ? "bg-white" : "bg-white/25"
}`}
/>
</div>
);
}
const CHANGELOG = [
{
date: "Mar 11",
title: "Globe mode & aircraft photos",
description:
"Zoom out to see the entire earth as a 3D sphere with altitude-colored dots for every flight. Trails are now interpolated with centripetal Catmull\u2013Rom splines — a C\u00B9-continuous piecewise cubic that passes through every waypoint without overshooting, using \u03B1\u2009=\u20090.5 parameterization for natural curvature. Dark terrain, aircraft photo banners in flight cards, and a hard dot-to-flight cutover with zero overlap. Globe mode is in beta — find it in Settings.",
},
{
date: "Feb 22",
title: "Flight history tracking",
description:
"Full trail rendering for every tracked flight. Airline logo caching so they actually load.",
},
{
date: "Feb 21",
title: "First person view",
description:
"FPV mode — pick any plane and ride along with a HUD. Also added flight search by callsign.",
},
{
date: "Feb 17",
title: "Airline logos & attribution",
description:
"Proper logos for airlines, and attribution for OSM, OpenSky, CARTO, Esri, and everyone whose data makes this work.",
},
{
date: "Feb 15",
title: "9,000+ airports",
description:
"Went from a handful of cities to every airport we could find. Copilot helped build the dataset. Added keyboard shortcuts and click-to-select.",
},
{
date: "Feb 14",
title: "Day one",
description:
"Basic map, flight cards, trail rendering, orbit camera. Spent most of the day fighting Vercel timeouts and OpenSky IP blocks before realizing the API just supports CORS.",
},
];
export function AboutContent() {
return (
<ScrollArea className="h-full">
<div className="flex flex-col gap-5 p-5 pt-3">
<h3 className="text-[20px] font-bold tracking-tight text-white/90">
Aeris
</h3>
<div className="space-y-3 text-[13px] leading-relaxed text-white/40">
<p>
Live flight tracking in 3D. The planes you see are real position
data comes from the OpenSky Network, updated every few seconds via
ADS-B receivers people run on their roofs worldwide.
</p>
<p>
You can search through 9,000+ airports, jump into first-person view
to ride along with any plane, or just leave it on a screen and watch
things move. Trails change color with altitude so you can tell
who&apos;s cruising at 35,000ft and who&apos;s on approach.
</p>
</div>
<div className="h-px w-full bg-white/6" />
<p className="text-[12px] leading-relaxed text-white/30">
Built by{" "}
<a
href="https://github.com/kewonit"
target="_blank"
rel="noopener noreferrer"
className="text-white/55 underline decoration-white/15 underline-offset-2 hover:text-white/70 transition-colors"
>
kewonit
</a>
. Open to internships {" "}
<a
href="mailto:kew@edbn.me"
className="text-white/55 underline decoration-white/15 underline-offset-2 hover:text-white/70 transition-colors"
>
kew@edbn.me
</a>
</p>
<p className="text-[12px] leading-relaxed text-white/30">
Source is on{" "}
<a
href="https://github.com/kewonit/aeris"
target="_blank"
rel="noopener noreferrer"
className="text-white/55 underline decoration-white/15 underline-offset-2 hover:text-white/70 transition-colors"
>
GitHub
</a>
. Got a question or just wanna say hi?{" "}
<a
href="mailto:aeris@edbn.me"
className="text-white/55 underline decoration-white/15 underline-offset-2 hover:text-white/70 transition-colors"
>
aeris@edbn.me
</a>
</p>
</div>
</ScrollArea>
);
}
export function ChangelogContent() {
return (
<ScrollArea className="h-full">
<div className="flex flex-col gap-4 p-5 pt-3">
{CHANGELOG.map((entry) => (
<div key={entry.date} className="flex gap-3">
<span className="shrink-0 pt-0.5 text-[11px] tabular-nums text-white/20 w-11">
{entry.date}
</span>
<div className="min-w-0">
<p className="text-[13px] font-medium text-white/55">
{entry.title}
</p>
<p className="mt-0.5 text-[12px] leading-relaxed text-white/30">
{entry.description}
</p>
</div>
</div>
))}
</div>
</ScrollArea>
);
}

View File

@ -0,0 +1,123 @@
"use client";
import { useState } from "react";
import Image from "next/image";
import { motion, AnimatePresence } from "motion/react";
import { Check } from "lucide-react";
import { MAP_STYLES, type MapStyle } from "@/lib/map-styles";
import { ScrollArea } from "@/components/ui/scroll-area";
export function StyleContent({
activeStyle,
onSelect,
}: {
activeStyle: MapStyle;
onSelect: (style: MapStyle) => void;
}) {
return (
<ScrollArea className="h-full">
<div className="grid grid-cols-2 sm:grid-cols-2 gap-2.5 sm:gap-3 p-4 sm:p-5 pt-2">
{MAP_STYLES.map((style, i) => (
<StyleTile
key={style.id}
style={style}
isActive={style.id === activeStyle.id}
index={i}
onSelect={() => onSelect(style)}
/>
))}
</div>
<div className="border-t border-white/4 px-5 py-3">
<p className="text-[11px] font-medium text-white/12">
Satellite © Esri · Terrain © OpenTopoMap / Terrain Tiles · Base maps ©
CARTO
</p>
</div>
</ScrollArea>
);
}
function StyleTile({
style,
isActive,
index,
onSelect,
}: {
style: MapStyle;
isActive: boolean;
index: number;
onSelect: () => void;
}) {
const [imgLoaded, setImgLoaded] = useState(false);
return (
<motion.button
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.04 * index, duration: 0.25, ease: "easeOut" }}
onClick={onSelect}
aria-pressed={isActive}
aria-label={`${style.name} map style`}
className="group relative flex flex-col gap-2 text-left"
>
<div
className={`relative aspect-16/10 w-full overflow-hidden rounded-xl transition-all duration-200 ${
isActive
? "ring-2 ring-white/50 ring-offset-2 ring-offset-black/80 shadow-[0_0_20px_rgba(255,255,255,0.06)]"
: "ring-1 ring-white/8 group-hover:ring-white/18"
}`}
>
<div
className="absolute inset-0"
style={{ background: style.preview }}
/>
<Image
src={style.previewUrl}
alt={`${style.name} preview`}
fill
unoptimized
onLoad={() => setImgLoaded(true)}
onError={() => setImgLoaded(true)}
className={`object-cover transition-all duration-500 group-hover:scale-105 ${
imgLoaded ? "opacity-100" : "opacity-0"
}`}
draggable={false}
/>
<div className="absolute inset-0 rounded-xl shadow-[inset_0_1px_0_rgba(255,255,255,0.06),inset_0_-16px_28px_-10px_rgba(0,0,0,0.4)]" />
<AnimatePresence>
{isActive && (
<motion.div
initial={{ scale: 0, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0, opacity: 0 }}
transition={{
type: "spring",
stiffness: 500,
damping: 28,
}}
className="absolute right-1.5 top-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-white shadow-md shadow-black/30"
>
<Check className="h-3 w-3 text-black" strokeWidth={3} />
</motion.div>
)}
</AnimatePresence>
</div>
<div className="flex items-center gap-1.5 px-0.5">
<span
className={`text-[12px] font-semibold tracking-tight transition-colors ${
isActive
? "text-white/90"
: "text-white/40 group-hover:text-white/60"
}`}
>
{style.name}
</span>
{style.dark && (
<span className="h-0.5 w-0.5 rounded-full bg-white/20" />
)}
</div>
</motion.button>
);
}

View File

@ -1,36 +1,36 @@
"use client";
import { useState, useMemo, useRef, useEffect, type ReactNode } from "react";
import Image from "next/image";
import { useState, useEffect, useRef, type ReactNode } from "react";
import { motion, AnimatePresence } from "motion/react";
import {
Search,
Map as MapIcon,
Settings,
Keyboard,
X,
Check,
MapPin,
ChevronRight,
RotateCw,
Route,
Layers,
Palette,
ArrowLeftRight,
Github,
Plane,
Eye,
Loader2,
Info,
Clock,
} from "lucide-react";
import { CITIES, type City } from "@/lib/cities";
import { searchAirports, airportToCity } from "@/lib/airports";
import { MAP_STYLES, type MapStyle } from "@/lib/map-styles";
import { useSettings, type OrbitDirection } from "@/hooks/use-settings";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Slider } from "@/components/ui/slider";
import type { City } from "@/lib/cities";
import type { MapStyle } from "@/lib/map-styles";
import type { FlightState } from "@/lib/opensky";
import { formatCallsign } from "@/lib/flight-utils";
import { SearchContent } from "@/components/ui/control-panel-search";
import { StyleContent } from "@/components/ui/control-panel-styles";
import {
SettingsContent,
ShortcutsContent,
AboutContent,
ChangelogContent,
} from "@/components/ui/control-panel-settings";
type TabId = "search" | "style" | "settings";
type TabId =
| "search"
| "style"
| "settings"
| "shortcuts"
| "changelog"
| "about";
const MAIN_TABS: {
id: TabId;
@ -39,10 +39,15 @@ const MAIN_TABS: {
}[] = [
{ id: "search", icon: Search, label: "Search" },
{ id: "style", icon: MapIcon, label: "Map Style" },
{ id: "settings", icon: Settings, label: "Settings" },
];
const PANEL_TABS = MAIN_TABS;
const PANEL_TABS = [
...MAIN_TABS,
{ id: "settings" as TabId, icon: Settings, label: "Settings" },
{ id: "shortcuts" as TabId, icon: Keyboard, label: "Shortcuts" },
{ id: "changelog" as TabId, icon: Clock, label: "Changelog" },
{ id: "about" as TabId, icon: Info, label: "About" },
];
type ControlPanelProps = {
activeCity: City;
@ -69,9 +74,15 @@ export function ControlPanel({
function handleOpenSearch() {
setOpenTab("search");
}
function handleOpenShortcuts() {
setOpenTab("shortcuts");
}
window.addEventListener("aeris:open-search", handleOpenSearch);
return () =>
window.addEventListener("aeris:open-shortcuts", handleOpenShortcuts);
return () => {
window.removeEventListener("aeris:open-search", handleOpenSearch);
window.removeEventListener("aeris:open-shortcuts", handleOpenShortcuts);
};
}, []);
const open = (tab: TabId) => setOpenTab(tab);
@ -98,6 +109,22 @@ export function ControlPanel({
</motion.button>
))}
<motion.button
onClick={() => open("settings")}
className="flex h-9 w-9 items-center justify-center rounded-xl backdrop-blur-2xl transition-colors"
style={{
borderWidth: 1,
borderColor: "rgb(var(--ui-fg) / 0.06)",
backgroundColor: "rgb(var(--ui-fg) / 0.03)",
color: "rgb(var(--ui-fg) / 0.5)",
}}
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
aria-label="Settings"
>
<Settings className="h-4 w-4" />
</motion.button>
<AnimatePresence>
{openTab && (
<PanelDialog
@ -197,7 +224,7 @@ function PanelDialog({
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
className="fixed inset-0 z-80 bg-black/60 backdrop-blur-xl"
className="fixed inset-0 z-80 bg-black/70"
onClick={onClose}
/>
@ -217,7 +244,7 @@ function PanelDialog({
aria-modal="true"
aria-labelledby="panel-dialog-title"
>
<div className="flex flex-col sm:flex-row overflow-hidden rounded-2xl sm:rounded-3xl border border-white/8 bg-[#0c0c0e]/92 shadow-[0_40px_100px_rgba(0,0,0,0.8),0_0_0_1px_rgba(255,255,255,0.04)_inset] backdrop-blur-3xl backdrop-saturate-[1.8] h-[75vh] sm:h-auto sm:max-h-[85vh]">
<div className="flex flex-col sm:flex-row overflow-hidden rounded-2xl sm:rounded-3xl border border-white/8 bg-[#0c0c0e] shadow-[0_40px_100px_rgba(0,0,0,0.8),0_0_0_1px_rgba(255,255,255,0.04)_inset] h-[75vh] sm:h-auto sm:max-h-[85vh]">
{/* Desktop sidebar (hidden on mobile) */}
<div className="hidden sm:flex w-52 shrink-0 flex-col border-r border-white/6 py-5 px-3">
<p className="mb-3 px-2 text-[11px] font-semibold uppercase tracking-widest text-white/20">
@ -272,7 +299,7 @@ function PanelDialog({
</a>
<div className="border-t border-white/3 pt-2 px-2.5">
<p className="text-[10px] font-medium text-white/10 tracking-wide">
v0.1 · OpenSky Network
Powered by OpenSky Network
</p>
</div>
</div>
@ -337,24 +364,40 @@ function PanelDialog({
<SettingsContent />
</TabContent>
)}
{activeTab === "shortcuts" && (
<TabContent key="shortcuts">
<ShortcutsContent />
</TabContent>
)}
{activeTab === "changelog" && (
<TabContent key="changelog">
<ChangelogContent />
</TabContent>
)}
{activeTab === "about" && (
<TabContent key="about">
<AboutContent />
</TabContent>
)}
</AnimatePresence>
</div>
</div>
{/* Mobile tab bar */}
<div className="flex sm:hidden items-center gap-1 border-t border-white/6 px-3 pt-2 pb-3">
<nav className="flex flex-1 gap-1">
<div className="flex sm:hidden items-center gap-0.5 border-t border-white/6 px-2 pt-2 pb-3">
<nav className="flex flex-1 gap-0.5">
{PANEL_TABS.map(({ id, icon: Icon, label }) => {
const active = id === activeTab;
return (
<button
key={id}
onClick={() => onTabChange(id)}
className={`relative flex flex-1 items-center justify-center gap-1.5 rounded-lg px-2 py-2 text-center transition-colors ${
className={`relative flex flex-1 items-center justify-center rounded-lg py-2.5 transition-colors ${
active
? "text-white/90"
: "text-white/35 active:bg-white/6"
}`}
aria-label={label}
>
{active && (
<motion.div
@ -367,17 +410,14 @@ function PanelDialog({
}}
/>
)}
<Icon className="relative h-3.5 w-3.5 shrink-0" />
<span className="relative text-[12px] font-semibold">
{label}
</span>
<Icon className="relative h-4 w-4 shrink-0" />
</button>
);
})}
</nav>
<motion.button
onClick={onClose}
className="ml-1 flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-white/6 transition-colors active:bg-white/12"
className="ml-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-white/6 transition-colors active:bg-white/12"
whileTap={{ scale: 0.9 }}
aria-label="Close"
>
@ -403,785 +443,3 @@ function TabContent({ children }: { children: ReactNode }) {
</motion.div>
);
}
function SearchContent({
activeCity,
onSelect,
flights,
activeFlightIcao24,
onLookupFlight,
}: {
activeCity: City;
onSelect: (city: City) => void;
flights: FlightState[];
activeFlightIcao24: string | null;
onLookupFlight: (query: string, enterFpv?: boolean) => Promise<boolean>;
}) {
const [query, setQuery] = useState("");
const [lookupBusy, setLookupBusy] = useState(false);
const [lookupError, setLookupError] = useState<string | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
requestAnimationFrame(() => inputRef.current?.focus());
}, []);
const { featured, airports } = useMemo(() => {
const q = query.trim().toLowerCase();
if (!q)
return {
featured: CITIES,
airports: [] as ReturnType<typeof searchAirports>,
};
const featured = CITIES.filter(
(c) =>
c.name.toLowerCase().includes(q) ||
c.iata.toLowerCase().includes(q) ||
c.country.toLowerCase().includes(q),
);
const featuredIatas = new Set(CITIES.map((c) => c.iata));
const airports = searchAirports(q).filter(
(a) => !featuredIatas.has(a.iata),
);
return { featured, airports };
}, [query]);
const normalizedQuery = query.trim().toLowerCase();
const compactQuery = normalizedQuery.replace(/\s+/g, "");
const isIcao24Query = /^[0-9a-f]{6}$/.test(compactQuery);
const flightMatches = useMemo(() => {
if (!compactQuery) return [] as FlightState[];
return flights
.filter((flight) => {
const icao = flight.icao24.toLowerCase();
const callsign = (flight.callsign ?? "")
.trim()
.toLowerCase()
.replace(/\s+/g, "");
return icao.includes(compactQuery) || callsign.includes(compactQuery);
})
.slice(0, 12);
}, [flights, compactQuery]);
const hasResults =
featured.length > 0 || airports.length > 0 || flightMatches.length > 0;
async function runLookup(enterFpv = false) {
if (!query.trim() || lookupBusy) return;
setLookupBusy(true);
setLookupError(null);
try {
const found = await onLookupFlight(query, enterFpv);
if (!found) {
setLookupError(
isIcao24Query
? "Flight not found for this ICAO24 right now"
: "No live worldwide flight match found (or rate-limited)",
);
}
} finally {
setLookupBusy(false);
}
}
async function openFlight(icao24: string, enterFpv = false) {
if (lookupBusy) return;
setLookupBusy(true);
setLookupError(null);
try {
const found = await onLookupFlight(icao24, enterFpv);
if (!found) {
setLookupError("Unable to open the selected flight");
}
} finally {
setLookupBusy(false);
}
}
return (
<div className="flex h-full flex-col">
<div className="flex items-center gap-2.5 border-b border-white/6 mx-5 pb-3">
<Search className="h-3.5 w-3.5 shrink-0 text-white/25" />
<input
ref={inputRef}
value={query}
onChange={(e) => {
setQuery(e.target.value);
setLookupError(null);
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
void runLookup(false);
}
}}
placeholder="Search airports or flight number (callsign/ICAO24)..."
aria-label="Search airports by name, IATA code, city, country, or flight callsign/ICAO24"
className="flex-1 bg-transparent text-[14px] font-medium text-white/90 placeholder:text-white/20 outline-none"
/>
{query && (
<button
onClick={() => setQuery("")}
className="shrink-0 text-white/20 hover:text-white/40 transition-colors"
aria-label="Clear search"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
<ScrollArea className="flex-1">
<div className="p-2">
{compactQuery && (
<div className="px-3 pb-2 space-y-2">
<button
type="button"
onClick={() => void runLookup(false)}
disabled={lookupBusy}
className="flex w-full items-center justify-center gap-2 rounded-lg border border-white/10 bg-white/4 px-3 py-2 text-[12px] font-medium text-white/75 transition-colors hover:bg-white/7 disabled:cursor-not-allowed disabled:opacity-60"
>
{lookupBusy ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Search className="h-3.5 w-3.5" />
)}
<span>Open Flight Details</span>
</button>
<button
type="button"
onClick={() => void runLookup(true)}
disabled={lookupBusy}
className="flex w-full items-center justify-center gap-2 rounded-lg border border-sky-400/25 bg-sky-500/10 px-3 py-2 text-[12px] font-medium text-sky-300/90 transition-colors hover:bg-sky-500/15 disabled:cursor-not-allowed disabled:opacity-60"
>
{lookupBusy ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Eye className="h-3.5 w-3.5" />
)}
<span>Open in FPV</span>
</button>
</div>
)}
{lookupError && (
<p className="px-3 pb-2 text-[11px] font-medium text-amber-300/85">
{lookupError}
</p>
)}
{flightMatches.length > 0 && (
<>
<p className="px-3 pt-1 pb-1.5 text-[10px] font-semibold uppercase tracking-widest text-white/15">
Flights
</p>
{flightMatches.map((flight) => (
<FlightRow
key={flight.icao24}
callsign={formatCallsign(flight.callsign)}
detail={`${flight.icao24.toUpperCase()} · ${flight.originCountry}`}
isActive={activeFlightIcao24 === flight.icao24}
onOpen={() => void openFlight(flight.icao24, false)}
onFpv={() => void openFlight(flight.icao24, true)}
/>
))}
</>
)}
{!hasResults && (
<p className="py-8 text-center text-[12px] text-white/25">
No airports or flights found
</p>
)}
{featured.length > 0 && (
<>
{query && (
<p className="px-3 pt-2 pb-1.5 text-[10px] font-semibold uppercase tracking-widest text-white/15">
Featured
</p>
)}
{featured.map((city) => (
<LocationRow
key={city.id}
name={city.name}
detail={`${city.iata} · ${city.country}`}
isActive={activeCity?.id === city.id}
onClick={() => onSelect(city)}
/>
))}
</>
)}
{airports.length > 0 && (
<>
<p
className={`px-3 pb-1.5 text-[10px] font-semibold uppercase tracking-widest text-white/15 ${
featured.length > 0 ? "pt-3" : "pt-2"
}`}
>
Airports
</p>
{airports.map((airport) => (
<LocationRow
key={airport.iata}
name={airport.name}
detail={`${airport.iata} · ${airport.city}, ${airport.country}`}
isActive={activeCity?.iata === airport.iata}
onClick={() => onSelect(airportToCity(airport))}
/>
))}
</>
)}
{!query && (
<p className="px-3 pt-3 pb-1 text-center text-[10px] font-medium text-white/10">
Search 9,000+ airports worldwide
</p>
)}
</div>
</ScrollArea>
</div>
);
}
function LocationRow({
name,
detail,
isActive,
onClick,
}: {
name: string;
detail: string;
isActive: boolean;
onClick: () => void;
}) {
return (
<button
onClick={onClick}
aria-current={isActive ? "true" : undefined}
className={`group flex w-full items-center gap-2.5 rounded-xl px-3 py-2.5 text-left transition-colors hover:bg-white/4 ${
isActive ? "bg-white/6" : ""
}`}
>
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-white/4">
<MapPin className="h-3.5 w-3.5 text-white/40" />
</div>
<div className="flex-1 min-w-0">
<p className="truncate text-[14px] font-medium text-white/80">{name}</p>
<p className="text-[11px] font-medium text-white/25">{detail}</p>
</div>
<ChevronRight className="h-3.5 w-3.5 shrink-0 text-white/12 transition-colors group-hover:text-white/25" />
</button>
);
}
function FlightRow({
callsign,
detail,
isActive,
onOpen,
onFpv,
}: {
callsign: string;
detail: string;
isActive: boolean;
onOpen: () => void;
onFpv: () => void;
}) {
return (
<div
className={`group flex items-center gap-2.5 rounded-xl px-3 py-2.5 transition-colors hover:bg-white/4 ${
isActive ? "bg-white/6" : ""
}`}
>
<button
onClick={onOpen}
className="flex min-w-0 flex-1 items-center gap-2.5 text-left"
>
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-white/4">
<Plane className="h-3.5 w-3.5 text-white/40" />
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-[14px] font-medium text-white/80">
{callsign}
</p>
<p className="text-[11px] font-medium text-white/25">{detail}</p>
</div>
</button>
<button
type="button"
onClick={onFpv}
className="inline-flex h-7 items-center gap-1.5 rounded-lg border border-sky-400/20 bg-sky-500/10 px-2 text-[10px] font-semibold uppercase tracking-wide text-sky-300/90 transition-colors hover:bg-sky-500/20"
aria-label="Open flight in FPV"
>
<Eye className="h-3 w-3" />
FPV
</button>
</div>
);
}
function StyleContent({
activeStyle,
onSelect,
}: {
activeStyle: MapStyle;
onSelect: (style: MapStyle) => void;
}) {
return (
<ScrollArea className="h-full">
<div className="grid grid-cols-2 sm:grid-cols-2 gap-2.5 sm:gap-3 p-4 sm:p-5 pt-2">
{MAP_STYLES.map((style, i) => (
<StyleTile
key={style.id}
style={style}
isActive={style.id === activeStyle.id}
index={i}
onSelect={() => onSelect(style)}
/>
))}
</div>
<div className="border-t border-white/4 px-5 py-3">
<p className="text-[11px] font-medium text-white/12">
Satellite © Esri · Terrain © OpenTopoMap · Base maps © CARTO
</p>
</div>
</ScrollArea>
);
}
function StyleTile({
style,
isActive,
index,
onSelect,
}: {
style: MapStyle;
isActive: boolean;
index: number;
onSelect: () => void;
}) {
const [imgLoaded, setImgLoaded] = useState(false);
return (
<motion.button
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.04 * index, duration: 0.25, ease: "easeOut" }}
onClick={onSelect}
aria-pressed={isActive}
aria-label={`${style.name} map style`}
className="group relative flex flex-col gap-2 text-left"
>
<div
className={`relative aspect-16/10 w-full overflow-hidden rounded-xl transition-all duration-200 ${
isActive
? "ring-2 ring-white/50 ring-offset-2 ring-offset-black/80 shadow-[0_0_20px_rgba(255,255,255,0.06)]"
: "ring-1 ring-white/8 group-hover:ring-white/18"
}`}
>
<div
className="absolute inset-0"
style={{ background: style.preview }}
/>
<Image
src={style.previewUrl}
alt={`${style.name} preview`}
fill
unoptimized
onLoad={() => setImgLoaded(true)}
onError={() => setImgLoaded(true)}
className={`object-cover transition-all duration-500 group-hover:scale-105 ${
imgLoaded ? "opacity-100" : "opacity-0"
}`}
draggable={false}
/>
<div className="absolute inset-0 rounded-xl shadow-[inset_0_1px_0_rgba(255,255,255,0.06),inset_0_-16px_28px_-10px_rgba(0,0,0,0.4)]" />
<AnimatePresence>
{isActive && (
<motion.div
initial={{ scale: 0, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0, opacity: 0 }}
transition={{
type: "spring",
stiffness: 500,
damping: 28,
}}
className="absolute right-1.5 top-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-white shadow-md shadow-black/30"
>
<Check className="h-3 w-3 text-black" strokeWidth={3} />
</motion.div>
)}
</AnimatePresence>
</div>
<div className="flex items-center gap-1.5 px-0.5">
<span
className={`text-[12px] font-semibold tracking-tight transition-colors ${
isActive
? "text-white/90"
: "text-white/40 group-hover:text-white/60"
}`}
>
{style.name}
</span>
{style.dark && (
<span className="h-0.5 w-0.5 rounded-full bg-white/20" />
)}
</div>
</motion.button>
);
}
const ORBIT_SPEED_PRESETS = [
{ label: "Slow", value: 0.06 },
{ label: "Normal", value: 0.15 },
{ label: "Fast", value: 0.35 },
];
const ORBIT_SPEED_MIN = 0.02;
const ORBIT_SPEED_MAX = 0.5;
const ORBIT_SNAP_THRESHOLD = 0.025;
const TRAIL_THICKNESS_MIN = 1;
const TRAIL_THICKNESS_MAX = 8;
const TRAIL_DISTANCE_MIN = 12;
const TRAIL_DISTANCE_MAX = 100;
const ORBIT_DIRECTIONS: { label: string; value: OrbitDirection }[] = [
{ label: "Clockwise", value: "clockwise" },
{ label: "Counter", value: "counter-clockwise" },
];
function SettingsContent() {
const { settings, update, reset } = useSettings();
return (
<ScrollArea className="h-full">
<div className="space-y-0.5 p-3 pt-1">
<SettingRow
icon={<RotateCw className="h-4 w-4" />}
title="Auto-orbit"
description="Camera slowly rotates around the airport"
checked={settings.autoOrbit}
onChange={(v) => update("autoOrbit", v)}
/>
{settings.autoOrbit && (
<>
<OrbitSpeedSlider
value={settings.orbitSpeed}
onChange={(v) => update("orbitSpeed", v)}
/>
<SegmentRow
icon={<ArrowLeftRight className="h-4 w-4" />}
title="Direction"
options={ORBIT_DIRECTIONS}
value={settings.orbitDirection}
onChange={(v) => update("orbitDirection", v)}
/>
</>
)}
<div className="mx-3 my-2 h-px bg-white/4" />
<SettingRow
icon={<Route className="h-4 w-4" />}
title="Flight trails"
description="Altitude-colored trails behind aircraft"
checked={settings.showTrails}
onChange={(v) => update("showTrails", v)}
/>
{settings.showTrails && (
<>
<TrailThicknessSlider
value={settings.trailThickness}
onChange={(v) => update("trailThickness", v)}
/>
<TrailDistanceSlider
value={settings.trailDistance}
onChange={(v) => update("trailDistance", v)}
/>
</>
)}
<SettingRow
icon={<Layers className="h-4 w-4" />}
title="Ground shadows"
description="Shadow projections on the map surface"
checked={settings.showShadows}
onChange={(v) => update("showShadows", v)}
/>
<SettingRow
icon={<Palette className="h-4 w-4" />}
title="Altitude colors"
description="Color aircraft and trails by altitude"
checked={settings.showAltitudeColors}
onChange={(v) => update("showAltitudeColors", v)}
/>
<div className="px-3 pt-2">
<button
type="button"
onClick={reset}
className="inline-flex h-8 items-center justify-center rounded-lg px-3 text-[12px] font-medium text-white/65 ring-1 ring-white/10 transition-colors hover:bg-white/5 hover:text-white/85"
>
Reset to defaults
</button>
</div>
</div>
</ScrollArea>
);
}
function OrbitSpeedSlider({
value,
onChange,
}: {
value: number;
onChange: (v: number) => void;
}) {
const activeLabel =
ORBIT_SPEED_PRESETS.find(
(p) => Math.abs(p.value - value) < ORBIT_SNAP_THRESHOLD,
)?.label ?? `${value.toFixed(2)}×`;
function handleChange(vals: number[]) {
let raw = vals[0];
for (const preset of ORBIT_SPEED_PRESETS) {
if (Math.abs(raw - preset.value) < ORBIT_SNAP_THRESHOLD) {
raw = preset.value;
break;
}
}
onChange(raw);
}
return (
<div className="flex w-full items-center gap-3.5 rounded-xl px-3 py-2.5 text-left">
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-white/5 text-white/35 ring-1 ring-white/6">
<RotateCw className="h-4 w-4" />
</div>
<div className="flex flex-1 min-w-0 flex-col gap-2">
<div className="flex items-center justify-between">
<p className="text-[13px] font-medium text-white/80">Orbit speed</p>
<span className="text-[11px] font-semibold text-white/40 tabular-nums">
{activeLabel}
</span>
</div>
<div className="relative">
<Slider
min={ORBIT_SPEED_MIN}
max={ORBIT_SPEED_MAX}
step={0.01}
value={[value]}
onValueChange={handleChange}
aria-label="Orbit speed"
/>
<div className="pointer-events-none absolute inset-x-0 top-1/2 -translate-y-1/2 flex justify-between px-0.5">
{ORBIT_SPEED_PRESETS.map((preset) => {
const pct =
((preset.value - ORBIT_SPEED_MIN) /
(ORBIT_SPEED_MAX - ORBIT_SPEED_MIN)) *
100;
const isActive =
Math.abs(preset.value - value) < ORBIT_SNAP_THRESHOLD;
return (
<span
key={preset.label}
className={`absolute h-1.5 w-1.5 rounded-full -translate-x-1/2 -translate-y-1/2 transition-colors ${
isActive ? "bg-white/50" : "bg-white/15"
}`}
style={{ left: `${pct}%` }}
/>
);
})}
</div>
</div>
</div>
</div>
);
}
function TrailThicknessSlider({
value,
onChange,
}: {
value: number;
onChange: (v: number) => void;
}) {
return (
<div className="flex w-full items-center gap-3.5 rounded-xl px-3 py-2.5 text-left">
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-white/5 text-white/35 ring-1 ring-white/6">
<Layers className="h-4 w-4" />
</div>
<div className="flex flex-1 min-w-0 flex-col gap-2">
<div className="flex items-center justify-between">
<p className="text-[13px] font-medium text-white/80">
Trail thickness
</p>
<span className="text-[11px] font-semibold text-white/40 tabular-nums">
{value.toFixed(1)} px
</span>
</div>
<Slider
min={TRAIL_THICKNESS_MIN}
max={TRAIL_THICKNESS_MAX}
step={0.1}
value={[value]}
onValueChange={(vals) => onChange(vals[0])}
aria-label="Trail thickness"
/>
</div>
</div>
);
}
function TrailDistanceSlider({
value,
onChange,
}: {
value: number;
onChange: (v: number) => void;
}) {
return (
<div className="flex w-full items-center gap-3.5 rounded-xl px-3 py-2.5 text-left">
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-white/5 text-white/35 ring-1 ring-white/6">
<Route className="h-4 w-4" />
</div>
<div className="flex flex-1 min-w-0 flex-col gap-2">
<div className="flex items-center justify-between">
<p className="text-[13px] font-medium text-white/80">
Trail distance
</p>
<span className="text-[11px] font-semibold text-white/40 tabular-nums">
{value} pts
</span>
</div>
<Slider
min={TRAIL_DISTANCE_MIN}
max={TRAIL_DISTANCE_MAX}
step={1}
value={[value]}
onValueChange={(vals) => onChange(vals[0])}
aria-label="Trail distance"
/>
</div>
</div>
);
}
function SettingRow({
icon,
title,
description,
checked,
onChange,
}: {
icon: ReactNode;
title: string;
description: string;
checked: boolean;
onChange: (v: boolean) => void;
}) {
return (
<button
role="switch"
aria-checked={checked}
onClick={() => onChange(!checked)}
className="flex w-full items-center gap-3.5 rounded-xl px-3 py-3 text-left transition-colors hover:bg-white/4 active:bg-white/6"
>
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-white/5 text-white/35 ring-1 ring-white/6">
{icon}
</div>
<div className="flex-1 min-w-0">
<p className="text-[13px] font-medium text-white/80">{title}</p>
<p className="mt-0.5 text-[11px] font-medium leading-relaxed text-white/22">
{description}
</p>
</div>
<Toggle checked={checked} />
</button>
);
}
function SegmentRow<T extends string | number>({
icon,
title,
options,
value,
onChange,
}: {
icon: ReactNode;
title: string;
options: { label: string; value: T }[];
value: T;
onChange: (v: T) => void;
}) {
return (
<div className="flex w-full items-center gap-3.5 rounded-xl px-3 py-2.5 text-left">
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-white/5 text-white/35 ring-1 ring-white/6">
{icon}
</div>
<p className="flex-1 min-w-0 text-[13px] font-medium text-white/80">
{title}
</p>
<div
role="radiogroup"
aria-label={title}
className="flex shrink-0 rounded-md bg-white/4 p-0.5 ring-1 ring-white/6"
>
{options.map((opt) => {
const isActive = opt.value === value;
return (
<button
key={String(opt.value)}
role="radio"
aria-checked={isActive}
onClick={() => onChange(opt.value)}
className={`relative rounded-md px-2 py-1 text-[11px] font-semibold transition-colors ${
isActive ? "text-white/90" : "text-white/30 hover:text-white/50"
}`}
>
{isActive && (
<motion.div
layoutId={`seg-${title}`}
className="absolute inset-0 rounded-md bg-white/10"
transition={{
type: "spring",
stiffness: 500,
damping: 35,
}}
/>
)}
<span className="relative">{opt.label}</span>
</button>
);
})}
</div>
</div>
);
}
function Toggle({ checked }: { checked: boolean }) {
return (
<div
className={`relative h-5 w-9 shrink-0 rounded-full transition-colors duration-200 ${
checked ? "bg-white/20" : "bg-white/6"
}`}
>
<motion.div
animate={{ x: checked ? 17 : 2 }}
transition={{ type: "spring", stiffness: 500, damping: 30 }}
className={`absolute top-0.75 h-3.5 w-3.5 rounded-full shadow-sm transition-colors duration-200 ${
checked ? "bg-white" : "bg-white/25"
}`}
/>
</div>
);
}

View File

@ -13,7 +13,11 @@ import {
Navigation,
Building2,
Eye,
ChevronRight,
} from "lucide-react";
import { useAircraftPhotos } from "@/hooks/use-aircraft-photos";
import { AircraftPhotos } from "@/components/ui/aircraft-photos";
import { HeroBanner } from "@/components/ui/hero-banner";
import type { FlightState } from "@/lib/opensky";
import {
metersToFeet,
@ -84,6 +88,14 @@ export function FlightCard({
const showLogo = Boolean(logoUrl);
const genericLogoUrl = "/airline-logos/envoy-air.png";
const {
photos,
aircraft: photoAircraft,
loading: photosLoading,
error: photosError,
} = useAircraftPhotos(flight?.icao24 ?? null);
const heroPhoto = photos[0] ?? null;
return (
<AnimatePresence mode="wait">
{flight && (
@ -103,8 +115,10 @@ export function FlightCard({
aria-label="Selected flight details"
aria-live="polite"
>
<div className="rounded-2xl border border-white/8 bg-black/60 p-4 shadow-2xl shadow-black/40 backdrop-blur-2xl">
<div className="flex items-center justify-between">
<div className="overflow-hidden rounded-2xl border border-white/8 bg-black/60 shadow-2xl shadow-black/40 backdrop-blur-2xl">
<HeroBanner photo={heroPhoto} loading={photosLoading} />
<div className="p-4">
<div className="flex items-center gap-3.5">
<div className="relative flex h-20 w-20 items-center justify-center rounded-2xl border border-white/14 bg-white/10 shadow-lg shadow-black/25">
{showLogo ? (
@ -133,7 +147,6 @@ export function FlightCard({
}}
onError={() => {
if (logoUrl) markAirlineLogoFailed(logoUrl);
if (resolvedLogoIndex + 1 < logoCandidates.length) {
setLogoIndexByAirline((current) => ({
...current,
@ -169,35 +182,144 @@ export function FlightCard({
)}
</div>
<div>
<p className="text-sm font-semibold tracking-wide text-white">
<p className="text-base font-bold leading-tight text-white">
{formatCallsign(flight.callsign)}
</p>
<p className="text-[11px] font-medium tracking-wider text-white/40 uppercase">
<p className="mt-0.5 text-[11px] font-medium tracking-widest text-white/35 uppercase">
{flight.icao24}
{flightNum ? ` · #${flightNum}` : ""}
</p>
</div>
</div>
<div className="flex items-center gap-1.5">
{onToggleFpv && (
<motion.button
{company && (
<div className="mt-2.5 flex items-center gap-1.5">
<Building2 className="h-3 w-3 text-white/25" />
<p className="text-xs font-medium text-white/50">
{company}
{model ? (
<span className="text-white/30"> · {model}</span>
) : null}
</p>
</div>
)}
<div className="mt-3 h-px bg-linear-to-r from-transparent via-white/6 to-transparent" />
<div className="mt-3 grid grid-cols-2 gap-3">
<Metric
icon={<ArrowUp className="h-3 w-3" />}
label="Altitude"
value={metersToFeet(flight.baroAltitude)}
/>
<Metric
icon={<Gauge className="h-3 w-3" />}
label="Speed"
value={msToKnots(flight.velocity)}
/>
<Metric
icon={<Compass className="h-3 w-3" />}
label="Heading"
value={
heading !== null && Number.isFinite(heading)
? `${Math.round(heading)}° ${cardinal}`
: "—"
}
/>
<Metric
icon={<ArrowDown className="h-3 w-3" />}
label="V/S"
value={
flight.verticalRate !== null &&
Number.isFinite(flight.verticalRate)
? `${flight.verticalRate > 0 ? "+" : ""}${Math.round(flight.verticalRate)} m/s`
: "—"
}
/>
</div>
<div className="mt-3 h-px bg-linear-to-r from-transparent via-white/6 to-transparent" />
<div className="mt-2.5 flex flex-col gap-1.5">
<div className="flex items-center gap-1.5">
<Globe className="h-3 w-3 text-white/25" />
<p className="text-[11px] text-white/40">
{flight.originCountry}
</p>
</div>
{cardinal && (
<div className="flex items-center gap-1.5">
<Navigation
className="h-3 w-3 text-white/25"
style={{
transform:
heading !== null && Number.isFinite(heading)
? `rotate(${heading}deg)`
: undefined,
}}
/>
<p className="text-[11px] text-white/40">
Heading {cardinal}
{flight.latitude !== null &&
flight.longitude !== null &&
Number.isFinite(flight.latitude) &&
Number.isFinite(flight.longitude) && (
<span className="text-white/20">
{" "}
· {Math.abs(flight.latitude).toFixed(2)}°
{flight.latitude >= 0 ? "N" : "S"},{" "}
{Math.abs(flight.longitude).toFixed(2)}°
{flight.longitude >= 0 ? "E" : "W"}
</span>
)}
</p>
</div>
)}
{flight.squawk && (
<div className="flex items-center gap-1.5">
<span
className={`h-3 w-3 text-center text-[8px] font-bold leading-3 ${
isEmergencySquawk(flight.squawk)
? "text-red-400"
: "text-white/25"
}`}
>
SQ
</span>
<p
className={`font-mono text-[11px] tabular-nums ${
isEmergencySquawk(flight.squawk)
? "text-red-400"
: "text-white/40"
}`}
>
{flight.squawk}
{isEmergencySquawk(flight.squawk) && (
<span className="ml-1.5 rounded bg-red-500/15 px-1.5 py-0.5 text-[9px] font-semibold tracking-wider text-red-400 uppercase">
{squawkLabel(flight.squawk)}
</span>
)}
</p>
</div>
)}
</div>
{onToggleFpv && (
<div className="mt-3">
<div className="h-px bg-linear-to-r from-transparent via-white/6 to-transparent" />
<button
type="button"
onClick={() =>
(isFpvActive || canEnterFpv) &&
flight &&
onToggleFpv(flight.icao24)
}
disabled={!isFpvActive && !canEnterFpv}
className={`flex h-6 w-6 items-center justify-center rounded-full transition-colors ${
isFpvActive
? "bg-emerald-500/20 text-emerald-400"
: !canEnterFpv
? "bg-white/4 text-white/15 cursor-not-allowed"
: "bg-white/6 text-white/40 hover:bg-white/12"
className={`mt-2 flex w-full items-center gap-1.5 text-left transition-colors ${
!isFpvActive && !canEnterFpv
? "opacity-35 cursor-not-allowed"
: ""
}`}
whileHover={
isFpvActive || canEnterFpv ? { scale: 1.1 } : {}
}
whileTap={isFpvActive || canEnterFpv ? { scale: 0.9 } : {}}
aria-label={
isFpvActive
? "Exit first person view"
@ -215,131 +337,44 @@ export function FlightCard({
: "FPV unavailable (no position data)"
}
>
<Eye className="h-3 w-3" />
</motion.button>
)}
<motion.button
<Eye
className={`h-3 w-3 ${isFpvActive ? "text-emerald-400" : "text-white/25"}`}
/>
<span
className={`text-[11px] font-medium tracking-wide uppercase ${isFpvActive ? "text-emerald-400/70" : "text-white/30"}`}
>
{isFpvActive
? "Exit First Person View"
: "First Person View"}
</span>
<ChevronRight
className={`ml-auto h-2.5 w-2.5 ${isFpvActive ? "text-emerald-400/40" : "text-white/20"}`}
/>
</button>
</div>
)}
<AircraftPhotos
photos={photos}
loading={photosLoading}
aircraft={photoAircraft}
error={photosError}
/>
<div className="mt-3">
<div className="h-px bg-linear-to-r from-transparent via-white/6 to-transparent" />
<button
type="button"
onClick={onClose}
className="flex h-6 w-6 items-center justify-center rounded-full bg-white/6 transition-colors hover:bg-white/12"
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
className="mt-2 flex w-full items-center gap-1.5 text-left transition-colors hover:opacity-70"
aria-label="Deselect flight"
>
<X className="h-3 w-3 text-white/40" />
</motion.button>
</div>
</div>
{company && (
<div className="mt-2.5 flex items-center gap-1.5">
<Building2 className="h-3 w-3 text-white/25" />
<p className="text-[11px] font-semibold tracking-wide text-white/55">
{company}
{model ? (
<span className="text-white/30"> · {model}</span>
) : null}
</p>
</div>
)}
<div className="mt-3 h-px bg-linear-to-r from-transparent via-white/6 to-transparent" />
<div className="mt-3 grid grid-cols-2 gap-3">
<Metric
icon={<ArrowUp className="h-3 w-3" />}
label="Altitude"
value={metersToFeet(flight.baroAltitude)}
/>
<Metric
icon={<Gauge className="h-3 w-3" />}
label="Speed"
value={msToKnots(flight.velocity)}
/>
<Metric
icon={<Compass className="h-3 w-3" />}
label="Heading"
value={
heading !== null && Number.isFinite(heading)
? `${Math.round(heading)}° ${cardinal}`
: "—"
}
/>
<Metric
icon={<ArrowDown className="h-3 w-3" />}
label="V/S"
value={
flight.verticalRate !== null &&
Number.isFinite(flight.verticalRate)
? `${flight.verticalRate > 0 ? "+" : ""}${Math.round(flight.verticalRate)} m/s`
: "—"
}
/>
</div>
<div className="mt-3 h-px bg-linear-to-r from-transparent via-white/6 to-transparent" />
<div className="mt-2.5 flex flex-col gap-1.5">
<div className="flex items-center gap-1.5">
<Globe className="h-3 w-3 text-white/25" />
<p className="text-[11px] font-medium tracking-wide text-white/40">
{flight.originCountry}
</p>
</div>
{cardinal && (
<div className="flex items-center gap-1.5">
<Navigation
className="h-3 w-3 text-white/25"
style={{
transform:
heading !== null && Number.isFinite(heading)
? `rotate(${heading}deg)`
: undefined,
}}
/>
<p className="text-[11px] font-medium tracking-wide text-white/40">
Heading {cardinal}
{flight.latitude !== null &&
flight.longitude !== null &&
Number.isFinite(flight.latitude) &&
Number.isFinite(flight.longitude) && (
<span className="text-white/20">
{" "}
· {Math.abs(flight.latitude).toFixed(2)}°
{flight.latitude >= 0 ? "N" : "S"},{" "}
{Math.abs(flight.longitude).toFixed(2)}°
{flight.longitude >= 0 ? "E" : "W"}
</span>
)}
</p>
</div>
)}
{flight.squawk && (
<div className="flex items-center gap-1.5">
<span
className={`h-3 w-3 text-center text-[8px] font-bold leading-3 ${
isEmergencySquawk(flight.squawk)
? "text-red-400"
: "text-white/25"
}`}
>
SQ
<X className="h-3 w-3 text-white/25" />
<span className="text-[11px] font-medium tracking-wide text-white/30 uppercase">
Close
</span>
<p
className={`font-mono text-[11px] font-medium tracking-wide ${
isEmergencySquawk(flight.squawk)
? "text-red-400"
: "text-white/40"
}`}
>
{flight.squawk}
{isEmergencySquawk(flight.squawk) && (
<span className="ml-1.5 rounded bg-red-500/15 px-1.5 py-0.5 text-[9px] font-semibold tracking-wider text-red-400 uppercase">
{squawkLabel(flight.squawk)}
</span>
)}
</p>
</div>
)}
</button>
</div>
</div>
</div>
</motion.div>
@ -379,13 +414,13 @@ function Metric({
}) {
return (
<div className="flex flex-col gap-1">
<div className="flex items-center gap-1.5 text-white/30">
<div className="flex items-center gap-1.5 text-white/25">
{icon}
<span className="text-[10px] font-medium tracking-wider uppercase">
<span className="text-[10px] font-medium tracking-widest uppercase">
{label}
</span>
</div>
<p className="text-[13px] font-semibold tracking-tight text-white/90">
<p className="text-sm font-semibold tabular-nums text-white/90">
{value}
</p>
</div>

View File

@ -0,0 +1,69 @@
"use client";
import { useState, useEffect } from "react";
import { Camera, ImageOff } from "lucide-react";
import type { NormalizedPhoto } from "@/hooks/use-aircraft-photos";
type HeroBannerProps = {
photo: NormalizedPhoto | null;
loading: boolean;
};
export function HeroBanner({ photo, loading }: HeroBannerProps) {
const [loaded, setLoaded] = useState(false);
const [failed, setFailed] = useState(false);
useEffect(() => {
setLoaded(false);
setFailed(false);
}, [photo?.id]);
const hasPhoto = photo != null && !failed;
return (
<div className="relative h-36 w-full overflow-hidden bg-white/5">
{/* Skeleton while loading */}
{loading && !hasPhoto && (
<span
aria-hidden
className="absolute inset-0 animate-pulse bg-linear-to-br from-white/5 via-white/8 to-white/5"
/>
)}
{/* No image placeholder */}
{!loading && !hasPhoto && (
<div className="flex h-full w-full flex-col items-center justify-center gap-1.5 text-white/20">
<ImageOff className="h-6 w-6" />
<span className="text-[10px] font-medium">No photo available</span>
</div>
)}
{/* Actual image */}
{photo && !failed && (
<>
{!loaded && (
<span
aria-hidden
className="absolute inset-0 animate-pulse bg-linear-to-br from-white/5 via-white/8 to-white/5"
/>
)}
<img
src={photo.thumbnail}
alt="Aircraft"
onLoad={() => setLoaded(true)}
onError={() => setFailed(true)}
className={`h-full w-full object-cover transition-opacity duration-300 ${loaded ? "opacity-100" : "opacity-0"}`}
draggable={false}
/>
<span className="pointer-events-none absolute inset-0 bg-linear-to-t from-black/40 via-black/5 to-transparent" />
{photo.photographer && loaded && (
<span className="absolute bottom-2 right-2.5 flex items-center gap-1 rounded-full bg-black/40 px-2 py-0.5 text-[9px] font-medium text-white/60 backdrop-blur-sm">
<Camera className="h-2.5 w-2.5" />
{photo.photographer}
</span>
)}
</>
)}
</div>
);
}

View File

@ -4,11 +4,12 @@ import { useEffect, useRef } from "react";
import { motion, AnimatePresence } from "motion/react";
import { X, Keyboard } from "lucide-react";
const SHORTCUTS = [
export const SHORTCUTS = [
{ key: "N", description: "North up" },
{ key: "R", description: "Reset view" },
{ key: "O", description: "Toggle orbit" },
{ key: "/", description: "Open search" },
{ key: "⌘K", description: "Open search (anywhere)" },
{ key: "F", description: "First person view" },
{ key: "?", description: "Shortcuts help" },
{ key: "Esc", description: "Close / Deselect" },

View File

@ -0,0 +1,295 @@
"use client";
import { useState, useEffect } from "react";
export type NormalizedPhoto = {
id: string;
url: string;
thumbnail: string;
photographer: string | null;
location: string | null;
dateTaken: string | null;
link: string | null;
};
export type AircraftDetails = {
registration: string;
manufacturer: string | null;
type: string | null;
typeCode: string | null;
owner: string | null;
airline: string | null;
};
export type UseAircraftPhotosResult = {
photos: NormalizedPhoto[];
aircraft: AircraftDetails | null;
loading: boolean;
error: boolean;
};
const CACHE_TTL_MS = 10 * 60_000;
const NEGATIVE_TTL_MS = 2 * 60_000;
const CACHE_MAX = 200;
const FETCH_TIMEOUT_MS = 10_000;
type CacheEntry = {
aircraft: AircraftDetails | null;
photos: NormalizedPhoto[];
ts: number;
ttl: number;
};
const cache = new Map<string, CacheEntry>();
function getCached(key: string): CacheEntry | null {
const entry = cache.get(key);
if (!entry) return null;
if (Date.now() - entry.ts > entry.ttl) {
cache.delete(key);
return null;
}
return entry;
}
function putCache(
key: string,
aircraft: AircraftDetails | null,
photos: NormalizedPhoto[],
): void {
if (cache.size >= CACHE_MAX) {
const oldest = cache.keys().next().value;
if (oldest !== undefined) cache.delete(oldest);
}
cache.set(key, {
aircraft,
photos,
ts: Date.now(),
ttl: photos.length > 0 ? CACHE_TTL_MS : NEGATIVE_TTL_MS,
});
}
type FetchResult = {
aircraft: AircraftDetails | null;
photos: NormalizedPhoto[];
};
async function fetchJson<T>(
url: string,
signal?: AbortSignal,
): Promise<T | null> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
const onAbort = () => controller.abort();
signal?.addEventListener("abort", onAbort);
try {
const res = await fetch(url, {
signal: controller.signal,
headers: { Accept: "application/json" },
});
if (!res.ok) return null;
return (await res.json()) as T;
} catch {
return null;
} finally {
clearTimeout(timer);
signal?.removeEventListener("abort", onAbort);
}
}
type HexDbAircraft = {
ModeS?: string;
Registration?: string;
Manufacturer?: string;
ICAOTypeCode?: string;
Type?: string;
RegisteredOwners?: string;
OperatorFlagCode?: string;
};
async function fetchAircraftDetails(
icao24: string,
signal?: AbortSignal,
): Promise<AircraftDetails | null> {
const data = await fetchJson<HexDbAircraft>(
`https://hexdb.io/api/v1/aircraft/${encodeURIComponent(icao24)}`,
signal,
);
if (!data?.Registration) return null;
return {
registration: data.Registration,
manufacturer: data.Manufacturer ?? null,
type: data.Type ?? null,
typeCode: data.ICAOTypeCode ?? null,
owner: data.RegisteredOwners ?? null,
airline: null,
};
}
type JetApiImage = {
Image?: string;
Thumbnail?: string;
Link?: string;
Photographer?: string;
Location?: string;
DateTaken?: string;
Aircraft?: string;
Airline?: string;
};
type JetApiResponse = {
JetPhotos?: {
Reg?: string;
Images?: JetApiImage[];
};
FlightRadar?: {
Aircraft?: string;
Airline?: string;
Operator?: string;
TypeCode?: string;
ModeS?: string;
};
};
function normalizePhotos(raw: JetApiImage[] | undefined): NormalizedPhoto[] {
if (!raw || !Array.isArray(raw)) return [];
const seen = new Set<string>();
const out: NormalizedPhoto[] = [];
for (const img of raw) {
const fullUrl = typeof img.Image === "string" ? img.Image : null;
if (!fullUrl) continue;
if (seen.has(fullUrl)) continue;
seen.add(fullUrl);
const thumb =
typeof img.Thumbnail === "string" && img.Thumbnail
? img.Thumbnail
: fullUrl;
out.push({
id: `jp-${out.length}-${fullUrl.slice(-16).replace(/[^a-zA-Z0-9]/g, "")}`,
url: fullUrl,
thumbnail: thumb,
photographer:
typeof img.Photographer === "string" && img.Photographer
? img.Photographer
: null,
location:
typeof img.Location === "string" && img.Location ? img.Location : null,
dateTaken:
typeof img.DateTaken === "string" && img.DateTaken
? img.DateTaken
: null,
link: typeof img.Link === "string" && img.Link ? img.Link : null,
});
}
return out;
}
async function fetchPhotosViaProxy(
reg: string,
signal?: AbortSignal,
): Promise<{ photos: NormalizedPhoto[]; airline: string | null }> {
const data = await fetchJson<JetApiResponse>(
`/api/aircraft-photos?reg=${encodeURIComponent(reg)}`,
signal,
);
if (!data) return { photos: [], airline: null };
const photos = normalizePhotos(data.JetPhotos?.Images);
const airline =
typeof data.FlightRadar?.Airline === "string"
? data.FlightRadar.Airline
: null;
return { photos, airline };
}
async function fetchAll(
icao24: string,
signal?: AbortSignal,
): Promise<FetchResult> {
const aircraft = await fetchAircraftDetails(icao24, signal);
if (!aircraft) return { aircraft: null, photos: [] };
const { photos, airline } = await fetchPhotosViaProxy(
aircraft.registration,
signal,
);
const enriched: AircraftDetails = {
...aircraft,
airline: airline ?? aircraft.owner,
};
return { aircraft: enriched, photos };
}
export function useAircraftPhotos(
icao24: string | null,
): UseAircraftPhotosResult {
const [photos, setPhotos] = useState<NormalizedPhoto[]>([]);
const [aircraft, setAircraft] = useState<AircraftDetails | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
useEffect(() => {
if (!icao24) {
setPhotos([]);
setAircraft(null);
setLoading(false);
setError(false);
return;
}
const normalized = icao24.toLowerCase();
const cached = getCached(normalized);
if (cached) {
setPhotos(cached.photos);
setAircraft(cached.aircraft);
setLoading(false);
setError(false);
return;
}
let cancelled = false;
const controller = new AbortController();
setLoading(true);
setError(false);
setPhotos([]);
setAircraft(null);
fetchAll(normalized, controller.signal).then(
(result) => {
if (cancelled) return;
putCache(normalized, result.aircraft, result.photos);
setPhotos(result.photos);
setAircraft(result.aircraft);
setLoading(false);
},
() => {
if (cancelled) return;
putCache(normalized, null, []);
setLoading(false);
setError(true);
},
);
return () => {
cancelled = true;
controller.abort();
};
}, [icao24]);
return { photos, aircraft, loading, error };
}

View File

@ -0,0 +1,248 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { fetchFlightByIcao24, type FlightState } from "@/lib/opensky";
import { cityFromFlight } from "@/components/flight-tracker-random";
import {
syncFpvToUrl,
GITHUB_REPO_API,
} from "@/components/flight-tracker-utils";
import type { City } from "@/lib/cities";
// ── Types ──────────────────────────────────────────────────────────────
export interface UseFlightMonitorsOptions {
pendingFpvRef: React.RefObject<string | null>;
fpvIcao24: string | null;
fpvFlight: FlightState | null;
followIcao24: string | null;
followFlight: FlightState | null;
selectedIcao24: string | null;
selectedFlight: FlightState | null;
displayFlights: FlightState[];
activeCity: City;
rateLimited: boolean;
setSelectedIcao24: (v: string | null) => void;
setFpvIcao24: (v: string | null) => void;
setFollowIcao24: (v: string | null) => void;
setCityOverride: (v: City) => void;
setFpvSeedCenter: (v: { lng: number; lat: number } | null) => void;
}
export interface UseFlightMonitorsResult {
repoStars: number | null;
}
// ── Hook ───────────────────────────────────────────────────────────────
export function useFlightMonitors(
opts: UseFlightMonitorsOptions,
): UseFlightMonitorsResult {
const {
pendingFpvRef,
fpvIcao24,
fpvFlight,
followIcao24,
followFlight,
selectedIcao24,
selectedFlight,
displayFlights,
activeCity,
rateLimited,
setSelectedIcao24,
setFpvIcao24,
setFollowIcao24,
setCityOverride,
setFpvSeedCenter,
} = opts;
const [repoStars, setRepoStars] = useState<number | null>(null);
// ── Pending FPV resolution ───────────────────────────────────────
const fpvLookupDoneRef = useRef(false);
useEffect(() => {
const pending = pendingFpvRef.current;
if (!pending || fpvIcao24) return;
const match = displayFlights.find(
(f) => f.icao24.toLowerCase() === pending,
);
if (match && match.longitude != null && match.latitude != null) {
if (match.onGround) {
(pendingFpvRef as React.MutableRefObject<string | null>).current = null;
syncFpvToUrl(null, activeCity);
setSelectedIcao24(match.icao24);
return;
}
(pendingFpvRef as React.MutableRefObject<string | null>).current = null;
fpvLookupDoneRef.current = false;
setFpvSeedCenter({ lng: match.longitude, lat: match.latitude });
setFpvIcao24(pending);
setFollowIcao24(null);
return;
}
if (!fpvLookupDoneRef.current && displayFlights.length > 0) {
fpvLookupDoneRef.current = true;
const controller = new AbortController();
fetchFlightByIcao24(pending, controller.signal)
.then((result) => {
if (
result.flight &&
result.flight.longitude != null &&
result.flight.latitude != null &&
!result.flight.onGround &&
pendingFpvRef.current === pending
) {
const focusCity = cityFromFlight(result.flight);
if (focusCity) {
setCityOverride(focusCity);
}
setFpvSeedCenter({
lng: result.flight.longitude,
lat: result.flight.latitude,
});
(pendingFpvRef as React.MutableRefObject<string | null>).current =
null;
setFpvIcao24(pending);
setFollowIcao24(null);
} else if (pendingFpvRef.current === pending) {
(pendingFpvRef as React.MutableRefObject<string | null>).current =
null;
syncFpvToUrl(null, activeCity);
if (result.flight) {
setSelectedIcao24(result.flight.icao24);
}
}
})
.catch(() => {
if (pendingFpvRef.current === pending) {
(pendingFpvRef as React.MutableRefObject<string | null>).current =
null;
}
});
return () => controller.abort();
}
}, [
displayFlights,
fpvIcao24,
activeCity,
pendingFpvRef,
setSelectedIcao24,
setFpvIcao24,
setFollowIcao24,
setCityOverride,
setFpvSeedCenter,
]);
// ── FPV miss counting ────────────────────────────────────────────
const fpvMissCountRef = useRef(0);
useEffect(() => {
if (!fpvIcao24) {
fpvMissCountRef.current = 0;
return;
}
if (fpvFlight) {
fpvMissCountRef.current = 0;
if (fpvFlight.onGround) {
const exitIcao = fpvIcao24;
const timer = setTimeout(() => {
setSelectedIcao24(exitIcao);
setFpvIcao24(null);
}, 0);
return () => clearTimeout(timer);
}
} else {
if (!rateLimited) {
fpvMissCountRef.current += 1;
}
if (fpvMissCountRef.current >= 3) {
const exitIcao = fpvIcao24;
const timer = setTimeout(() => {
setSelectedIcao24(exitIcao);
setFpvIcao24(null);
}, 0);
return () => clearTimeout(timer);
}
}
}, [
fpvIcao24,
fpvFlight,
rateLimited,
displayFlights,
setSelectedIcao24,
setFpvIcao24,
]);
// ── Follow miss counting ─────────────────────────────────────────
const followMissCountRef = useRef(0);
useEffect(() => {
if (!followIcao24) {
followMissCountRef.current = 0;
return;
}
if (followFlight) {
followMissCountRef.current = 0;
} else {
followMissCountRef.current += 1;
if (followMissCountRef.current >= 3) {
const timer = setTimeout(() => setFollowIcao24(null), 0);
return () => clearTimeout(timer);
}
}
}, [followIcao24, followFlight, displayFlights, setFollowIcao24]);
// ── Selected flight missing timeout ──────────────────────────────
const missingSinceRef = useRef<number | null>(null);
useEffect(() => {
if (!selectedIcao24) {
missingSinceRef.current = null;
return;
}
if (selectedFlight) {
missingSinceRef.current = null;
return;
}
const now = Date.now();
if (missingSinceRef.current == null) {
missingSinceRef.current = now;
return;
}
if (now - missingSinceRef.current >= 60_000) {
const timer = setTimeout(() => setSelectedIcao24(null), 0);
missingSinceRef.current = null;
return () => clearTimeout(timer);
}
}, [selectedIcao24, selectedFlight, displayFlights, setSelectedIcao24]);
// ── Repo stars ───────────────────────────────────────────────────
useEffect(() => {
let mounted = true;
async function loadRepoStars() {
try {
const res = await fetch(GITHUB_REPO_API, { cache: "no-store" });
if (!res.ok) return;
const data = (await res.json()) as { stargazers_count?: number };
if (mounted && typeof data.stargazers_count === "number") {
setRepoStars(data.stargazers_count);
}
} catch {
/* silent fallback */
}
}
loadRepoStars();
return () => {
mounted = false;
};
}, []);
return { repoStars };
}

View File

@ -13,6 +13,7 @@ type TrackCacheEntry = {
const DEFAULT_REFRESH_MS = 0;
const TRACK_CACHE_TTL_MS_EFFECTIVE = 10 * 60_000;
const NEGATIVE_CACHE_TTL_MS_EFFECTIVE = 60_000;
const TRACK_CACHE_MAX_ENTRIES = 100;
const trackCache = new Map<string, TrackCacheEntry>();
@ -28,7 +29,9 @@ function loadGlobalBackoff(): void {
if (typeof window === "undefined") return;
try {
const nextAllowedRaw = sessionStorage.getItem(GLOBAL_BACKOFF_KEY);
const nextAllowed = nextAllowedRaw ? Number.parseInt(nextAllowedRaw, 10) : 0;
const nextAllowed = nextAllowedRaw
? Number.parseInt(nextAllowedRaw, 10)
: 0;
if (Number.isFinite(nextAllowed) && nextAllowed > 0) {
globalNextAllowedAt = Math.max(globalNextAllowedAt, nextAllowed);
}
@ -36,7 +39,10 @@ function loadGlobalBackoff(): void {
const backoffRaw = sessionStorage.getItem(GLOBAL_BACKOFF_MS_KEY);
const backoff = backoffRaw ? Number.parseInt(backoffRaw, 10) : 0;
if (Number.isFinite(backoff) && backoff > 0) {
globalBackoffMs = Math.min(GLOBAL_BACKOFF_MAX_MS, Math.max(60_000, backoff));
globalBackoffMs = Math.min(
GLOBAL_BACKOFF_MAX_MS,
Math.max(60_000, backoff),
);
}
} catch {
// ignore
@ -112,6 +118,13 @@ export function useFlightTrack(
async function load() {
const now = Date.now();
// Sweep stale entries to bound memory growth over time
for (const [k, entry] of trackCache) {
if (now - entry.fetchedAt > cacheTtlMs(entry.track)) {
trackCache.delete(k);
}
}
if (now < globalNextAllowedAt) {
return;
}
@ -165,6 +178,14 @@ export function useFlightTrack(
track: nextTrack,
});
// Evict oldest entries when cache exceeds max size (FIFO via Map insertion order)
if (trackCache.size > TRACK_CACHE_MAX_ENTRIES) {
const oldestKey = trackCache.keys().next().value as
| string
| undefined;
if (oldestKey && oldestKey !== key) trackCache.delete(oldestKey);
}
setFetchedAtMs(fetchedAt);
setTrack(nextTrack);

View File

@ -25,16 +25,25 @@ export function useKeyboardShortcuts(actions: ShortcutActions) {
useEffect(() => {
function handler(e: KeyboardEvent) {
const target = e.target as HTMLElement;
if (INPUT_TAGS.has(target.tagName) || target.isContentEditable) return;
const dialogOpen = !!document.querySelector(
'[role="dialog"][aria-modal="true"]',
);
if (e.ctrlKey || e.metaKey || e.altKey) return;
const a = ref.current;
// Ctrl/Cmd+K opens search from anywhere (even inside inputs)
if ((e.ctrlKey || e.metaKey) && e.key === "k") {
e.preventDefault();
a.onOpenSearch();
return;
}
// Don't intercept other shortcuts when focused in input fields
if (INPUT_TAGS.has(target.tagName) || target.isContentEditable) return;
if (e.ctrlKey || e.metaKey || e.altKey) return;
if (e.key === "Escape") {
if (!dialogOpen) a.onDeselect();
return;

View File

@ -0,0 +1,80 @@
"use client";
import { useMemo } from "react";
import { stitchHistoricalTrail } from "@/lib/trail-stitching";
import type { TrailEntry } from "@/hooks/use-trail-history";
import type { FlightState } from "@/lib/opensky";
import type { FlightTrack } from "@/lib/opensky";
/**
* Merges the live trail history with a fetched historical track for the
* currently selected flight, stitching them seamlessly via
* `stitchHistoricalTrail`.
*/
export function useMergedTrails(
selectedIcao24: string | null,
selectedTrack: FlightTrack | null,
selectedTrackFetchedAtMs: number,
displayTrails: TrailEntry[],
displayFlights: FlightState[],
): TrailEntry[] {
return useMemo(() => {
if (!selectedIcao24 || !selectedTrack) return displayTrails;
const flight =
displayFlights.find((f) => f.icao24 === selectedIcao24) ?? null;
const livePos: [number, number] | null =
flight && flight.longitude != null && flight.latitude != null
? [flight.longitude, flight.latitude]
: null;
const existingTrail =
displayTrails.find((t) => t.icao24 === selectedIcao24) ?? null;
const stitchResult = stitchHistoricalTrail(
selectedTrack,
existingTrail,
livePos,
flight,
selectedTrackFetchedAtMs,
);
if (!stitchResult.valid || stitchResult.path.length < 2) {
return displayTrails;
}
const { path: trackPositions, altitudes: trackAltitudes } = stitchResult;
const out = displayTrails.map((t) => {
if (t.icao24 !== selectedIcao24) return t;
const baroAltitude =
trackAltitudes[trackAltitudes.length - 1] ?? t.baroAltitude ?? null;
return {
...t,
path: trackPositions,
altitudes: trackAltitudes,
baroAltitude,
fullHistory: true,
};
});
if (!out.some((t) => t.icao24 === selectedIcao24)) {
out.push({
icao24: selectedIcao24,
path: trackPositions,
altitudes: trackAltitudes,
baroAltitude: trackAltitudes[trackAltitudes.length - 1] ?? null,
fullHistory: true,
});
}
return out;
}, [
selectedIcao24,
selectedTrack,
selectedTrackFetchedAtMs,
displayTrails,
displayFlights,
]);
}

View File

@ -23,9 +23,10 @@ export type Settings = {
showShadows: boolean;
showAltitudeColors: boolean;
fpvChaseDistance: number;
globeMode: boolean;
};
const TRAIL_THICKNESS_MIN = 1;
const TRAIL_THICKNESS_MIN = 0.5;
const TRAIL_THICKNESS_MAX = 8;
const TRAIL_DISTANCE_MIN = 12;
const TRAIL_DISTANCE_MAX = 100;
@ -61,11 +62,12 @@ const DEFAULT_SETTINGS: Settings = {
orbitSpeed: 0.06,
orbitDirection: "clockwise",
showTrails: true,
trailThickness: 2,
trailThickness: 1.3,
trailDistance: 40,
showShadows: true,
showAltitudeColors: true,
fpvChaseDistance: 0.0048,
globeMode: false,
};
const STORAGE_KEY = "aeris:settings";
@ -99,7 +101,8 @@ function isValidSettings(obj: unknown): obj is Settings {
typeof s.fpvChaseDistance === "number" &&
Number.isFinite(s.fpvChaseDistance) &&
s.fpvChaseDistance >= FPV_CHASE_DISTANCE_MIN &&
s.fpvChaseDistance <= FPV_CHASE_DISTANCE_MAX
s.fpvChaseDistance <= FPV_CHASE_DISTANCE_MAX &&
typeof s.globeMode === "boolean"
);
}

View File

@ -73,7 +73,10 @@ class TrailStore {
private seen = new Set<string>();
private bootstrapUpdatesRemaining = BOOTSTRAP_UPDATES;
private filterAltitude(id: string, rawAltitude: number | null): number | null {
private filterAltitude(
id: string,
rawAltitude: number | null,
): number | null {
if (rawAltitude == null) return null;
const state =
@ -91,7 +94,8 @@ class TrailStore {
const absoluteDeviations = state.recent.map((x) => Math.abs(x - med));
const mad = median(absoluteDeviations);
const outlierThreshold =
ALTITUDE_OUTLIER_BASE_METERS + ALTITUDE_OUTLIER_SCALE * Math.max(120, mad);
ALTITUDE_OUTLIER_BASE_METERS +
ALTITUDE_OUTLIER_SCALE * Math.max(120, mad);
const isOutlier = Math.abs(rawAltitude - med) > outlierThreshold;
state.outlierStreak = isOutlier ? state.outlierStreak + 1 : 0;
@ -104,10 +108,7 @@ class TrailStore {
: ALTITUDE_SMOOTHING_ALPHA_GUARDED;
const delta = rawAltitude - state.filtered;
const clampedDelta = Math.max(
-maxStep,
Math.min(maxStep, delta),
);
const clampedDelta = Math.max(-maxStep, Math.min(maxStep, delta));
const filtered = state.filtered + clampedDelta * alpha;
state.filtered = filtered;
@ -158,6 +159,7 @@ class TrailStore {
const dy = pos.position[1] - last[1];
if (dx * dx + dy * dy > JUMP_THRESHOLD_DEG * JUMP_THRESHOLD_DEG) {
trail.length = 0;
this.altitudeStates.delete(id);
}
trail.push(pos);

View File

@ -26,7 +26,8 @@ function lerpColor(a: RGB, b: RGB, t: number): RGB {
export function altitudeToColor(
altitude: number | null,
): [number, number, number, number] {
if (altitude === null || !Number.isFinite(altitude)) return [100, 100, 100, 200];
if (altitude === null || !Number.isFinite(altitude))
return [100, 100, 100, 200];
const normalized = Math.min(Math.max(altitude / MAX_ALTITUDE_METERS, 0), 1);
const t = Math.pow(normalized, 0.4);

View File

@ -21,3 +21,227 @@ export function unwrapLngPath(
}
return out;
}
// ── Great-circle utilities ─────────────────────────────────────────────
const DEG2RAD = Math.PI / 180;
const RAD2DEG = 180 / Math.PI;
/**
* Angular distance between two points in radians (Haversine formula).
* Accurate for all distances on the sphere.
*/
export function haversineDistanceRad(
lng1: number,
lat1: number,
lng2: number,
lat2: number,
): number {
const la1 = lat1 * DEG2RAD;
const la2 = lat2 * DEG2RAD;
const dLat = (lat2 - lat1) * DEG2RAD;
const dLng = (lng2 - lng1) * DEG2RAD;
const a =
Math.sin(dLat / 2) ** 2 +
Math.cos(la1) * Math.cos(la2) * Math.sin(dLng / 2) ** 2;
return 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
/**
* Approximate great-circle distance in degrees (for quick threshold checks).
*/
export function gcDistanceDeg(
lng1: number,
lat1: number,
lng2: number,
lat2: number,
): number {
return haversineDistanceRad(lng1, lat1, lng2, lat2) * RAD2DEG;
}
/**
* Intermediate point on a great circle at fraction `t` ∈ [0, 1].
* Uses the standard spherical interpolation formula.
* Reference: https://www.movable-type.co.uk/scripts/latlong.html
*/
export function greatCircleIntermediate(
lng1: number,
lat1: number,
lng2: number,
lat2: number,
t: number,
): [number, number] {
// Degenerate cases
if (t <= 0) return [lng1, lat1];
if (t >= 1) return [lng2, lat2];
const la1 = lat1 * DEG2RAD;
const lo1 = lng1 * DEG2RAD;
const la2 = lat2 * DEG2RAD;
const lo2 = lng2 * DEG2RAD;
const d = haversineDistanceRad(lng1, lat1, lng2, lat2);
// Very short distance — linear interpolation is fine and avoids division by ~0
if (d < 1e-9) {
return [lng1 + (lng2 - lng1) * t, lat1 + (lat2 - lat1) * t];
}
const sinD = Math.sin(d);
const a = Math.sin((1 - t) * d) / sinD;
const b = Math.sin(t * d) / sinD;
const x =
a * Math.cos(la1) * Math.cos(lo1) + b * Math.cos(la2) * Math.cos(lo2);
const y =
a * Math.cos(la1) * Math.sin(lo1) + b * Math.cos(la2) * Math.sin(lo2);
const z = a * Math.sin(la1) + b * Math.sin(la2);
const lat = Math.atan2(z, Math.sqrt(x * x + y * y)) * RAD2DEG;
const lng = Math.atan2(y, x) * RAD2DEG;
return [lng, lat];
}
/**
* Densify a path segment along a great-circle arc.
* Inserts intermediate points between each consecutive pair of points
* when the segment angular distance exceeds `thresholdDeg`.
*
* Works with [lng, lat, altitude] elevated points. Altitude is linearly
* interpolated.
*/
export function densifyGreatCircle(
path: Array<[number, number, number]>,
thresholdDeg: number = 0.5,
maxPointsPerSegment: number = 32,
): Array<[number, number, number]> {
if (path.length < 2) return path.slice();
const result: Array<[number, number, number]> = [path[0]];
for (let i = 0; i < path.length - 1; i++) {
const [lng1, lat1, alt1] = path[i];
const [lng2, lat2, alt2] = path[i + 1];
const dist = gcDistanceDeg(lng1, lat1, lng2, lat2);
if (dist > thresholdDeg) {
const n = Math.min(
maxPointsPerSegment,
Math.max(2, Math.ceil(dist / thresholdDeg)),
);
for (let j = 1; j < n; j++) {
const t = j / n;
const [lng, lat] = greatCircleIntermediate(lng1, lat1, lng2, lat2, t);
const alt = alt1 + (alt2 - alt1) * t;
result.push([lng, lat, alt]);
}
}
result.push(path[i + 1]);
}
return result;
}
/**
* Densify a 2D path along great-circle arcs.
*/
export function densifyGreatCircle2D(
path: Array<[number, number]>,
thresholdDeg: number = 0.5,
maxPointsPerSegment: number = 32,
): Array<[number, number]> {
if (path.length < 2) return path.slice();
const result: Array<[number, number]> = [path[0]];
for (let i = 0; i < path.length - 1; i++) {
const [lng1, lat1] = path[i];
const [lng2, lat2] = path[i + 1];
const dist = gcDistanceDeg(lng1, lat1, lng2, lat2);
if (dist > thresholdDeg) {
const n = Math.min(
maxPointsPerSegment,
Math.max(2, Math.ceil(dist / thresholdDeg)),
);
for (let j = 1; j < n; j++) {
const t = j / n;
const [lng, lat] = greatCircleIntermediate(lng1, lat1, lng2, lat2, t);
result.push([lng, lat]);
}
}
result.push(path[i + 1]);
}
return result;
}
/**
* Check if a path segment crosses the antimeridian (|Δlng| > 180).
* Returns true if the segment wraps around.
*/
export function crossesAntimeridian(lng1: number, lng2: number): boolean {
return Math.abs(lng2 - lng1) > 180;
}
/**
* Split a path into separate segments at antimeridian crossings.
* Each segment is a contiguous array of coordinates that do NOT cross
* the antimeridian, suitable for MapLibre GeoJSON line rendering on a globe.
*/
export function splitAtAntimeridian(
path: Array<[number, number]>,
): Array<Array<[number, number]>> {
if (path.length < 2) return [path.slice()];
const segments: Array<Array<[number, number]>> = [];
let current: Array<[number, number]> = [path[0]];
for (let i = 1; i < path.length; i++) {
const prevLng = path[i - 1][0];
const currLng = path[i][0];
if (crossesAntimeridian(prevLng, currLng)) {
// Compute the crossing latitude by linear interpolation
const prevLat = path[i - 1][1];
const currLat = path[i][1];
// Normalize longitudes for interpolation
let norm1 = prevLng;
let norm2 = currLng;
if (norm2 - norm1 > 180) norm2 -= 360;
else if (norm1 - norm2 > 180) norm2 += 360;
const dLng = norm2 - norm1;
if (Math.abs(dLng) > 1e-10) {
// Find t where longitude crosses ±180
const crossLng = prevLng > 0 ? 180 : -180;
const t = (crossLng - norm1) / dLng;
const crossLat = prevLat + (currLat - prevLat) * t;
// End current segment at the crossing
current.push([crossLng, crossLat]);
segments.push(current);
// Start new segment from the other side
current = [[-crossLng, crossLat]];
} else {
segments.push(current);
current = [];
}
}
current.push(path[i]);
}
if (current.length > 0) {
segments.push(current);
}
return segments.filter((s) => s.length >= 2);
}

View File

@ -1,5 +1,67 @@
export type MapStyleSpec = string | Record<string, unknown>;
export type TerrainProfile = "none" | "dark";
export const TERRAIN_DEM_SOURCE_ID = "aeris-terrain-dem";
export const TERRAIN_HILLSHADE_LAYER_ID = "aeris-terrain-hillshade";
/**
* Single shared DEM source for both terrain mesh AND hillshade.
* Uses AWS Terrain Tiles (Mapzen/Tilezen) — free, reliable, globally cached on S3.
* Terrarium encoding: elevation = (R * 256 + G + B / 256) - 32768
* maxzoom capped at 12 (terrain detail beyond that is imperceptible for flight tracking).
*/
export function createTerrainDemSource(): Record<string, unknown> {
return {
type: "raster-dem",
tiles: [
"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png",
],
encoding: "terrarium",
tileSize: 256,
maxzoom: 12,
volatile: true,
};
}
export const DARK_TERRAIN_SPEC: Record<string, unknown> = {
source: TERRAIN_DEM_SOURCE_ID,
exaggeration: 0.8, // MapLibre terrain.exaggeration only accepts a number, not an expression
};
export const DARK_TERRAIN_HILLSHADE_LAYER: Record<string, unknown> = {
id: TERRAIN_HILLSHADE_LAYER_ID,
type: "hillshade",
source: TERRAIN_DEM_SOURCE_ID, // reuse same DEM source — no duplicate tile fetches
minzoom: 3, // skip hillshade at globe zoom (invisible anyway, saves GPU)
layout: { visibility: "visible" },
paint: {
"hillshade-shadow-color": "#040608",
"hillshade-highlight-color": "rgba(180,195,210,0.12)",
"hillshade-accent-color": "#0d1117",
"hillshade-exaggeration": [
"interpolate",
["linear"],
["zoom"],
3,
0, // invisible at low zoom
5,
0.3, // fade in gently
8,
0.5, // full hillshade at regional zoom
],
},
};
export const DARK_TERRAIN_SKY: Record<string, unknown> = {
"sky-color": "#070a0d",
"sky-horizon-blend": 0.5,
"horizon-color": "#0a0e12",
"fog-color": "#070a0d",
"fog-ground-blend": 0.5,
"atmosphere-blend": ["interpolate", ["linear"], ["zoom"], 0, 0.8, 5, 0],
};
export type MapStyle = {
id: string;
name: string;
@ -7,6 +69,7 @@ export type MapStyle = {
preview: string;
previewUrl: string;
dark: boolean;
terrainProfile?: TerrainProfile;
};
const SATELLITE_STYLE: Record<string, unknown> = {
@ -26,21 +89,6 @@ const SATELLITE_STYLE: Record<string, unknown> = {
layers: [{ id: "satellite", type: "raster", source: "esri-satellite" }],
};
const TERRAIN_STYLE: Record<string, unknown> = {
version: 8,
sources: {
opentopomap: {
type: "raster",
tiles: ["https://tile.opentopomap.org/{z}/{x}/{y}.png"],
tileSize: 256,
maxzoom: 17,
attribution:
"&copy; <a href='https://opentopomap.org/'>OpenTopoMap</a> (<a href='https://creativecommons.org/licenses/by-sa/3.0/'>CC-BY-SA</a>) · &copy; <a href='https://www.openstreetmap.org/copyright'>OpenStreetMap</a> contributors",
},
},
layers: [{ id: "terrain", type: "raster", source: "opentopomap" }],
};
const ESRI_TOPO_STYLE: Record<string, unknown> = {
version: 8,
sources: {
@ -58,45 +106,6 @@ const ESRI_TOPO_STYLE: Record<string, unknown> = {
layers: [{ id: "esri-topo", type: "raster", source: "esri-topo" }],
};
const SHADED_RELIEF_STYLE: Record<string, unknown> = {
version: 8,
sources: {
"esri-satellite": {
type: "raster",
tiles: [
"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
],
tileSize: 256,
maxzoom: 18,
attribution:
"&copy; <a href='https://www.esri.com/'>Esri</a>, Maxar, Earthstar Geographics",
},
"terrain-dem": {
type: "raster-dem",
tiles: [
"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png",
],
tileSize: 256,
maxzoom: 15,
encoding: "terrarium",
attribution:
"<a href='https://github.com/tilezen/joerd'>Mapzen/Tilezen</a> · AWS Open Data",
},
},
terrain: {
source: "terrain-dem",
exaggeration: 1.5,
},
sky: {
"sky-color": "#76a8d6",
"horizon-color": "#d4e4f0",
"fog-color": "#c8d8e8",
"sky-horizon-blend": 0.5,
"horizon-fog-blend": 0.1,
},
layers: [{ id: "satellite-base", type: "raster", source: "esri-satellite" }],
};
export const MAP_STYLES: MapStyle[] = [
{
id: "dark",
@ -107,6 +116,16 @@ export const MAP_STYLES: MapStyle[] = [
previewUrl: "https://a.basemaps.cartocdn.com/dark_nolabels/3/4/2@2x.png",
dark: true,
},
{
id: "dark-terrain",
name: "Dark Terrain",
style:
"https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json",
preview: "linear-gradient(135deg, #111416 0%, #1d2427 50%, #101315 100%)",
previewUrl: "https://a.basemaps.cartocdn.com/dark_nolabels/3/4/2@2x.png",
dark: true,
terrainProfile: "dark",
},
{
id: "dark-labels",
name: "Annotated",
@ -134,14 +153,6 @@ export const MAP_STYLES: MapStyle[] = [
"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/3/2/4",
dark: true,
},
{
id: "terrain",
name: "Terrain",
style: TERRAIN_STYLE,
preview: "linear-gradient(135deg, #c8d8c0 0%, #a8c098 50%, #d0d8c0 100%)",
previewUrl: "https://tile.opentopomap.org/3/4/2.png",
dark: false,
},
{
id: "topo",
name: "Topo",
@ -151,24 +162,6 @@ export const MAP_STYLES: MapStyle[] = [
"https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/3/2/4",
dark: false,
},
{
id: "relief",
name: "3D Terrain",
style: SHADED_RELIEF_STYLE,
preview: "linear-gradient(135deg, #1a3050 0%, #2a5040 50%, #1a3050 100%)",
previewUrl:
"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/3/2/4",
dark: true,
},
{
id: "positron",
name: "Light",
style:
"https://basemaps.cartocdn.com/gl/positron-nolabels-gl-style/style.json",
preview: "linear-gradient(135deg, #e8e8e8 0%, #fafafa 50%, #e8e8e8 100%)",
previewUrl: "https://a.basemaps.cartocdn.com/light_nolabels/3/4/2@2x.png",
dark: false,
},
];
export const DEFAULT_STYLE = MAP_STYLES[0];
@ -185,8 +178,8 @@ export function getAttributions(styleId: string): AttributionEntry[] {
switch (styleId) {
case "dark":
case "dark-labels":
case "dark-terrain":
case "voyager":
case "positron":
base.push(
{
label: "OpenStreetMap",
@ -194,19 +187,16 @@ export function getAttributions(styleId: string): AttributionEntry[] {
},
{ label: "CARTO", url: "https://carto.com/attributions" },
);
if (styleId === "dark-terrain") {
base.push({
label: "MapLibre Terrain",
url: "https://demotiles.maplibre.org/",
});
}
break;
case "satellite":
base.push({ label: "Esri", url: "https://www.esri.com/" });
break;
case "terrain":
base.push(
{
label: "OpenStreetMap",
url: "https://www.openstreetmap.org/copyright",
},
{ label: "OpenTopoMap", url: "https://opentopomap.org/" },
);
break;
case "topo":
base.push(
{
@ -216,12 +206,6 @@ export function getAttributions(styleId: string): AttributionEntry[] {
{ label: "Esri", url: "https://www.esri.com/" },
);
break;
case "relief":
base.push(
{ label: "Esri", url: "https://www.esri.com/" },
{ label: "Mapzen", url: "https://github.com/tilezen/joerd" },
);
break;
default:
base.push({
label: "OpenStreetMap",

389
src/lib/opensky-flights.ts Normal file
View File

@ -0,0 +1,389 @@
import type {
CallsignLookupResult,
FetchResult,
FlightState,
OpenSkyResponse,
} from "./opensky-types";
import {
CALLSIGN_CACHE_MAX_ENTRIES,
CALLSIGN_CACHE_TTL_MS,
FETCH_TIMEOUT_MS,
ICAO24_REGEX,
MAX_1_CREDIT_RADIUS_DEG,
OPENSKY_API,
SEGMENT_DELAY_MS,
} from "./opensky-types";
import {
normalizeCallsign,
normalizeBounds,
parseRateLimitInfo,
parseStates,
} from "./opensky-parsing";
// ── Bounding Box Flights ───────────────────────────────────────────────
export async function fetchFlightsByBbox(
lamin: number,
lamax: number,
lomin: number,
lomax: number,
signal?: AbortSignal,
): Promise<FetchResult> {
const [la0, la1] = normalizeBounds(lamin, lamax, -90, 90);
const [lo0, lo1] = normalizeBounds(lomin, lomax, -180, 180);
const url = `${OPENSKY_API}/states/all?lamin=${la0}&lamax=${la1}&lomin=${lo0}&lomax=${lo1}&extended=1`;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
const onExternalAbort = () => controller.abort();
signal?.addEventListener("abort", onExternalAbort);
try {
const res = await fetch(url, {
cache: "no-store",
signal: controller.signal,
});
const rateLimitInfo = parseRateLimitInfo(res);
if (res.status === 429) {
return {
flights: [],
rateLimited: true,
creditsRemaining: rateLimitInfo.creditsRemaining,
retryAfterSeconds: rateLimitInfo.retryAfterSeconds,
};
}
if (!res.ok) {
return {
flights: [],
rateLimited: false,
creditsRemaining: rateLimitInfo.creditsRemaining,
retryAfterSeconds: null,
};
}
const payload = (await res.json()) as unknown;
const data =
typeof payload === "object" && payload !== null
? (payload as OpenSkyResponse)
: { time: 0, states: null };
return {
flights: parseStates(data),
rateLimited: false,
creditsRemaining: rateLimitInfo.creditsRemaining,
retryAfterSeconds: null,
};
} catch (err) {
if (err instanceof Error && err.name === "AbortError") {
if (signal?.aborted) throw err;
throw new Error("OpenSky request timed out");
}
throw err;
} finally {
clearTimeout(timer);
signal?.removeEventListener("abort", onExternalAbort);
}
}
// ── Bbox Helper ────────────────────────────────────────────────────────
export function bboxFromCenter(
lng: number,
lat: number,
radiusDeg: number,
): [lamin: number, lamax: number, lomin: number, lomax: number] {
// If callers pass a bogus radius, fall back to a safe 1-credit value.
const safeRadiusRaw =
Number.isFinite(radiusDeg) && radiusDeg > 0
? radiusDeg
: MAX_1_CREDIT_RADIUS_DEG;
const safeRadius = Math.min(safeRadiusRaw, MAX_1_CREDIT_RADIUS_DEG);
// Compensate longitude extent for converging meridians at higher latitudes.
// At the equator cos(0)=1 so lngRadius equals safeRadius (no change).
// At 60°N cos(60°)=0.5 so lngRadius doubles to cover the same ground distance.
// Clamp near poles to avoid division by near-zero.
const cosLat = Math.cos((Math.abs(lat) * Math.PI) / 180);
const lngRadius = Math.min(180, safeRadius / Math.max(cosLat, 0.01));
return [lat - safeRadius, lat + safeRadius, lng - lngRadius, lng + lngRadius];
}
// ── Single Aircraft by ICAO24 ──────────────────────────────────────────
/**
* Fetch a single aircraft's state by its ICAO24 address (global lookup).
* Costs 4 API credits (no bbox = full globe) but returns at most one result.
* Returns the flight if found, or null.
*/
export async function fetchFlightByIcao24(
icao24: string,
signal?: AbortSignal,
): Promise<{ flight: FlightState | null; creditsRemaining: number | null }> {
const normalizedIcao24 = icao24.trim().toLowerCase();
if (!ICAO24_REGEX.test(normalizedIcao24)) {
return { flight: null, creditsRemaining: null };
}
const url = `${OPENSKY_API}/states/all?icao24=${encodeURIComponent(normalizedIcao24)}&extended=1`;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
const onExternalAbort = () => controller.abort();
signal?.addEventListener("abort", onExternalAbort);
try {
const res = await fetch(url, {
cache: "no-store",
signal: controller.signal,
});
const rateLimitInfo = parseRateLimitInfo(res);
if (res.status === 429 || !res.ok) {
return { flight: null, creditsRemaining: rateLimitInfo.creditsRemaining };
}
const payload = (await res.json()) as unknown;
const data =
typeof payload === "object" && payload !== null
? (payload as OpenSkyResponse)
: { time: 0, states: null };
const flights = parseStates(data, {
includeGround: true,
requireBaroAltitude: false,
});
return {
flight: flights.find((f) => f.icao24 === normalizedIcao24) ?? null,
creditsRemaining: rateLimitInfo.creditsRemaining,
};
} catch (err) {
if (err instanceof Error && err.name === "AbortError") {
if (signal?.aborted) throw err;
}
return { flight: null, creditsRemaining: null };
} finally {
clearTimeout(timer);
signal?.removeEventListener("abort", onExternalAbort);
}
}
// ── Callsign Search ────────────────────────────────────────────────────
const callsignLookupCache = new Map<
string,
{ timestamp: number; result: CallsignLookupResult }
>();
// In-flight promise dedup: prevents concurrent 4-credit global fetches
// for the same normalized callsign query.
const callsignInFlight = new Map<string, Promise<CallsignLookupResult>>();
export async function fetchFlightByCallsign(
callsign: string,
signal?: AbortSignal,
): Promise<CallsignLookupResult> {
const normalizedQuery = normalizeCallsign(callsign);
if (!normalizedQuery) {
return {
flight: null,
creditsRemaining: null,
rateLimited: false,
retryAfterSeconds: null,
};
}
const cached = callsignLookupCache.get(normalizedQuery);
if (cached && Date.now() - cached.timestamp <= CALLSIGN_CACHE_TTL_MS) {
return cached.result;
}
// If there's already an in-flight request for this query, piggyback on it
const existing = callsignInFlight.get(normalizedQuery);
if (existing) return existing;
const promise = fetchFlightByCallsignImpl(normalizedQuery, signal);
callsignInFlight.set(normalizedQuery, promise);
try {
return await promise;
} finally {
callsignInFlight.delete(normalizedQuery);
}
}
async function fetchFlightByCallsignImpl(
normalizedQuery: string,
signal?: AbortSignal,
): Promise<CallsignLookupResult> {
const url = `${OPENSKY_API}/states/all?extended=1`;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
const onExternalAbort = () => controller.abort();
signal?.addEventListener("abort", onExternalAbort);
try {
const res = await fetch(url, {
cache: "no-store",
signal: controller.signal,
});
const rateLimitInfo = parseRateLimitInfo(res);
if (res.status === 429) {
return {
flight: null,
creditsRemaining: rateLimitInfo.creditsRemaining,
rateLimited: true,
retryAfterSeconds: rateLimitInfo.retryAfterSeconds,
};
}
if (!res.ok) {
return {
flight: null,
creditsRemaining: rateLimitInfo.creditsRemaining,
rateLimited: false,
retryAfterSeconds: null,
};
}
const payload = (await res.json()) as unknown;
const data =
typeof payload === "object" && payload !== null
? (payload as OpenSkyResponse)
: { time: 0, states: null };
const flights = parseStates(data, {
includeGround: true,
requireBaroAltitude: false,
});
const exact = flights.find(
(f) => normalizeCallsign(f.callsign) === normalizedQuery,
);
const startsWith =
exact ??
flights.find((f) =>
normalizeCallsign(f.callsign).startsWith(normalizedQuery),
);
const contains =
startsWith ??
flights.find((f) =>
normalizeCallsign(f.callsign).includes(normalizedQuery),
);
const result: CallsignLookupResult = {
flight: contains ?? null,
creditsRemaining: rateLimitInfo.creditsRemaining,
rateLimited: false,
retryAfterSeconds: null,
};
callsignLookupCache.set(normalizedQuery, {
timestamp: Date.now(),
result,
});
if (callsignLookupCache.size > CALLSIGN_CACHE_MAX_ENTRIES) {
const oldestKey = callsignLookupCache.keys().next().value as
| string
| undefined;
if (oldestKey) callsignLookupCache.delete(oldestKey);
}
return result;
} catch (err) {
if (err instanceof Error && err.name === "AbortError") {
if (signal?.aborted) throw err;
}
return {
flight: null,
creditsRemaining: null,
rateLimited: false,
retryAfterSeconds: null,
};
} finally {
clearTimeout(timer);
signal?.removeEventListener("abort", onExternalAbort);
}
}
// ── Route Corridor Fetch ───────────────────────────────────────────────
/**
* Fetch flights across multiple bounding-box segments (for route corridors).
* Segments are fetched sequentially with a small delay to avoid burst rate limits.
* Results are merged and deduplicated by icao24.
*
* If a 429 is received mid-sequence, partial results collected so far are returned
* with `rateLimited: true`.
*/
export async function fetchFlightsByRoute(
segments: { lamin: number; lamax: number; lomin: number; lomax: number }[],
signal?: AbortSignal,
): Promise<FetchResult> {
if (segments.length === 0) {
return {
flights: [],
rateLimited: false,
creditsRemaining: null,
retryAfterSeconds: null,
};
}
const seen = new Map<string, FlightState>();
let rateLimited = false;
let lowestCredits: number | null = null;
let retryAfterSeconds: number | null = null;
for (let i = 0; i < segments.length; i++) {
if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
const seg = segments[i];
const result = await fetchFlightsByBbox(
seg.lamin,
seg.lamax,
seg.lomin,
seg.lomax,
signal,
);
for (const f of result.flights) {
if (!seen.has(f.icao24)) {
seen.set(f.icao24, f);
}
}
if (result.creditsRemaining !== null) {
lowestCredits =
lowestCredits === null
? result.creditsRemaining
: Math.min(lowestCredits, result.creditsRemaining);
}
if (result.rateLimited) {
rateLimited = true;
retryAfterSeconds = result.retryAfterSeconds;
break;
}
if (i < segments.length - 1) {
await new Promise<void>((resolve) => {
const timer = setTimeout(resolve, SEGMENT_DELAY_MS);
const onAbort = () => {
clearTimeout(timer);
resolve();
};
signal?.addEventListener("abort", onAbort, { once: true });
});
}
}
return {
flights: Array.from(seen.values()),
rateLimited,
creditsRemaining: lowestCredits,
retryAfterSeconds,
};
}

109
src/lib/opensky-parsing.ts Normal file
View File

@ -0,0 +1,109 @@
import type {
FlightState,
OpenSkyResponse,
ParseStateOptions,
RateLimitInfo,
} from "./opensky-types";
import { ICAO24_REGEX, clamp } from "./opensky-types";
// ── Header Parsing ─────────────────────────────────────────────────────
export function parseIntegerHeader(value: string | null): number | null {
if (value === null) return null;
const parsed = Number.parseInt(value, 10);
return Number.isFinite(parsed) ? parsed : null;
}
export function parseRateLimitInfo(response: Response): RateLimitInfo {
return {
creditsRemaining: parseIntegerHeader(
response.headers.get("x-rate-limit-remaining"),
),
retryAfterSeconds: parseIntegerHeader(
response.headers.get("x-rate-limit-retry-after-seconds"),
),
};
}
// ── Value Helpers ──────────────────────────────────────────────────────
export function isFiniteNumber(value: unknown): value is number {
return typeof value === "number" && Number.isFinite(value);
}
export function normalizeBounds(
lower: number,
upper: number,
min: number,
max: number,
): [number, number] {
if (!Number.isFinite(lower) || !Number.isFinite(upper)) {
throw new Error("Invalid bounding box coordinates");
}
const lo = clamp(lower, min, max);
const hi = clamp(upper, min, max);
return lo <= hi ? [lo, hi] : [hi, lo];
}
// ── State Row Parsing ──────────────────────────────────────────────────
export function parseStateRow(
rawState: (string | number | boolean | null)[],
): FlightState | null {
if (rawState.length < 17) return null;
const icao24 =
typeof rawState[0] === "string" ? rawState[0].toLowerCase() : "";
if (!ICAO24_REGEX.test(icao24)) return null;
const longitude = isFiniteNumber(rawState[5]) ? rawState[5] : null;
const latitude = isFiniteNumber(rawState[6]) ? rawState[6] : null;
const baroAltitude = isFiniteNumber(rawState[7]) ? rawState[7] : null;
return {
icao24,
callsign:
typeof rawState[1] === "string" ? rawState[1].trim() || null : null,
originCountry: typeof rawState[2] === "string" ? rawState[2] : "Unknown",
longitude,
latitude,
baroAltitude,
onGround: rawState[8] === true,
velocity: isFiniteNumber(rawState[9]) ? rawState[9] : null,
trueTrack: isFiniteNumber(rawState[10]) ? rawState[10] : null,
verticalRate: isFiniteNumber(rawState[11]) ? rawState[11] : null,
geoAltitude: isFiniteNumber(rawState[13]) ? rawState[13] : null,
squawk: typeof rawState[14] === "string" ? rawState[14] : null,
spiFlag: rawState[15] === true,
positionSource: isFiniteNumber(rawState[16]) ? rawState[16] : 0,
category: isFiniteNumber(rawState[17]) ? rawState[17] : null,
};
}
export function parseStates(
raw: OpenSkyResponse,
options?: ParseStateOptions,
): FlightState[] {
if (!raw || !Array.isArray(raw.states)) return [];
const includeGround = options?.includeGround ?? false;
const requireBaroAltitude = options?.requireBaroAltitude ?? true;
return raw.states
.map(parseStateRow)
.filter((state): state is FlightState => state !== null)
.filter(
(f) =>
f.longitude !== null &&
f.latitude !== null &&
(includeGround || !f.onGround) &&
(!requireBaroAltitude || f.baroAltitude !== null),
);
}
// ── Callsign Normalization ─────────────────────────────────────────────
export function normalizeCallsign(value: string | null): string {
if (!value) return "";
return value.trim().toUpperCase().replace(/\s+/g, "");
}

242
src/lib/opensky-tracks.ts Normal file
View File

@ -0,0 +1,242 @@
import type {
FlightTrack,
OpenSkyTrackResponse,
TrackFetchResult,
TrackWaypoint,
} from "./opensky-types";
import { FETCH_TIMEOUT_MS, ICAO24_REGEX, OPENSKY_API } from "./opensky-types";
import { parseRateLimitInfo } from "./opensky-parsing";
// ── Track Waypoint Parsing ─────────────────────────────────────────────
function parseTrackWaypoint(raw: unknown): TrackWaypoint | null {
if (!Array.isArray(raw) || raw.length < 6) return null;
const time =
typeof raw[0] === "number" && Number.isFinite(raw[0]) ? raw[0] : null;
const latitude =
typeof raw[1] === "number" && Number.isFinite(raw[1]) ? raw[1] : null;
const longitude =
typeof raw[2] === "number" && Number.isFinite(raw[2]) ? raw[2] : null;
const baroAltitude =
typeof raw[3] === "number" && Number.isFinite(raw[3]) ? raw[3] : null;
const trueTrack =
typeof raw[4] === "number" && Number.isFinite(raw[4]) ? raw[4] : null;
const onGround = raw[5] === true;
if (time === null) return null;
return { time, latitude, longitude, baroAltitude, trueTrack, onGround };
}
// ── Flight Track Parsing ───────────────────────────────────────────────
function parseFlightTrack(
icao24: string,
payload: unknown,
): FlightTrack | null {
if (typeof payload !== "object" || payload === null) return null;
const data = payload as OpenSkyTrackResponse;
const startTime =
typeof data.startTime === "number" && Number.isFinite(data.startTime)
? data.startTime
: 0;
const endTime =
typeof data.endTime === "number" && Number.isFinite(data.endTime)
? data.endTime
: 0;
const callsignRaw =
typeof data.callsign === "string"
? data.callsign
: typeof data.calllsign === "string"
? data.calllsign
: null;
const callsign = callsignRaw ? callsignRaw.trim() || null : null;
const rawPath = Array.isArray(data.path) ? data.path : [];
const parsed = rawPath
.map(parseTrackWaypoint)
.filter((p): p is TrackWaypoint => p !== null)
.filter((p) => p.latitude !== null && p.longitude !== null);
// Be defensive: some responses can be out-of-order.
parsed.sort((a, b) => a.time - b.time);
// Remove consecutive duplicates (helps avoid long straight chords when data is jittery).
const path: TrackWaypoint[] = [];
let lastLng: number | null = null;
let lastLat: number | null = null;
for (const p of parsed) {
if (lastLng !== null && lastLat !== null) {
if (p.longitude === lastLng && p.latitude === lastLat) continue;
}
path.push(p);
lastLng = p.longitude;
lastLat = p.latitude;
}
if (path.length < 2) return null;
return {
icao24,
startTime,
endTime,
callsign,
path,
};
}
// ── Fetch Track ────────────────────────────────────────────────────────
/**
* Fetch a flight track (trajectory) for an aircraft.
*
* Uses the experimental OpenSky tracks endpoint. For live flights, pass time=0
* which returns the current (ongoing) track if available.
*/
export async function fetchTrackByIcao24(
icao24: string,
time: number = 0,
signal?: AbortSignal,
): Promise<TrackFetchResult> {
const normalizedIcao24 = icao24.trim().toLowerCase();
if (!ICAO24_REGEX.test(normalizedIcao24)) {
return {
track: null,
rateLimited: false,
creditsRemaining: null,
retryAfterSeconds: null,
};
}
const safeTime = Number.isFinite(time) ? Math.max(0, Math.floor(time)) : 0;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
const onExternalAbort = () => {
if (!controller.signal.aborted) controller.abort();
};
signal?.addEventListener("abort", onExternalAbort, { once: true });
if (signal?.aborted) {
onExternalAbort();
}
try {
async function fetchWithTime(
t: number,
): Promise<{ result: TrackFetchResult; notFound: boolean }> {
const urlAll = `${OPENSKY_API}/tracks/all?icao24=${encodeURIComponent(normalizedIcao24)}&time=${t}`;
const urlFallback = `${OPENSKY_API}/tracks?icao24=${encodeURIComponent(normalizedIcao24)}&time=${t}`;
async function attempt(
url: string,
): Promise<{ result: TrackFetchResult; status: number }> {
const res = await fetch(url, {
cache: "no-store",
signal: controller.signal,
});
const rateLimitInfo = parseRateLimitInfo(res);
if (res.status === 429) {
return {
status: res.status,
result: {
track: null,
rateLimited: true,
creditsRemaining: rateLimitInfo.creditsRemaining,
retryAfterSeconds: rateLimitInfo.retryAfterSeconds,
},
};
}
if (res.status === 404 || res.status === 401 || res.status === 403) {
return {
status: res.status,
result: {
track: null,
rateLimited: false,
creditsRemaining: rateLimitInfo.creditsRemaining,
retryAfterSeconds: null,
},
};
}
if (!res.ok) {
return {
status: res.status,
result: {
track: null,
rateLimited: false,
creditsRemaining: rateLimitInfo.creditsRemaining,
retryAfterSeconds: null,
},
};
}
const payload = (await res.json()) as unknown;
return {
status: res.status,
result: {
track: parseFlightTrack(normalizedIcao24, payload),
rateLimited: false,
creditsRemaining: rateLimitInfo.creditsRemaining,
retryAfterSeconds: null,
},
};
}
const primary = await attempt(urlAll);
if (primary.result.track || primary.result.rateLimited) {
return { result: primary.result, notFound: false };
}
// Some OpenSky deployments/documentation use `/tracks` instead of `/tracks/all`.
// Fall back only when the primary endpoint is missing (404), not on auth failures.
if (primary.status === 404) {
const fallback = await attempt(urlFallback);
// Only treat as "not found" if both endpoints return 404.
const notFound = fallback.status === 404;
return { result: fallback.result, notFound };
}
return { result: primary.result, notFound: false };
}
const primary = await fetchWithTime(safeTime);
if (primary.result.track || primary.result.rateLimited || safeTime !== 0) {
return primary.result;
}
// Per OpenSky docs: `time` can be any time between the start and end of a known flight.
// `time=0` only returns a live track if OpenSky considers a flight ongoing. If that lookup
// fails with a not-found response, retry once with the current timestamp.
if (!primary.notFound) {
return primary.result;
}
const nowSec = Math.floor(Date.now() / 1000);
if (nowSec > 0) {
const retry = await fetchWithTime(nowSec);
return retry.result;
}
return primary.result;
} catch (err) {
if (err instanceof Error && err.name === "AbortError") {
// Abort is expected on effect cleanup or request timeouts. Treat it as a
// normal cancellation and return an empty result.
}
return {
track: null,
rateLimited: false,
creditsRemaining: null,
retryAfterSeconds: null,
};
} finally {
clearTimeout(timer);
signal?.removeEventListener("abort", onExternalAbort);
}
}

104
src/lib/opensky-types.ts Normal file
View File

@ -0,0 +1,104 @@
/** @see https://openskynetwork.github.io/opensky-api/rest.html */
// ── API Constants ──────────────────────────────────────────────────────
export const OPENSKY_API = "https://opensky-network.org/api";
export const FETCH_TIMEOUT_MS = 15_000;
export const ICAO24_REGEX = /^[0-9a-f]{6}$/i;
/** Callsign lookup scans global /states/all (4 credits); cache longer to reduce spikes. */
export const CALLSIGN_CACHE_TTL_MS = 2 * 60_000;
export const CALLSIGN_CACHE_MAX_ENTRIES = 200;
/** Keep bbox queries inside OpenSky's 025 sq-deg (1 credit) tier. */
export const MAX_1_CREDIT_RADIUS_DEG = 2.49;
/** Delay between sequential segment fetches to avoid burst rate limits. */
export const SEGMENT_DELAY_MS = 200;
// ── Exported Types ─────────────────────────────────────────────────────
export type FlightState = {
icao24: string;
callsign: string | null;
originCountry: string;
longitude: number | null;
latitude: number | null;
baroAltitude: number | null;
onGround: boolean;
velocity: number | null;
trueTrack: number | null;
verticalRate: number | null;
geoAltitude: number | null;
squawk: string | null;
spiFlag: boolean;
positionSource: number;
category: number | null;
};
export type FetchResult = {
flights: FlightState[];
rateLimited: boolean;
creditsRemaining: number | null;
retryAfterSeconds: number | null;
};
export type TrackWaypoint = {
time: number;
latitude: number | null;
longitude: number | null;
baroAltitude: number | null;
trueTrack: number | null;
onGround: boolean;
};
export type FlightTrack = {
icao24: string;
startTime: number;
endTime: number;
callsign: string | null;
path: TrackWaypoint[];
};
export type TrackFetchResult = {
track: FlightTrack | null;
rateLimited: boolean;
creditsRemaining: number | null;
retryAfterSeconds: number | null;
};
// ── Internal Types (used across sub-modules) ───────────────────────────
export type OpenSkyResponse = {
time: number;
states: (string | number | boolean | null)[][] | null;
};
export type ParseStateOptions = {
includeGround?: boolean;
requireBaroAltitude?: boolean;
};
export type RateLimitInfo = {
creditsRemaining: number | null;
retryAfterSeconds: number | null;
};
export type CallsignLookupResult = {
flight: FlightState | null;
creditsRemaining: number | null;
rateLimited: boolean;
retryAfterSeconds: number | null;
};
export type OpenSkyTrackResponse = {
icao24?: unknown;
startTime?: unknown;
endTime?: unknown;
callsign?: unknown;
// Defensive: accept a misspelled field name if present.
calllsign?: unknown;
path?: unknown;
};
// ── Shared Utilities ───────────────────────────────────────────────────
export const clamp = (value: number, min: number, max: number) =>
Math.min(Math.max(value, min), max);

View File

@ -1,732 +1,29 @@
/** @see https://openskynetwork.github.io/opensky-api/rest.html */
const OPENSKY_API = "https://opensky-network.org/api";
const FETCH_TIMEOUT_MS = 15_000;
const ICAO24_REGEX = /^[0-9a-f]{6}$/i;
// Callsign lookup scans global /states/all (4 credits); cache longer to reduce spikes.
const CALLSIGN_CACHE_TTL_MS = 2 * 60_000;
const CALLSIGN_CACHE_MAX_ENTRIES = 200;
// Keep bbox queries inside OpenSky's 025 sq-deg (1 credit) tier.
const MAX_1_CREDIT_RADIUS_DEG = 2.49;
export type FlightState = {
icao24: string;
callsign: string | null;
originCountry: string;
longitude: number | null;
latitude: number | null;
baroAltitude: number | null;
onGround: boolean;
velocity: number | null;
trueTrack: number | null;
verticalRate: number | null;
geoAltitude: number | null;
squawk: string | null;
spiFlag: boolean;
positionSource: number;
category: number | null;
};
type OpenSkyResponse = {
time: number;
states: (string | number | boolean | null)[][] | null;
};
type ParseStateOptions = {
includeGround?: boolean;
requireBaroAltitude?: boolean;
};
type RateLimitInfo = {
creditsRemaining: number | null;
retryAfterSeconds: number | null;
};
const clamp = (value: number, min: number, max: number) =>
Math.min(Math.max(value, min), max);
function parseIntegerHeader(value: string | null): number | null {
if (value === null) return null;
const parsed = Number.parseInt(value, 10);
return Number.isFinite(parsed) ? parsed : null;
}
function parseRateLimitInfo(response: Response): RateLimitInfo {
return {
creditsRemaining: parseIntegerHeader(
response.headers.get("x-rate-limit-remaining"),
),
retryAfterSeconds: parseIntegerHeader(
response.headers.get("x-rate-limit-retry-after-seconds"),
),
};
}
function isFiniteNumber(value: unknown): value is number {
return typeof value === "number" && Number.isFinite(value);
}
function normalizeBounds(
lower: number,
upper: number,
min: number,
max: number,
): [number, number] {
if (!Number.isFinite(lower) || !Number.isFinite(upper)) {
throw new Error("Invalid bounding box coordinates");
}
const lo = clamp(lower, min, max);
const hi = clamp(upper, min, max);
return lo <= hi ? [lo, hi] : [hi, lo];
}
function parseStateRow(rawState: (string | number | boolean | null)[]): FlightState | null {
if (rawState.length < 17) return null;
const icao24 = typeof rawState[0] === "string" ? rawState[0].toLowerCase() : "";
if (!ICAO24_REGEX.test(icao24)) return null;
const longitude = isFiniteNumber(rawState[5]) ? rawState[5] : null;
const latitude = isFiniteNumber(rawState[6]) ? rawState[6] : null;
const baroAltitude = isFiniteNumber(rawState[7]) ? rawState[7] : null;
return {
icao24,
callsign: typeof rawState[1] === "string" ? rawState[1].trim() || null : null,
originCountry:
typeof rawState[2] === "string" ? rawState[2] : "Unknown",
longitude,
latitude,
baroAltitude,
onGround: rawState[8] === true,
velocity: isFiniteNumber(rawState[9]) ? rawState[9] : null,
trueTrack: isFiniteNumber(rawState[10]) ? rawState[10] : null,
verticalRate: isFiniteNumber(rawState[11]) ? rawState[11] : null,
geoAltitude: isFiniteNumber(rawState[13]) ? rawState[13] : null,
squawk: typeof rawState[14] === "string" ? rawState[14] : null,
spiFlag: rawState[15] === true,
positionSource: isFiniteNumber(rawState[16]) ? rawState[16] : 0,
category: isFiniteNumber(rawState[17]) ? rawState[17] : null,
};
}
function parseStates(raw: OpenSkyResponse, options?: ParseStateOptions): FlightState[] {
if (!raw || !Array.isArray(raw.states)) return [];
const includeGround = options?.includeGround ?? false;
const requireBaroAltitude = options?.requireBaroAltitude ?? true;
return raw.states
.map(parseStateRow)
.filter((state): state is FlightState => state !== null)
.filter(
(f) =>
f.longitude !== null &&
f.latitude !== null &&
(includeGround || !f.onGround) &&
(!requireBaroAltitude || f.baroAltitude !== null),
);
}
function normalizeCallsign(value: string | null): string {
if (!value) return "";
return value.trim().toUpperCase().replace(/\s+/g, "");
}
export type FetchResult = {
flights: FlightState[];
rateLimited: boolean;
creditsRemaining: number | null;
retryAfterSeconds: number | null;
};
export async function fetchFlightsByBbox(
lamin: number,
lamax: number,
lomin: number,
lomax: number,
signal?: AbortSignal,
): Promise<FetchResult> {
const [la0, la1] = normalizeBounds(lamin, lamax, -90, 90);
const [lo0, lo1] = normalizeBounds(lomin, lomax, -180, 180);
const url = `${OPENSKY_API}/states/all?lamin=${la0}&lamax=${la1}&lomin=${lo0}&lomax=${lo1}&extended=1`;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
const onExternalAbort = () => controller.abort();
signal?.addEventListener("abort", onExternalAbort);
try {
const res = await fetch(url, {
cache: "no-store",
signal: controller.signal,
});
const rateLimitInfo = parseRateLimitInfo(res);
if (res.status === 429) {
return {
flights: [],
rateLimited: true,
creditsRemaining: rateLimitInfo.creditsRemaining,
retryAfterSeconds: rateLimitInfo.retryAfterSeconds,
};
}
if (!res.ok) {
return {
flights: [],
rateLimited: false,
creditsRemaining: rateLimitInfo.creditsRemaining,
retryAfterSeconds: null,
};
}
const payload = (await res.json()) as unknown;
const data =
typeof payload === "object" && payload !== null
? (payload as OpenSkyResponse)
: { time: 0, states: null };
return {
flights: parseStates(data),
rateLimited: false,
creditsRemaining: rateLimitInfo.creditsRemaining,
retryAfterSeconds: null,
};
} catch (err) {
if (err instanceof Error && err.name === "AbortError") {
if (signal?.aborted) throw err;
throw new Error("OpenSky request timed out");
}
throw err;
} finally {
clearTimeout(timer);
signal?.removeEventListener("abort", onExternalAbort);
}
}
export function bboxFromCenter(
lng: number,
lat: number,
radiusDeg: number,
): [lamin: number, lamax: number, lomin: number, lomax: number] {
// If callers pass a bogus radius, fall back to a safe 1-credit value.
const safeRadiusRaw =
Number.isFinite(radiusDeg) && radiusDeg > 0 ? radiusDeg : MAX_1_CREDIT_RADIUS_DEG;
const safeRadius = Math.min(safeRadiusRaw, MAX_1_CREDIT_RADIUS_DEG);
return [
lat - safeRadius,
lat + safeRadius,
lng - safeRadius,
lng + safeRadius,
];
}
/**
* Fetch a single aircraft's state by its ICAO24 address (global lookup).
* Costs 4 API credits (no bbox = full globe) but returns at most one result.
* Returns the flight if found, or null.
*/
export async function fetchFlightByIcao24(
icao24: string,
signal?: AbortSignal,
): Promise<{ flight: FlightState | null; creditsRemaining: number | null }> {
const normalizedIcao24 = icao24.trim().toLowerCase();
if (!ICAO24_REGEX.test(normalizedIcao24)) {
return { flight: null, creditsRemaining: null };
}
const url = `${OPENSKY_API}/states/all?icao24=${encodeURIComponent(normalizedIcao24)}&extended=1`;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
const onExternalAbort = () => controller.abort();
signal?.addEventListener("abort", onExternalAbort);
try {
const res = await fetch(url, {
cache: "no-store",
signal: controller.signal,
});
const rateLimitInfo = parseRateLimitInfo(res);
if (res.status === 429 || !res.ok) {
return { flight: null, creditsRemaining: rateLimitInfo.creditsRemaining };
}
const payload = (await res.json()) as unknown;
const data =
typeof payload === "object" && payload !== null
? (payload as OpenSkyResponse)
: { time: 0, states: null };
const flights = parseStates(data, {
includeGround: true,
requireBaroAltitude: false,
});
return {
flight:
flights.find((f) => f.icao24 === normalizedIcao24) ?? null,
creditsRemaining: rateLimitInfo.creditsRemaining,
};
} catch (err) {
if (err instanceof Error && err.name === "AbortError") {
if (signal?.aborted) throw err;
}
return { flight: null, creditsRemaining: null };
} finally {
clearTimeout(timer);
signal?.removeEventListener("abort", onExternalAbort);
}
}
type CallsignLookupResult = {
flight: FlightState | null;
creditsRemaining: number | null;
rateLimited: boolean;
retryAfterSeconds: number | null;
};
const callsignLookupCache = new Map<
string,
{ timestamp: number; result: CallsignLookupResult }
>();
export async function fetchFlightByCallsign(
callsign: string,
signal?: AbortSignal,
): Promise<CallsignLookupResult> {
const normalizedQuery = normalizeCallsign(callsign);
if (!normalizedQuery) {
return {
flight: null,
creditsRemaining: null,
rateLimited: false,
retryAfterSeconds: null,
};
}
const cached = callsignLookupCache.get(normalizedQuery);
if (cached && Date.now() - cached.timestamp <= CALLSIGN_CACHE_TTL_MS) {
return cached.result;
}
const url = `${OPENSKY_API}/states/all?extended=1`;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
const onExternalAbort = () => controller.abort();
signal?.addEventListener("abort", onExternalAbort);
try {
const res = await fetch(url, {
cache: "no-store",
signal: controller.signal,
});
const rateLimitInfo = parseRateLimitInfo(res);
if (res.status === 429) {
return {
flight: null,
creditsRemaining: rateLimitInfo.creditsRemaining,
rateLimited: true,
retryAfterSeconds: rateLimitInfo.retryAfterSeconds,
};
}
if (!res.ok) {
return {
flight: null,
creditsRemaining: rateLimitInfo.creditsRemaining,
rateLimited: false,
retryAfterSeconds: null,
};
}
const payload = (await res.json()) as unknown;
const data =
typeof payload === "object" && payload !== null
? (payload as OpenSkyResponse)
: { time: 0, states: null };
const flights = parseStates(data, {
includeGround: true,
requireBaroAltitude: false,
});
const exact = flights.find(
(f) => normalizeCallsign(f.callsign) === normalizedQuery,
);
const startsWith =
exact ??
flights.find((f) => normalizeCallsign(f.callsign).startsWith(normalizedQuery));
const contains =
startsWith ??
flights.find((f) => normalizeCallsign(f.callsign).includes(normalizedQuery));
const result: CallsignLookupResult = {
flight: contains ?? null,
creditsRemaining: rateLimitInfo.creditsRemaining,
rateLimited: false,
retryAfterSeconds: null,
};
callsignLookupCache.set(normalizedQuery, {
timestamp: Date.now(),
result,
});
if (callsignLookupCache.size > CALLSIGN_CACHE_MAX_ENTRIES) {
const oldestKey = callsignLookupCache.keys().next().value as string | undefined;
if (oldestKey) callsignLookupCache.delete(oldestKey);
}
return result;
} catch (err) {
if (err instanceof Error && err.name === "AbortError") {
if (signal?.aborted) throw err;
}
return {
flight: null,
creditsRemaining: null,
rateLimited: false,
retryAfterSeconds: null,
};
} finally {
clearTimeout(timer);
signal?.removeEventListener("abort", onExternalAbort);
}
}
const SEGMENT_DELAY_MS = 200;
/**
* Fetch flights across multiple bounding-box segments (for route corridors).
* Segments are fetched sequentially with a small delay to avoid burst rate limits.
* Results are merged and deduplicated by icao24.
* OpenSky Network API client — barrel re-export.
*
* If a 429 is received mid-sequence, partial results collected so far are returned
* with `rateLimited: true`.
*/
export async function fetchFlightsByRoute(
segments: { lamin: number; lamax: number; lomin: number; lomax: number }[],
signal?: AbortSignal,
): Promise<FetchResult> {
if (segments.length === 0) {
return {
flights: [],
rateLimited: false,
creditsRemaining: null,
retryAfterSeconds: null,
};
}
const seen = new Map<string, FlightState>();
let rateLimited = false;
let lowestCredits: number | null = null;
let retryAfterSeconds: number | null = null;
for (let i = 0; i < segments.length; i++) {
if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
const seg = segments[i];
const result = await fetchFlightsByBbox(
seg.lamin,
seg.lamax,
seg.lomin,
seg.lomax,
signal,
);
for (const f of result.flights) {
if (!seen.has(f.icao24)) {
seen.set(f.icao24, f);
}
}
if (result.creditsRemaining !== null) {
lowestCredits =
lowestCredits === null
? result.creditsRemaining
: Math.min(lowestCredits, result.creditsRemaining);
}
if (result.rateLimited) {
rateLimited = true;
retryAfterSeconds = result.retryAfterSeconds;
break;
}
if (i < segments.length - 1) {
await new Promise<void>((resolve) => {
const timer = setTimeout(resolve, SEGMENT_DELAY_MS);
const onAbort = () => {
clearTimeout(timer);
resolve();
};
signal?.addEventListener("abort", onAbort, { once: true });
});
}
}
return {
flights: Array.from(seen.values()),
rateLimited,
creditsRemaining: lowestCredits,
retryAfterSeconds,
};
}
export type TrackWaypoint = {
time: number;
latitude: number | null;
longitude: number | null;
baroAltitude: number | null;
trueTrack: number | null;
onGround: boolean;
};
export type FlightTrack = {
icao24: string;
startTime: number;
endTime: number;
callsign: string | null;
path: TrackWaypoint[];
};
export type TrackFetchResult = {
track: FlightTrack | null;
rateLimited: boolean;
creditsRemaining: number | null;
retryAfterSeconds: number | null;
};
type OpenSkyTrackResponse = {
icao24?: unknown;
startTime?: unknown;
endTime?: unknown;
callsign?: unknown;
// Defensive: accept a misspelled field name if present.
calllsign?: unknown;
path?: unknown;
};
function parseTrackWaypoint(raw: unknown): TrackWaypoint | null {
if (!Array.isArray(raw) || raw.length < 6) return null;
const time = typeof raw[0] === "number" && Number.isFinite(raw[0]) ? raw[0] : null;
const latitude = typeof raw[1] === "number" && Number.isFinite(raw[1]) ? raw[1] : null;
const longitude = typeof raw[2] === "number" && Number.isFinite(raw[2]) ? raw[2] : null;
const baroAltitude = typeof raw[3] === "number" && Number.isFinite(raw[3]) ? raw[3] : null;
const trueTrack = typeof raw[4] === "number" && Number.isFinite(raw[4]) ? raw[4] : null;
const onGround = raw[5] === true;
if (time === null) return null;
return { time, latitude, longitude, baroAltitude, trueTrack, onGround };
}
function parseFlightTrack(
icao24: string,
payload: unknown,
): FlightTrack | null {
if (typeof payload !== "object" || payload === null) return null;
const data = payload as OpenSkyTrackResponse;
const startTime =
typeof data.startTime === "number" && Number.isFinite(data.startTime)
? data.startTime
: 0;
const endTime =
typeof data.endTime === "number" && Number.isFinite(data.endTime)
? data.endTime
: 0;
const callsignRaw =
typeof data.callsign === "string"
? data.callsign
: typeof data.calllsign === "string"
? data.calllsign
: null;
const callsign = callsignRaw ? callsignRaw.trim() || null : null;
const rawPath = Array.isArray(data.path) ? data.path : [];
const parsed = rawPath
.map(parseTrackWaypoint)
.filter((p): p is TrackWaypoint => p !== null)
.filter((p) => p.latitude !== null && p.longitude !== null);
// Be defensive: some responses can be out-of-order.
parsed.sort((a, b) => a.time - b.time);
// Remove consecutive duplicates (helps avoid long straight chords when data is jittery).
const path: TrackWaypoint[] = [];
let lastLng: number | null = null;
let lastLat: number | null = null;
for (const p of parsed) {
if (lastLng !== null && lastLat !== null) {
if (p.longitude === lastLng && p.latitude === lastLat) continue;
}
path.push(p);
lastLng = p.longitude;
lastLat = p.latitude;
}
if (path.length < 2) return null;
return {
icao24,
startTime,
endTime,
callsign,
path,
};
}
/**
* Fetch a flight track (trajectory) for an aircraft.
* All implementation has been split into focused sub-modules.
* This file re-exports everything for backward compatibility.
*
* Uses the experimental OpenSky tracks endpoint. For live flights, pass time=0
* which returns the current (ongoing) track if available.
* @see https://openskynetwork.github.io/opensky-api/rest.html
*/
export async function fetchTrackByIcao24(
icao24: string,
time: number = 0,
signal?: AbortSignal,
): Promise<TrackFetchResult> {
const normalizedIcao24 = icao24.trim().toLowerCase();
if (!ICAO24_REGEX.test(normalizedIcao24)) {
return {
track: null,
rateLimited: false,
creditsRemaining: null,
retryAfterSeconds: null,
};
}
const safeTime = Number.isFinite(time) ? Math.max(0, Math.floor(time)) : 0;
// ── Types ──────────────────────────────────────────────────────────────
export type {
FlightState,
FetchResult,
TrackWaypoint,
FlightTrack,
TrackFetchResult,
} from "./opensky-types";
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
const onExternalAbort = () => {
if (!controller.signal.aborted) controller.abort();
};
signal?.addEventListener("abort", onExternalAbort, { once: true });
// ── Flight fetchers ────────────────────────────────────────────────────
export {
fetchFlightsByBbox,
bboxFromCenter,
fetchFlightByIcao24,
fetchFlightByCallsign,
fetchFlightsByRoute,
} from "./opensky-flights";
if (signal?.aborted) {
onExternalAbort();
}
try {
async function fetchWithTime(
t: number,
): Promise<{ result: TrackFetchResult; notFound: boolean }> {
const urlAll = `${OPENSKY_API}/tracks/all?icao24=${encodeURIComponent(normalizedIcao24)}&time=${t}`;
const urlFallback = `${OPENSKY_API}/tracks?icao24=${encodeURIComponent(normalizedIcao24)}&time=${t}`;
async function attempt(url: string): Promise<{ result: TrackFetchResult; status: number }> {
const res = await fetch(url, {
cache: "no-store",
signal: controller.signal,
});
const rateLimitInfo = parseRateLimitInfo(res);
if (res.status === 429) {
return {
status: res.status,
result: {
track: null,
rateLimited: true,
creditsRemaining: rateLimitInfo.creditsRemaining,
retryAfterSeconds: rateLimitInfo.retryAfterSeconds,
},
};
}
if (res.status === 404 || res.status === 401 || res.status === 403) {
return {
status: res.status,
result: {
track: null,
rateLimited: false,
creditsRemaining: rateLimitInfo.creditsRemaining,
retryAfterSeconds: null,
},
};
}
if (!res.ok) {
return {
status: res.status,
result: {
track: null,
rateLimited: false,
creditsRemaining: rateLimitInfo.creditsRemaining,
retryAfterSeconds: null,
},
};
}
const payload = (await res.json()) as unknown;
return {
status: res.status,
result: {
track: parseFlightTrack(normalizedIcao24, payload),
rateLimited: false,
creditsRemaining: rateLimitInfo.creditsRemaining,
retryAfterSeconds: null,
},
};
}
const primary = await attempt(urlAll);
if (primary.result.track || primary.result.rateLimited) {
return { result: primary.result, notFound: false };
}
// Some OpenSky deployments/documentation use `/tracks` instead of `/tracks/all`.
// Fall back only when the primary endpoint is missing (404), not on auth failures.
if (primary.status === 404) {
const fallback = await attempt(urlFallback);
// Only treat as “not found” if both endpoints return 404.
const notFound = fallback.status === 404;
return { result: fallback.result, notFound };
}
return { result: primary.result, notFound: false };
}
const primary = await fetchWithTime(safeTime);
if (primary.result.track || primary.result.rateLimited || safeTime !== 0) {
return primary.result;
}
// Per OpenSky docs: `time` can be any time between the start and end of a known flight.
// `time=0` only returns a live track if OpenSky considers a flight ongoing. If that lookup
// fails with a not-found response, retry once with the current timestamp.
if (!primary.notFound) {
return primary.result;
}
const nowSec = Math.floor(Date.now() / 1000);
if (nowSec > 0) {
const retry = await fetchWithTime(nowSec);
return retry.result;
}
return primary.result;
} catch (err) {
if (err instanceof Error && err.name === "AbortError") {
// Abort is expected on effect cleanup or request timeouts. Treat it as a
// normal cancellation and return an empty result.
}
return {
track: null,
rateLimited: false,
creditsRemaining: null,
retryAfterSeconds: null,
};
} finally {
clearTimeout(timer);
signal?.removeEventListener("abort", onExternalAbort);
}
}
// ── Track fetcher ──────────────────────────────────────────────────────
export { fetchTrackByIcao24 } from "./opensky-tracks";

126
src/lib/trail-altitude.ts Normal file
View File

@ -0,0 +1,126 @@
/**
* Altitude profile smoothing and ground-segment filtering.
*
* Used by trail-stitching to produce smooth altitude curves for
* historical flight tracks that have sparse waypoints.
*/
export type WaypointLike = {
onGround: boolean;
latitude: number | null;
longitude: number | null;
baroAltitude: number | null;
};
/**
* Smooth altitude values using box filtering and rate-of-change limiting.
*
* Historical trails have staircase-like altitude profiles from sparse
* waypoints. This applies:
* 1. A gentle 5-pass box filter to remove staircase artifacts.
* 2. A bi-directional rate-of-change limiter for realistic climb/descent.
*/
export function smoothAltitudeProfile(
altitudes: Array<number | null>,
defaultAlt: number,
): number[] {
const filled = fillNullAltitudes(altitudes, defaultAlt);
if (filled.length < 4) return filled;
// Pass 1: Gentle 5-pass box filter.
let current = filled;
for (let pass = 0; pass < 5; pass++) {
const next = [...current];
for (let i = 1; i < current.length - 1; i++) {
next[i] =
current[i - 1] * 0.25 + current[i] * 0.5 + current[i + 1] * 0.25;
}
current = next;
}
// Pass 2: Rate-of-change limiter for realistic climb/descent profiles.
const smoothed = [...current];
for (let pass = 0; pass < 3; pass++) {
for (let i = 1; i < smoothed.length; i++) {
const delta = smoothed[i] - smoothed[i - 1];
const absDelta = Math.abs(delta);
if (absDelta > 200) {
const softMax = 200 + (absDelta - 200) * 0.6;
smoothed[i] = smoothed[i - 1] + Math.sign(delta) * softMax;
}
}
// Reverse pass to avoid directional bias.
for (let i = smoothed.length - 2; i >= 0; i--) {
const delta = smoothed[i] - smoothed[i + 1];
const absDelta = Math.abs(delta);
if (absDelta > 200) {
const softMax = 200 + (absDelta - 200) * 0.6;
smoothed[i] = smoothed[i + 1] + Math.sign(delta) * softMax;
}
}
}
// Blend with original to preserve endpoint altitudes.
smoothed[0] = current[0];
smoothed[smoothed.length - 1] = current[current.length - 1];
return smoothed;
}
/**
* Fill null altitude values using nearest-neighbour interpolation.
*/
function fillNullAltitudes(
altitudes: Array<number | null>,
defaultAlt: number,
): number[] {
const out = altitudes.map((a) =>
a !== null && Number.isFinite(a) ? a : NaN,
);
// Forward fill.
let lastValid = NaN;
for (let i = 0; i < out.length; i++) {
if (!isNaN(out[i])) {
lastValid = out[i];
} else if (!isNaN(lastValid)) {
out[i] = lastValid;
}
}
// Backward fill (for leading NaNs).
lastValid = NaN;
for (let i = out.length - 1; i >= 0; i--) {
if (!isNaN(out[i])) {
lastValid = out[i];
} else if (!isNaN(lastValid)) {
out[i] = lastValid;
}
}
return out.map((v) => (isNaN(v) ? defaultAlt : v));
}
/**
* Strip leading and trailing ground segments from a historical track.
* Keeps the first/last airborne waypoint as endpoints.
* Returns null if all waypoints are on the ground.
*/
export function filterGroundSegments<T extends WaypointLike>(
waypoints: T[],
): T[] | null {
let firstAirborne = -1;
let lastAirborne = -1;
for (let i = 0; i < waypoints.length; i++) {
if (!waypoints[i].onGround) {
if (firstAirborne === -1) firstAirborne = i;
lastAirborne = i;
}
}
if (firstAirborne === -1) return null;
return waypoints.slice(firstAirborne, lastAirborne + 1);
}

420
src/lib/trail-cleanup.ts Normal file
View File

@ -0,0 +1,420 @@
/**
* Path cleanup algorithms for flight trails.
*
* Provides:
* - Curvature-aware adaptive downsampling (Ramer-Douglas-Peucker)
* - Spike / backtrack point removal
* - Sharp-corner rounding (3D and 2D Bézier arcs)
* - Post-spline self-intersection (loop) detection and removal
*/
import type { ElevatedPoint } from "./trail-spline";
// ---------------------------------------------------------------------------
// Curvature-aware adaptive downsampling
// ---------------------------------------------------------------------------
/**
* Downsample a dense path to at most `maxPoints` while preserving detail
* at curves. Uses the Ramer-Douglas-Peucker algorithm adapted for 3D
* elevated points.
*/
export function adaptiveDownsample(
points: ElevatedPoint[],
maxPoints: number,
): ElevatedPoint[] {
if (points.length <= maxPoints) return points;
let lo = 0;
let hi = 5;
let bestResult = points;
for (let iter = 0; iter < 20; iter++) {
const mid = (lo + hi) / 2;
const result = rdpSimplify(points, mid);
if (result.length <= maxPoints) {
bestResult = result;
hi = mid;
} else {
lo = mid;
}
if (Math.abs(result.length - maxPoints) < maxPoints * 0.05) break;
}
if (bestResult.length < maxPoints * 0.5 && points.length > maxPoints) {
return uniformSample(points, maxPoints);
}
return bestResult;
}
/** Ramer-Douglas-Peucker simplification for 3D points. */
function rdpSimplify(
points: ElevatedPoint[],
epsilon: number,
): ElevatedPoint[] {
if (points.length <= 2) return points.slice();
const first = points[0];
const last = points[points.length - 1];
let maxDist = 0;
let maxIdx = 0;
for (let i = 1; i < points.length - 1; i++) {
const d = perpendicularDistance(points[i], first, last);
if (d > maxDist) {
maxDist = d;
maxIdx = i;
}
}
if (maxDist > epsilon) {
const left = rdpSimplify(points.slice(0, maxIdx + 1), epsilon);
const right = rdpSimplify(points.slice(maxIdx), epsilon);
return [...left.slice(0, -1), ...right];
}
return [first, last];
}
/** Perpendicular distance from a point to a line segment (2D, using lng/lat). */
function perpendicularDistance(
point: ElevatedPoint,
lineStart: ElevatedPoint,
lineEnd: ElevatedPoint,
): number {
const dx = lineEnd[0] - lineStart[0];
const dy = lineEnd[1] - lineStart[1];
const denom = dx * dx + dy * dy;
if (denom < 1e-12) {
const ex = point[0] - lineStart[0];
const ey = point[1] - lineStart[1];
return Math.sqrt(ex * ex + ey * ey);
}
const t = Math.max(
0,
Math.min(
1,
((point[0] - lineStart[0]) * dx + (point[1] - lineStart[1]) * dy) / denom,
),
);
const projX = lineStart[0] + t * dx;
const projY = lineStart[1] + t * dy;
const ex = point[0] - projX;
const ey = point[1] - projY;
return Math.sqrt(ex * ex + ey * ey);
}
/** Uniform sampling — picks evenly-spaced points, always including first and last. */
function uniformSample(
points: ElevatedPoint[],
count: number,
): ElevatedPoint[] {
if (points.length <= count) return points;
const out: ElevatedPoint[] = [points[0]];
const step = (points.length - 1) / (count - 1);
for (let i = 1; i < count - 1; i++) {
out.push(points[Math.round(i * step)]);
}
out.push(points[points.length - 1]);
return out;
}
// ---------------------------------------------------------------------------
// Spike / backtrack removal
// ---------------------------------------------------------------------------
/**
* Remove "spike" points where the path reverses direction sharply,
* creating V-shaped artifacts.
*/
export function removeSpikePoints(
path: [number, number][],
altitudes: Array<number | null>,
cosThreshold: number = -0.5,
): { path: [number, number][]; altitudes: Array<number | null> } {
if (path.length < 3) return { path, altitudes };
const keep: boolean[] = new Array(path.length).fill(true);
let removed = 0;
for (let pass = 0; pass < 3; pass++) {
let changed = false;
for (let i = 1; i < path.length - 1; i++) {
if (!keep[i]) continue;
let prevIdx = i - 1;
while (prevIdx >= 0 && !keep[prevIdx]) prevIdx--;
if (prevIdx < 0) continue;
let nextIdx = i + 1;
while (nextIdx < path.length && !keep[nextIdx]) nextIdx++;
if (nextIdx >= path.length) continue;
const prev = path[prevIdx];
const curr = path[i];
const next = path[nextIdx];
const dx1 = curr[0] - prev[0];
const dy1 = curr[1] - prev[1];
const dx2 = next[0] - curr[0];
const dy2 = next[1] - curr[1];
const len1 = Math.sqrt(dx1 * dx1 + dy1 * dy1);
const len2 = Math.sqrt(dx2 * dx2 + dy2 * dy2);
if (len1 < 1e-10 || len2 < 1e-10) continue;
const cos = (dx1 * dx2 + dy1 * dy2) / (len1 * len2);
if (cos < cosThreshold) {
keep[i] = false;
removed++;
changed = true;
}
}
if (!changed) break;
}
if (removed === 0) return { path, altitudes };
const newPath: [number, number][] = [];
const newAlt: Array<number | null> = [];
for (let i = 0; i < path.length; i++) {
if (keep[i]) {
newPath.push(path[i]);
newAlt.push(altitudes[i] ?? null);
}
}
return { path: newPath, altitudes: newAlt };
}
// ---------------------------------------------------------------------------
// Sharp-corner rounding (pre-spline loop prevention)
// ---------------------------------------------------------------------------
/**
* Round sharp corners in a 3D waypoint path by replacing each sharp turn
* with a smooth quadratic Bézier arc.
*/
export function roundSharpCorners3D(
points: ElevatedPoint[],
thresholdDeg: number = 20,
): ElevatedPoint[] {
if (points.length < 3) return points;
const thresholdRad = (thresholdDeg * Math.PI) / 180;
const result: ElevatedPoint[] = [points[0]];
for (let i = 1; i < points.length - 1; i++) {
const prev = points[i - 1];
const curr = points[i];
const next = points[i + 1];
const distPrev = Math.sqrt(
(curr[0] - prev[0]) ** 2 + (curr[1] - prev[1]) ** 2,
);
const distNext = Math.sqrt(
(next[0] - curr[0]) ** 2 + (next[1] - curr[1]) ** 2,
);
if (distPrev < 5e-4 || distNext < 5e-4) {
result.push(curr);
continue;
}
const headingIn = Math.atan2(curr[0] - prev[0], curr[1] - prev[1]);
const headingOut = Math.atan2(next[0] - curr[0], next[1] - curr[1]);
let delta = headingOut - headingIn;
if (delta > Math.PI) delta -= 2 * Math.PI;
if (delta < -Math.PI) delta += 2 * Math.PI;
const absDelta = Math.abs(delta);
if (absDelta > thresholdRad) {
const setback = Math.min(distPrev, distNext) * 0.45;
const t1Factor = setback / distPrev;
const T1: ElevatedPoint = [
curr[0] + (prev[0] - curr[0]) * t1Factor,
curr[1] + (prev[1] - curr[1]) * t1Factor,
curr[2] + (prev[2] - curr[2]) * t1Factor,
];
const t2Factor = setback / distNext;
const T2: ElevatedPoint = [
curr[0] + (next[0] - curr[0]) * t2Factor,
curr[1] + (next[1] - curr[1]) * t2Factor,
curr[2] + (next[2] - curr[2]) * t2Factor,
];
const arcCount = Math.max(
6,
Math.min(14, Math.round((10 * absDelta) / Math.PI)),
);
for (let j = 0; j <= arcCount; j++) {
const t = j / arcCount;
const u = 1 - t;
result.push([
u * u * T1[0] + 2 * u * t * curr[0] + t * t * T2[0],
u * u * T1[1] + 2 * u * t * curr[1] + t * t * T2[1],
u * u * T1[2] + 2 * u * t * curr[2] + t * t * T2[2],
]);
}
} else {
result.push(curr);
}
}
result.push(points[points.length - 1]);
return result;
}
/**
* Round sharp corners in a 2D path (for active / live trails).
* Same algorithm as roundSharpCorners3D but operates on [lng, lat] arrays.
*/
export function roundSharpCorners2D(
points: [number, number][],
thresholdDeg: number = 15,
): [number, number][] {
if (points.length < 3) return points;
const thresholdRad = (thresholdDeg * Math.PI) / 180;
const result: [number, number][] = [points[0]];
for (let i = 1; i < points.length - 1; i++) {
const prev = points[i - 1];
const curr = points[i];
const next = points[i + 1];
const distPrev = Math.sqrt(
(curr[0] - prev[0]) ** 2 + (curr[1] - prev[1]) ** 2,
);
const distNext = Math.sqrt(
(next[0] - curr[0]) ** 2 + (next[1] - curr[1]) ** 2,
);
if (distPrev < 5e-4 || distNext < 5e-4) {
result.push(curr);
continue;
}
const headingIn = Math.atan2(curr[0] - prev[0], curr[1] - prev[1]);
const headingOut = Math.atan2(next[0] - curr[0], next[1] - curr[1]);
let delta = headingOut - headingIn;
if (delta > Math.PI) delta -= 2 * Math.PI;
if (delta < -Math.PI) delta += 2 * Math.PI;
const absDelta = Math.abs(delta);
if (absDelta > thresholdRad) {
const setback = Math.min(distPrev, distNext) * 0.45;
const t1Factor = setback / distPrev;
const T1: [number, number] = [
curr[0] + (prev[0] - curr[0]) * t1Factor,
curr[1] + (prev[1] - curr[1]) * t1Factor,
];
const t2Factor = setback / distNext;
const T2: [number, number] = [
curr[0] + (next[0] - curr[0]) * t2Factor,
curr[1] + (next[1] - curr[1]) * t2Factor,
];
const arcCount = Math.max(
6,
Math.min(12, Math.round((8 * absDelta) / Math.PI)),
);
for (let j = 0; j <= arcCount; j++) {
const t = j / arcCount;
const u = 1 - t;
result.push([
u * u * T1[0] + 2 * u * t * curr[0] + t * t * T2[0],
u * u * T1[1] + 2 * u * t * curr[1] + t * t * T2[1],
]);
}
} else {
result.push(curr);
}
}
result.push(points[points.length - 1]);
return result;
}
// ---------------------------------------------------------------------------
// Post-spline self-intersection (loop) detection and removal
// ---------------------------------------------------------------------------
/** Check if two 2D line segments intersect (strict, not at endpoints). */
function segmentsIntersect(
a1: ElevatedPoint,
a2: ElevatedPoint,
b1: ElevatedPoint,
b2: ElevatedPoint,
): { hit: boolean; t: number } {
const ax = a2[0] - a1[0],
ay = a2[1] - a1[1];
const bx = b2[0] - b1[0],
by = b2[1] - b1[1];
const denom = ax * by - ay * bx;
if (Math.abs(denom) < 1e-15) return { hit: false, t: 0 };
const cx = b1[0] - a1[0],
cy = b1[1] - a1[1];
const t = (cx * by - cy * bx) / denom;
const u = (cx * ay - cy * ax) / denom;
return { hit: t > 0.01 && t < 0.99 && u > 0.01 && u < 0.99, t };
}
/**
* Detect and remove self-intersecting loops in a splined path.
*
* Uses a local search window (up to 120 segments ahead) so the cost is
* O(N × window) rather than O(N²).
*/
export function removePathLoops(path: ElevatedPoint[]): ElevatedPoint[] {
if (path.length < 8) return path;
let result = path;
const MAX_WINDOW = 120;
for (let pass = 0; pass < 5; pass++) {
let found = false;
outer: for (let i = 0; i < result.length - 3; i++) {
const maxJ = Math.min(i + MAX_WINDOW, result.length - 1);
for (let j = i + 2; j < maxJ; j++) {
const { hit, t } = segmentsIntersect(
result[i],
result[i + 1],
result[j],
result[j + 1],
);
if (hit) {
const ix: ElevatedPoint = [
result[i][0] + t * (result[i + 1][0] - result[i][0]),
result[i][1] + t * (result[i + 1][1] - result[i][1]),
result[i][2] + t * (result[i + 1][2] - result[i][2]),
];
const next = [...result.slice(0, i + 1), ix, ...result.slice(j + 1)];
result = next;
found = true;
break outer;
}
}
}
if (!found) break;
}
return result;
}

View File

@ -0,0 +1,20 @@
/**
* Trail smoothing utilities for historical flight tracks.
*
* This barrel re-exports from focused sub-modules:
* - trail-spline.ts: Centripetal Catmull-Rom spline interpolation
* - trail-altitude.ts: Altitude smoothing & ground-segment filtering
* - trail-cleanup.ts: Downsampling, spike removal, corner rounding, loop removal
*/
export { catmullRomSpline3D } from "./trail-spline";
export type { ElevatedPoint } from "./trail-spline";
export { smoothAltitudeProfile, filterGroundSegments } from "./trail-altitude";
export type { WaypointLike } from "./trail-altitude";
export {
adaptiveDownsample,
removeSpikePoints,
roundSharpCorners3D,
roundSharpCorners2D,
removePathLoops,
} from "./trail-cleanup";

283
src/lib/trail-spline.ts Normal file
View File

@ -0,0 +1,283 @@
/**
* Centripetal Catmull-Rom spline interpolation for 3D flight trails.
*
* The centripetal parameterisation (alpha = 0.5) avoids cusps and self-
* intersections that the uniform variant can produce.
*
* Reference: E. Yuksel, S. Schaefer, J. Keyser "On the parameterization
* of Catmull-Rom curves" (2011).
*/
export type ElevatedPoint = [lng: number, lat: number, altitude: number];
const CR_ALPHA = 0.5; // centripetal
function crKnot(ti: number, pi: ElevatedPoint, pj: ElevatedPoint): number {
const dx = pj[0] - pi[0];
const dy = pj[1] - pi[1];
const dz = pj[2] - pi[2];
const d2 = dx * dx + dy * dy + dz * dz;
// d^alpha where alpha = 0.5 → sqrt(d) → (d^2)^0.25
return ti + Math.pow(Math.max(d2, 1e-12), CR_ALPHA * 0.5);
}
/**
* Evaluate a single centripetal Catmull-Rom segment (P1→P2) at parameter t
* in [0,1]. P0 and P3 are the neighbouring control points.
*/
function crSegmentPoint(
P0: ElevatedPoint,
P1: ElevatedPoint,
P2: ElevatedPoint,
P3: ElevatedPoint,
t01: number,
): ElevatedPoint {
const t0 = 0;
const t1 = crKnot(t0, P0, P1);
const t2 = crKnot(t1, P1, P2);
const t3 = crKnot(t2, P2, P3);
const t = t1 + t01 * (t2 - t1);
const out: ElevatedPoint = [0, 0, 0];
for (let dim = 0; dim < 3; dim++) {
const p0 = P0[dim];
const p1 = P1[dim];
const p2 = P2[dim];
const p3 = P3[dim];
const A1 = safeLerp(p0, p1, t0, t1, t);
const A2 = safeLerp(p1, p2, t1, t2, t);
const A3 = safeLerp(p2, p3, t2, t3, t);
const B1 = safeLerp(A1, A2, t0, t2, t);
const B2 = safeLerp(A2, A3, t1, t3, t);
out[dim] = safeLerp(B1, B2, t1, t2, t);
}
return out;
}
/** Lerp with guard against zero-length intervals. */
function safeLerp(
a: number,
b: number,
tA: number,
tB: number,
t: number,
): number {
const denom = tB - tA;
if (Math.abs(denom) < 1e-12) return (a + b) * 0.5;
return ((tB - t) / denom) * a + ((t - tA) / denom) * b;
}
/**
* Generate a virtual control point by reflecting the first/last segment.
*/
function reflectEndpoint(
anchor: ElevatedPoint,
neighbour: ElevatedPoint,
): ElevatedPoint {
return [
2 * anchor[0] - neighbour[0],
2 * anchor[1] - neighbour[1],
2 * anchor[2] - neighbour[2],
];
}
/**
* Determine how many interpolated points to insert in a segment based on
* its arc length (in degrees) and heading change.
*/
function segmentDensity(
a: ElevatedPoint,
b: ElevatedPoint,
prevHeading: number | null,
minPts: number,
maxPts: number,
): number {
const dx = b[0] - a[0];
const dy = b[1] - a[1];
const dist = Math.sqrt(dx * dx + dy * dy);
const heading = Math.atan2(dx, dy);
let curvatureFactor = 0;
if (prevHeading !== null) {
let delta = heading - prevHeading;
if (delta > Math.PI) delta -= 2 * Math.PI;
if (delta < -Math.PI) delta += 2 * Math.PI;
curvatureFactor = Math.abs(delta) / Math.PI;
}
const distFactor = Math.min(1, dist / 2);
const raw =
minPts + (maxPts - minPts) * Math.max(distFactor, curvatureFactor);
return Math.max(minPts, Math.min(maxPts, Math.round(raw)));
}
/**
* Interpolate sparse waypoints into a smooth 3D path using centripetal
* Catmull-Rom splines.
*
* @param points Ordered waypoints [lng, lat, alt]. Minimum 2 points.
* @param minPtsPerSeg Minimum interpolated points per segment (default 6).
* @param maxPtsPerSeg Maximum interpolated points per segment (default 28).
* @returns Smoothly interpolated path including all original waypoints.
*/
export function catmullRomSpline3D(
points: ElevatedPoint[],
minPtsPerSeg: number = 6,
maxPtsPerSeg: number = 28,
): ElevatedPoint[] {
if (points.length < 2) return points.slice();
if (points.length === 2) {
return linearInterpolateSegment(points[0], points[1], 8);
}
if (points.length === 3) {
const virtual0 = reflectEndpoint(points[0], points[1]);
const virtual3 = reflectEndpoint(points[2], points[1]);
return catmullRomSplineCore(
[virtual0, ...points, virtual3],
1,
points.length,
minPtsPerSeg,
maxPtsPerSeg,
);
}
const virtual0 = reflectEndpoint(points[0], points[1]);
const virtualN = reflectEndpoint(
points[points.length - 1],
points[points.length - 2],
);
const extended = [virtual0, ...points, virtualN];
return catmullRomSplineCore(
extended,
1,
points.length,
minPtsPerSeg,
maxPtsPerSeg,
);
}
/**
* Internal: Interpolate segments [startIdx .. startIdx+segCount-1] within
* the `extended` control-point array (which has virtual endpoints prepended/
* appended).
*
* Uses variable tension: straight segments (low heading change) get more
* linear interpolation to avoid S-curve wobble; turn segments get full
* Catmull-Rom curvature for smooth arcs.
*/
function catmullRomSplineCore(
extended: ElevatedPoint[],
startIdx: number,
segCount: number,
minPts: number,
maxPts: number,
): ElevatedPoint[] {
const result: ElevatedPoint[] = [];
let prevHeading: number | null = null;
const headings: number[] = [];
for (let i = 0; i < segCount - 1; i++) {
const idx = startIdx + i;
const P1 = extended[idx];
const P2 = extended[idx + 1];
headings.push(Math.atan2(P2[0] - P1[0], P2[1] - P1[1]));
}
for (let i = 0; i < segCount - 1; i++) {
const idx = startIdx + i;
const P0 = extended[idx - 1];
const P1 = extended[idx];
const P2 = extended[idx + 1];
const P3 = extended[idx + 2];
const nPts = segmentDensity(P1, P2, prevHeading, minPts, maxPts);
const headingBefore = i > 0 ? headings[i - 1] : headings[i];
const headingAfter =
i < headings.length - 1 ? headings[i + 1] : headings[i];
let deltaIn = headings[i] - headingBefore;
if (deltaIn > Math.PI) deltaIn -= 2 * Math.PI;
if (deltaIn < -Math.PI) deltaIn += 2 * Math.PI;
let deltaOut = headingAfter - headings[i];
if (deltaOut > Math.PI) deltaOut -= 2 * Math.PI;
if (deltaOut < -Math.PI) deltaOut += 2 * Math.PI;
const maxDelta = Math.max(Math.abs(deltaIn), Math.abs(deltaOut));
const STRAIGHT_THRESHOLD = (5 * Math.PI) / 180;
const CURVE_THRESHOLD = (20 * Math.PI) / 180;
const tension =
maxDelta <= STRAIGHT_THRESHOLD
? 0.92
: maxDelta >= CURVE_THRESHOLD
? 0.0
: 0.92 *
(1.0 -
(maxDelta - STRAIGHT_THRESHOLD) /
(CURVE_THRESHOLD - STRAIGHT_THRESHOLD));
result.push(P1);
for (let j = 1; j < nPts; j++) {
const t = j / nPts;
if (tension >= 0.98) {
result.push(lerpPoint(P1, P2, t));
} else if (tension <= 0.02) {
result.push(crSegmentPoint(P0, P1, P2, P3, t));
} else {
const splineP = crSegmentPoint(P0, P1, P2, P3, t);
const linearP = lerpPoint(P1, P2, t);
result.push([
linearP[0] * tension + splineP[0] * (1 - tension),
linearP[1] * tension + splineP[1] * (1 - tension),
linearP[2] * tension + splineP[2] * (1 - tension),
]);
}
}
prevHeading = headings[i];
}
result.push(extended[startIdx + segCount - 1]);
return result;
}
/** Linear interpolation between two elevated points. */
function lerpPoint(
a: ElevatedPoint,
b: ElevatedPoint,
t: number,
): ElevatedPoint {
return [
a[0] + (b[0] - a[0]) * t,
a[1] + (b[1] - a[1]) * t,
a[2] + (b[2] - a[2]) * t,
];
}
/** Simple linear interpolation for 2-point paths. */
function linearInterpolateSegment(
a: ElevatedPoint,
b: ElevatedPoint,
count: number,
): ElevatedPoint[] {
const out: ElevatedPoint[] = [];
for (let i = 0; i <= count; i++) {
const t = i / count;
out.push([
a[0] + (b[0] - a[0]) * t,
a[1] + (b[1] - a[1]) * t,
a[2] + (b[2] - a[2]) * t,
]);
}
return out;
}

457
src/lib/trail-stitching.ts Normal file
View File

@ -0,0 +1,457 @@
/**
* Trail stitching — merges sparse historical track data with the high-
* frequency live trail to produce a single smooth path.
*
* Extracted from the ~120-line inline `mergedTrails` computation in
* flight-tracker.tsx so the logic is testable, documented, and the
* thresholds are named constants.
*/
import { snapLngToReference, unwrapLngPath } from "@/lib/geo";
import {
catmullRomSpline3D,
filterGroundSegments,
smoothAltitudeProfile,
adaptiveDownsample,
removeSpikePoints,
roundSharpCorners3D,
removePathLoops,
} from "@/lib/trail-smoothing";
import type { FlightTrack } from "@/lib/opensky";
import type { TrailEntry } from "@/hooks/use-trail-history";
import type { FlightState } from "@/lib/opensky";
// ---------------------------------------------------------------------------
// Named thresholds (were magic numbers in the old inline code)
// ---------------------------------------------------------------------------
/** Number of recent live-trail points to append after the historical track. */
const LIVE_TAIL_POINT_COUNT = 18;
/** Maximum search depth (from end) when looking for overlap between the
* historical track and the live tail. Increased to account for spline
* densification of sparse waypoints. */
const OVERLAP_SEARCH_WINDOW = 150;
/** If the closest point on the historical track is within this distance
* (degrees) of the first live-tail point, snap them together. */
const MERGE_SNAP_DEG = 0.06;
/** If the gap is larger than MERGE_SNAP but smaller than this, insert a
* smooth bridge between the track end and the live tail start. */
const CONNECT_BRIDGE_DEG = 0.07;
/** Maximum gap (degrees) before we give up trying to connect stale history
* to the live tail. Scaled by altitude: low flights are more constrained
* because their waypoints are denser. */
const MAX_GAP_HIGH_ALT_DEG = 3.5;
const MAX_GAP_LOW_ALT_DEG = 1.25;
const LOW_ALTITUDE_THRESHOLD = 6_000; // meters
/** If the track's last waypoint is this old AND the gap is moderate, treat
* the historical data as disconnected (stale). */
const STALE_DISCONNECT_GAP_DEG = 0.06;
const STALE_DISCONNECT_AGE_SEC = 900;
const MODERATE_DISCONNECT_GAP_DEG = 0.1;
const MODERATE_DISCONNECT_AGE_SEC = 300;
const HARD_DISCONNECT_GAP_DEG = 0.25;
/** Default speed assumption when the flight state doesn't report one. */
const DEFAULT_SPEED_MPS = 140;
const MIN_SPEED_MPS = 30;
/** Maximum distance (degrees) from the live position to the nearest track
* waypoint before we reject the track as belonging to a different flight
* or being hopelessly stale. */
const TRACK_REJECT_HIGH_ALT_DEG = 6;
const TRACK_REJECT_LOW_ALT_DEG = 2.8;
/** Maximum number of interpolated steps when bridging a gap. */
const BRIDGE_MAX_STEPS = 24;
const BRIDGE_MIN_STEPS = 6;
const BRIDGE_STEP_SIZE_DEG = 0.15;
/** Maximum points after spline interpolation before downsampling. */
const MAX_SPLINED_POINTS = 1800;
// ---------------------------------------------------------------------------
// Slerp-based great-circle bridge (for smooth gap interpolation)
// ---------------------------------------------------------------------------
/**
* Spherical linear interpolation between two [lng, lat] points.
* More accurate than linear interpolation for gaps > ~0.1°.
*/
function slerpBridge(
aLng: number,
aLat: number,
bLng: number,
bLat: number,
t: number,
): [number, number] {
// For very small distances, linear interpolation is fine and avoids
// numerical issues in the slerp formula.
const dLng = bLng - aLng;
const dLat = bLat - aLat;
if (dLng * dLng + dLat * dLat < 0.01 * 0.01) {
return [aLng + dLng * t, aLat + dLat * t];
}
// Convert to radians.
const toRad = Math.PI / 180;
const la1 = aLat * toRad;
const lo1 = aLng * toRad;
const la2 = bLat * toRad;
const lo2 = bLng * toRad;
// Great-circle angular distance.
const dLat2 = la2 - la1;
const dLon2 = lo2 - lo1;
const a =
Math.sin(dLat2 / 2) ** 2 +
Math.cos(la1) * Math.cos(la2) * Math.sin(dLon2 / 2) ** 2;
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
if (c < 1e-10) {
return [aLng + dLng * t, aLat + dLat * t];
}
const sinC = Math.sin(c);
const A = Math.sin((1 - t) * c) / sinC;
const B = Math.sin(t * c) / sinC;
const x =
A * Math.cos(la1) * Math.cos(lo1) + B * Math.cos(la2) * Math.cos(lo2);
const y =
A * Math.cos(la1) * Math.sin(lo1) + B * Math.cos(la2) * Math.sin(lo2);
const z = A * Math.sin(la1) + B * Math.sin(la2);
const toDeg = 180 / Math.PI;
return [
Math.atan2(y, x) * toDeg,
Math.atan2(z, Math.sqrt(x * x + y * y)) * toDeg,
];
}
/**
* Cubic ease-in-out for altitude interpolation during bridge segments.
* Produces a more natural transition than linear.
*/
function cubicEaseInOut(t: number): number {
return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
}
// ---------------------------------------------------------------------------
// Main stitch function
// ---------------------------------------------------------------------------
export type StitchResult = {
path: [number, number][];
altitudes: Array<number | null>;
valid: boolean;
};
/**
* Stitch a historical flight track with the current live trail and live
* position into one continuous path.
*
* Steps:
* 1. Filter ground segments from historical track
* 2. Extract and unwrap positions
* 3. Validate track proximity to live position
* 4. Apply Catmull-Rom spline smoothing to sparse historical waypoints
* 5. Merge live tail with smoothed historical path
* 6. Ensure path reaches the aircraft
*/
export function stitchHistoricalTrail(
track: FlightTrack,
liveTail: TrailEntry | null,
livePosition: [number, number] | null,
flight: FlightState | null,
fetchedAtMs: number,
): StitchResult {
// --- Step 1: Filter ground segments ---
const airborneWaypoints = filterGroundSegments(track.path);
const waypoints = airborneWaypoints ?? track.path;
// --- Step 2: Extract and unwrap positions ---
const rawPositions: [number, number][] = [];
const rawAltitudes: Array<number | null> = [];
for (const p of waypoints) {
if (p.longitude == null || p.latitude == null) continue;
rawPositions.push([p.longitude, p.latitude]);
rawAltitudes.push(p.baroAltitude ?? null);
}
if (rawPositions.length < 2) {
return { path: [], altitudes: [], valid: false };
}
// Unwrap longitudes to avoid dateline artifacts.
const trackPositions = unwrapLngPath(rawPositions);
const trackAltitudes = [...rawAltitudes];
// --- Step 3: Validate track proximity to live position ---
const livePosAdjusted: [number, number] | null =
livePosition && trackPositions.length > 0
? [
snapLngToReference(
livePosition[0],
trackPositions[trackPositions.length - 1][0],
),
livePosition[1],
]
: livePosition;
const lastWaypointTime = waypoints[waypoints.length - 1]?.time;
const nowSec = fetchedAtMs > 0 ? Math.floor(fetchedAtMs / 1000) : 0;
const lastWaypointAgeSec =
typeof lastWaypointTime === "number" && Number.isFinite(lastWaypointTime)
? Math.max(0, nowSec - lastWaypointTime)
: 0;
const speedMps =
flight &&
Number.isFinite(flight.velocity) &&
flight.velocity! > MIN_SPEED_MPS
? Math.max(0, flight.velocity!)
: DEFAULT_SPEED_MPS;
const expectedDeg = (speedMps * lastWaypointAgeSec) / 111_320;
if (livePosAdjusted && trackPositions.length >= 2) {
const searchStart = Math.max(
0,
trackPositions.length - OVERLAP_SEARCH_WINDOW,
);
let bestDistSq = Number.POSITIVE_INFINITY;
for (let i = searchStart; i < trackPositions.length; i++) {
const p = trackPositions[i];
const dx = p[0] - livePosAdjusted[0];
const dy = p[1] - livePosAdjusted[1];
const d2 = dx * dx + dy * dy;
if (d2 < bestDistSq) bestDistSq = d2;
}
const lowAltitude =
flight && Number.isFinite(flight.baroAltitude)
? flight.baroAltitude! < LOW_ALTITUDE_THRESHOLD
: false;
const maxRejectDeg = lowAltitude
? TRACK_REJECT_LOW_ALT_DEG
: TRACK_REJECT_HIGH_ALT_DEG;
const maxAllowedDeg = Math.min(
maxRejectDeg,
Math.max(lowAltitude ? 0.75 : 0.9, expectedDeg * 1.35 + 0.22),
);
if (bestDistSq > maxAllowedDeg * maxAllowedDeg) {
return { path: [], altitudes: [], valid: false };
}
}
// --- Step 4: Apply Catmull-Rom spline smoothing ---
// Build elevated points for spline interpolation.
const defaultAlt =
flight?.baroAltitude ?? rawAltitudes.find((a) => a != null) ?? 0;
const smoothedAlts = smoothAltitudeProfile(trackAltitudes, defaultAlt);
const elevatedWaypoints: [number, number, number][] = trackPositions.map(
(p, i) => [p[0], p[1], smoothedAlts[i] ?? defaultAlt],
);
// Pre-process: round sharp corners with Bézier arcs so the spline
// doesn't overshoot into self-intersecting loops at sharp turns.
const roundedWaypoints = roundSharpCorners3D(elevatedWaypoints, 20);
// Apply Catmull-Rom spline to produce a smooth path.
let splinedPath = catmullRomSpline3D(roundedWaypoints, 6, 28);
// Safety net: detect and remove any self-intersecting loops the
// spline may still have produced (e.g. from outlier waypoints).
splinedPath = removePathLoops(splinedPath);
// Downsample if the splined path is very dense.
if (splinedPath.length > MAX_SPLINED_POINTS) {
splinedPath = adaptiveDownsample(splinedPath, MAX_SPLINED_POINTS);
}
// Separate back into 2D path + altitudes for compatibility with TrailEntry.
const resultPath: [number, number][] = splinedPath.map((p) => [p[0], p[1]]);
const resultAltitudes: Array<number | null> = splinedPath.map((p) => p[2]);
// --- Step 5: Merge live tail ---
if (liveTail && liveTail.path.length >= 2) {
const tailCount = LIVE_TAIL_POINT_COUNT;
const start = Math.max(0, liveTail.path.length - tailCount);
const rawTailPath = liveTail.path.slice(start);
const tailAlt = liveTail.altitudes.slice(start);
// Unwrap tail points relative to the historical track end.
const tailPath: [number, number][] = [];
let refLng =
resultPath.length > 0
? resultPath[resultPath.length - 1][0]
: rawTailPath[0][0];
for (const [lng, lat] of rawTailPath) {
const nextLng = snapLngToReference(lng, refLng);
tailPath.push([nextLng, lat]);
refLng = nextLng;
}
const lowAltitude =
flight && Number.isFinite(flight.baroAltitude)
? flight.baroAltitude! < LOW_ALTITUDE_THRESHOLD
: false;
const maxConnectGapDeg = lowAltitude
? MAX_GAP_LOW_ALT_DEG
: MAX_GAP_HIGH_ALT_DEG;
const firstTail = tailPath[0];
const searchStart = Math.max(0, resultPath.length - OVERLAP_SEARCH_WINDOW);
let bestIndex = -1;
let bestDistSq = Number.POSITIVE_INFINITY;
for (let i = searchStart; i < resultPath.length; i++) {
const p = resultPath[i];
const dx = p[0] - firstTail[0];
const dy = p[1] - firstTail[1];
const d2 = dx * dx + dy * dy;
if (d2 < bestDistSq) {
bestDistSq = d2;
bestIndex = i;
}
}
if (bestIndex >= 0 && bestDistSq <= MERGE_SNAP_DEG * MERGE_SNAP_DEG) {
// Snap overlap: trim historical track and connect.
resultPath.splice(bestIndex + 1);
resultAltitudes.splice(bestIndex + 1);
const join = resultPath[resultPath.length - 1];
if (join) {
tailPath[0] = join;
const joinAlt = resultAltitudes[resultAltitudes.length - 1] ?? null;
tailAlt[0] = joinAlt ?? tailAlt[0] ?? null;
}
} else {
// No overlap: evaluate whether to disconnect or bridge.
const last = resultPath[resultPath.length - 1];
const lastAlt = resultAltitudes[resultAltitudes.length - 1] ?? null;
if (last) {
const dx = last[0] - firstTail[0];
const dy = last[1] - firstTail[1];
const gap = Math.sqrt(dx * dx + dy * dy);
const shouldDisconnect =
gap > HARD_DISCONNECT_GAP_DEG ||
(lastWaypointAgeSec > STALE_DISCONNECT_AGE_SEC &&
gap > STALE_DISCONNECT_GAP_DEG) ||
(lastWaypointAgeSec > MODERATE_DISCONNECT_AGE_SEC &&
gap > MODERATE_DISCONNECT_GAP_DEG);
if (shouldDisconnect) {
// Discard stale history, use only the live tail.
resultPath.splice(0, resultPath.length, ...tailPath);
resultAltitudes.splice(0, resultAltitudes.length, ...tailAlt);
tailPath.length = 0;
tailAlt.length = 0;
} else {
if (gap > maxConnectGapDeg) {
// Gap too large to bridge — drop the tail.
tailPath.length = 0;
} else if (gap > CONNECT_BRIDGE_DEG) {
// Insert a great-circle bridge with eased altitude.
const steps = Math.max(
BRIDGE_MIN_STEPS,
Math.min(BRIDGE_MAX_STEPS, Math.ceil(gap / BRIDGE_STEP_SIZE_DEG)),
);
const firstTailAlt = tailAlt[0] ?? null;
for (let s = 1; s < steps; s++) {
const t = s / steps;
const [lng, lat] = slerpBridge(
last[0],
last[1],
firstTail[0],
firstTail[1],
t,
);
resultPath.push([lng, lat]);
if (lastAlt == null && firstTailAlt == null) {
resultAltitudes.push(null);
} else {
const a0 = lastAlt ?? firstTailAlt ?? 0;
const a1 = firstTailAlt ?? lastAlt ?? a0;
// Cubic ease for altitude bridge.
resultAltitudes.push(a0 + (a1 - a0) * cubicEaseInOut(t));
}
}
} else {
// Small gap — snap the tail start to the track end.
tailPath[0] = last;
tailAlt[0] = lastAlt ?? tailAlt[0] ?? null;
}
}
}
}
// Append remaining tail points (skip consecutive duplicates + near-duplicates).
for (let i = 0; i < tailPath.length; i++) {
const pos = tailPath[i];
const alt = tailAlt[i] ?? null;
const last = resultPath[resultPath.length - 1];
if (last) {
const dx = pos[0] - last[0];
const dy = pos[1] - last[1];
// Skip near-duplicates (< ~10m apart) to avoid micro-segments.
if (dx * dx + dy * dy < 0.0001 * 0.0001) continue;
}
resultPath.push(pos);
resultAltitudes.push(alt);
}
}
// --- Step 6: Ensure the trail reaches the aircraft ---
if (livePosAdjusted) {
const last = resultPath[resultPath.length - 1];
if (last) {
const dx = livePosAdjusted[0] - last[0];
const dy = livePosAdjusted[1] - last[1];
if (dx * dx + dy * dy > 0.0001 * 0.0001) {
resultPath.push(livePosAdjusted);
resultAltitudes.push(flight?.baroAltitude ?? null);
}
} else {
resultPath.push(livePosAdjusted);
resultAltitudes.push(flight?.baroAltitude ?? null);
}
}
if (resultPath.length < 2) {
return { path: [], altitudes: [], valid: false };
}
// --- Step 7: Remove V-shaped spikes (backtrack artifacts) ---
const cleaned = removeSpikePoints(resultPath, resultAltitudes);
if (cleaned.path.length < 2) {
return { path: [], altitudes: [], valid: false };
}
// --- Step 8: Round sharp corners at the historical↔live junction ---
// The splined historical path has gentle per-point heading changes (~3-10°)
// so roundSharpCorners3D will ONLY add arcs where there's a significant
// heading discontinuity — typically at the merge junction or in the tail.
const merged3D: [number, number, number][] = cleaned.path.map((p, i) => [
p[0],
p[1],
(cleaned.altitudes[i] as number) ?? 0,
]);
const rounded = roundSharpCorners3D(merged3D, 25);
const finalPath = rounded.map<[number, number]>((p) => [p[0], p[1]]);
const finalAlts = rounded.map<number | null>((p) => p[2]);
return { path: finalPath, altitudes: finalAlts, valid: true };
}