Compare commits

...
Author SHA1 Message Date
Mazeyar Moeini FeizabadiandClaude Fable 5.2 cc5718bb82 docs(changelog): add the #1712 fragment
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:06:05 +01:00
Mazeyar Moeini FeizabadiandClaude Fable 5.2 f47313ff3b perf(vessels): prune the AIS store on a timer and evict in insertion order
Every AIS position message walked both the vessel map and the pending-track
map to expire stale entries, and once the store was past its 50,000 cap it
also sorted every row to find the one to evict. The static-data map was never
pruned at all.

The expiry walk now runs on the existing 15 s AIS watchdog tick. Readers
already filtered rows by age; the track reader and the pending first fix now
check age too, so nothing expired is served between ticks. The vessel map is
re-inserted on update, which keeps it least recently updated first, so the
cap is enforced per message by dropping from the front. A vessel's static
entry goes when the vessel does, and static entries that never got a position
are held to the same cap.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 14:43:43 +01:00
Sameh Khamis 188f0ccd9b Merge pull request #1696 from bilawalsidhu/sameh/i18n-entry
feat(i18n): an ./i18n entry for an application with its own language choice
2026-11-12 22:21:25 -08:00
Sameh Khamis ad9bd0f4f9 docs(changelog): 1696-i18n-entry 2026-11-12 22:07:30 -08:00
Sameh Khamis 5f96009b67 feat(i18n): an ./i18n entry for an application with its own language choice
startPageLocale, followPageLocale and switchLocale start, follow and switch
the page's language as the standalone application and the globe picker do,
for an application that offers the language elsewhere and passes
localePicker: false. The standalone application uses them.
2026-11-12 22:07:13 -08:00
Sameh Khamis feab48397f Merge pull request #1695 from bilawalsidhu/sameh/vessel-photos
feat(vessels): a selected vessel shows its Open Vessel Photos photo and MMSI
2026-11-12 20:42:37 -08:00
Sameh Khamis e4832c589c Merge branch 'main' into sameh/vessel-photos 2026-11-12 20:32:03 -08:00
Sameh Khamis e3069612b5 Merge pull request #1694 from bilawalsidhu/sameh/cctv-globe-plane-clamp
fix(cctv): on a globe map the camera plane ends where the view meets the ground
2026-11-12 20:31:59 -08:00
Sameh Khamis a930677c83 Merge branch 'main' into sameh/cctv-globe-plane-clamp 2026-11-12 20:22:04 -08:00
Sameh Khamis 3da5ffe71f Merge pull request #1693 from bilawalsidhu/sameh/cctv-frame-no-flash
fix(cctv): a new camera's frame shows the moment it is decoded, without a fade
2026-11-12 20:21:44 -08:00
Sameh Khamis 2bc3c1bed1 docs(changelog): 1695-vessel-photos 2026-11-12 20:11:20 -08:00
Sameh Khamis d5b030e7fa docs(changelog): 1694-cctv-globe-plane-clamp 2026-11-12 20:11:19 -08:00
Sameh Khamis 23aa1027fc docs(changelog): 1693-cctv-frame-no-flash 2026-11-12 20:11:17 -08:00
Sameh Khamis 347e77d1f6 feat(vessels): a selected vessel shows its Open Vessel Photos photo and MMSI
Selecting a vessel asks Open Vessel Photos (a free, keyless API) for its
photo by MMSI, once per MMSI. The CONTACTS view shows it under the vessel's
name and MMSI with the photographer, the photo's open licence and a link to
the vessel's page; only images on Open Vessel Photos' own host are shown, and
an answer about another MMSI is no photo. The vessel source exposes the lookup
as getEnrichment({kind: 'photo'}) and fetchOpenVesselPhoto for applications
with their own vessel source.
2026-11-12 20:10:30 -08:00
Sameh Khamis 2445af349d fix(cctv): on a globe map the camera plane ends where the view meets the ground
The activation probe raycast only the photoreal tiles. On a globe map the ray
missed, or ran on through the Earth and met a primitive thousands of
kilometres away, and the monitor plane stood at the camera's full range:
about a kilometre wide and hundreds of metres up. A hit at or beyond the range
now counts as none, and on a globe map the plane also clamps short of the
globe's terrain along the axis, or flat ground at the mount's ground while
that terrain is still loading, whichever is nearer.
2026-11-12 20:10:02 -08:00
Sameh Khamis 6e4df4c287 fix(cctv): a new camera's frame shows the moment it is decoded, without a fade
The preview settled when the image had loaded, so the panel's <img> took the
src while it was still decoding and then faded in over 180 ms: every camera
click lingered on an empty box. The preview now settles once the frame is
decoded (a rejected decode still shows the loaded frame, and a decode that
never settles shows it after one second), and the fade is gone.
2026-11-12 20:10:02 -08:00
55 changed files with 1243 additions and 71 deletions

No files matched your search

+4 -2
View File
@@ -31,6 +31,7 @@ How to read this:
| **adsb.lol** | Military flights + aircraft traces | ODbL 1.0 | "adsb.lol" (ODbL) |
| **adsbdb** (`api.adsbdb.com`) | Aircraft type, model name and registration by ICAO hex for enriched flights; airline and origin/destination airports for the tracked flight's callsign | No licence or rate limit is published for the service. Its own credits: aircraft data from PlaneBase, ICAO-to-N-number conversion by Guillaume Michel, and flight route data that "is the work of David Taylor, Edinburgh and Jim Mason, Glasgow, and may not be copied, published, or incorporated into other databases without the explicit permission of David J Taylor, Edinburgh" | "adsbdb — api.adsbdb.com" (courtesy); route data credited to David Taylor, Edinburgh, and Jim Mason, Glasgow |
| **Planespotters.net** (`api.planespotters.net/pub/photos/hex/{hex}`) | One thumbnail photo of the tracked aircraft, by ICAO hex, in the CONTEXT panel's CONTACTS view under the tracked flight's name | [Planespotters photo API terms](https://www.planespotters.net/photo/api); each photo remains the copyright of its photographer. Thumbnails may be hotlinked on the condition that the photographer is named next to the photo and the photo links to its Planespotters page with a followable link | "Photo © {photographer}" beside every photo that names one, linked to its Planespotters page; "Planespotters.net" in Data attribution |
| **Open Vessel Photos** (`openvesselphotos.org/v1/mmsi/{mmsi}`) | One photo of the selected vessel, by MMSI, in the CONTEXT panel's CONTACTS view under the vessel's name and MMSI | Free, keyless public API ([README](https://github.com/louptheron/openvesselphotos)); each photo keeps the open licence its author chose (CC BY, CC BY-SA, CC0, or public domain), given with it in the API | "Photo: {photographer} · {licence}" beside every photo, linked to the vessel's Open Vessel Photos page; "Open Vessel Photos" in Data attribution |
| **AISStream.io** | Live vessels (AIS) | Free, beta, no formal ToS; AIS is a public broadcast | "AISStream.io" (courtesy) |
| **CelesTrak** | Satellite TLEs (SGP4) and SATCAT records (object type, operational status, owner) that file each satellite under a class | US-government-origin data, no license; citation requested | "CelesTrak (celestrak.org), Dr. T.S. Kelso" |
| **The Space Devs — Launch Library 2 v2.3** | Recent launch, payload, stage, and recovery metadata for Space Missions (30d) | [The Space Devs terms of use](https://github.com/TheSpaceDevs/Tutorials/blob/main/faqs/faq_TSD.md#terms-of-use): data may be used and shared in any form; avoid forwarding it without added value; attribution is encouraged (not mandatory). [Official API limits](https://ll.thespacedevs.com/docs/): 15 unauthenticated calls/hour; optional token | "Launch Library 2 — The Space Devs" (courtesy attribution) |
@@ -238,7 +239,8 @@ The optional Local ADS-B layer and the broadcast-FM receiver use radio you recei
- **adsbdb enrichment.** `/api/adsbdb` resolves an ICAO hex to aircraft type, model name and registration, and the tracked flight's callsign to an airline and an origin/destination pair. Fan-out is deliberately small because adsbdb is a free community API that publishes no quota: at most 4 requests in flight, dispatches dripped to roughly 5/s, and each key asked for at most once per session (for the flights layer's enrichment, a lookup that failed temporarily, such as an outage, a timeout, a rate limit or an authorization refusal that may clear, may be asked again after a 60-second cool-down; an answer, found or not, and a permanent refusal such as a 404 are final; Local ADS-B lookups are asked once), with route lookups reserved for the tracked aircraft. The dev-server proxy caches each key for 24 hours in `.gev-cache/adsbdb.json`, negative answers included, so fresh entries survive server restarts. That gitignored cache remains local to the deployment and is not bundled with this repo. adsbdb publishes no general service license; its README says the route data may not be copied, published, or incorporated into other databases without the explicit permission of David J Taylor, Edinburgh. Deployers are responsible for obtaining any permission their use requires. Enrichment is best-effort and fail-silent — a flight that gets no answer keeps what the flight feed already gave it.
- **Planespotters photos.** When you track an aircraft, the browser asks `https://api.planespotters.net/pub/photos/hex/{hex}` directly (the API answers cross-origin, so no key and no server proxy are involved) for that aircraft only, once per hex per session, through the same enrichment queue as adsbdb, with an 8-second timeout. A miss is remembered for the session; a request that failed temporarily (an outage, the timeout or a rate limit) may be asked again after a 60-second cool-down while the aircraft stays tracked, as for the flights layer's other enrichment. Either way no photo shows meanwhile. The first photo whose image is an `https://` URL on `*.plnspttrs.net`, and whose page is an `https://www.planespotters.net` URL is shown in the CONTEXT panel's CONTACTS view, under the tracked flight's name (`src/ui/views/panels/AwarenessPanel.vue`), and nowhere else; a vessel, an installation, a military aircraft or a converted TR-3B has none, and a military aircraft or TR-3B is never looked up. Anything else is dropped, so the app never shows or links outside Planespotters (`src/data/planespottersPhoto.js`, also exported as `gods-eye-view/sources/planespotters` for servers that cache the lookup). The photo follows the attribution rules: the thumbnail is hotlinked from the URL the API gives (never copied or re-hosted), the photographer's name, when the answer gives one, is visible text next to it ("Photo © {photographer}"; a photo whose answer names no one shows no credit line), and the photo and credit are a plain link to the photo's Planespotters page with `target="_blank" rel="noopener"` and never `rel="nofollow"`. If the image fails to load, the photo and its credit are hidden.
- **Planespotters photos.** When you track an aircraft, the browser asks `https://api.planespotters.net/pub/photos/hex/{hex}` directly (the API answers cross-origin, so no key and no server proxy are involved) for that aircraft only, once per hex per session, through the same enrichment queue as adsbdb, with an 8-second timeout. A miss is remembered for the session; a request that failed temporarily (an outage, the timeout or a rate limit) may be asked again after a 60-second cool-down while the aircraft stays tracked, as for the flights layer's other enrichment. Either way no photo shows meanwhile. The first photo whose image is an `https://` URL on `*.plnspttrs.net`, and whose page is an `https://www.planespotters.net` URL is shown in the CONTEXT panel's CONTACTS view, under the tracked flight's name (`src/ui/views/panels/AwarenessPanel.vue`), and nowhere else; a vessel (see Open Vessel Photos below), an installation, a military aircraft or a converted TR-3B has none, and a military aircraft or TR-3B is never looked up. Anything else is dropped, so the app never shows or links outside Planespotters (`src/data/planespottersPhoto.js`, also exported as `gods-eye-view/sources/planespotters` for servers that cache the lookup). The photo follows the attribution rules: the thumbnail is hotlinked from the URL the API gives (never copied or re-hosted), the photographer's name, when the answer gives one, is visible text next to it ("Photo © {photographer}"; a photo whose answer names no one shows no credit line), and the photo and credit are a plain link to the photo's Planespotters page with `target="_blank" rel="noopener"` and never `rel="nofollow"`. If the image fails to load, the photo and its credit are hidden.
- **Open Vessel Photos.** When you select a vessel with a nine-digit MMSI, the browser asks `https://openvesselphotos.org/v1/mmsi/{mmsi}` directly (the API is keyless and answers cross-origin, so no key and no server proxy are involved; account credentials are never sent) for that vessel only, once per MMSI per session, with an 8-second timeout. A miss (a 404 or a vessel without photos) is remembered for the session; a failed request may be asked again after five minutes. The first photo whose image is an `https://openvesselphotos.org` URL and which names a licence is shown, at the 800 px size, in the CONTEXT panel's CONTACTS view under the vessel's name and MMSI (`src/ui/views/panels/AwarenessPanel.vue`), and nowhere else (`src/data/openVesselPhoto.js`, `src/layers/vessels/photos.js`). The image is hotlinked from the URL the API gives (never copied or re-hosted); the photographer and licence are visible text next to it ("Photo: {photographer} · {licence}", or "Photo · {licence}" when the answer names no one), and the photo and credit link to the vessel's Open Vessel Photos page with `target="_blank" rel="noopener"`. If the image fails to load, the photo and its credit are hidden.
- **Launch Library 2.** `/api/launches` makes a server-side rolling-30-day query against the supported v2.3 detailed launch endpoint, caches successful responses for 15 minutes in memory and on disk, and serves the last successful response during a throttle or transient outage. Anonymous access is limited to 15 calls/hour; deployments can provide `LL2_API_TOKEN` for authenticated access. The Space Devs' published terms permit using and sharing the API data in any form, ask users not to forward it without adding value, disclaim complete accuracy, and encourage—but do not require—attribution. This app keeps a courtesy credit. Payload and stage/recovery records are shown only when supplied. Failed launches expose their source status and never receive fallback orbit geometry or a live/estimated marker. LL2 supplies launch context and event timing, not continuous ascent telemetry or live orbital state.
- **TfL JamCams.** The camera list comes from the keyless `api.tfl.gov.uk` endpoint (an optional `TFL_APP_KEY` raises its rate limit); frames come from TfL's public S3 bucket. The "Powered by TfL Open Data" attribution is required by TfL's terms and is registered in the Data attribution popover.
- **Ontario 511 CCTV.** The camera list comes from the `511on.ca/api/v2/get/cameras` endpoint, which now requires a free developer key (`ONTARIO_511_API_KEY`: sign up at 511on.ca/my511/register, then request it while logged in at 511on.ca/developers/doc; throttled to 10 calls a minute). Without the key the pack is skipped. Frames are server-registered still images under `511on.ca/map/Cctv/`. The source is live-fetched at runtime and attributed under the Open Government Licence - Ontario. Access is governed by Ontario 511's Developer's Access Agreement (511on.ca/developers/resources): the data stays under the Open Government Licence - Ontario unless otherwise specified; key requests are reviewed case by case and ask for the intended use and any third parties that will receive the data; attribution by link to 511on.ca is encouraged, and the Ontario 511 logo may not be altered or used to imply endorsement (this app links and shows no logo); and the data is provided "as is", a disclaimer distributors should pass on, which the credit does.
@@ -686,4 +688,4 @@ NOAA density imagery with the raw GLM product.
## In-app attribution
The required Google Maps / Cesium credit renders on the on-globe credit line (`#cesium-credits`, bottom-left) and must stay visible — including in clean-view and recording modes (the whole line, logo + "Google Maps" + the "Data attribution" link, stays on screen; only the GEV panels/HUD fade). The layer-specific credits (adsb.lol, adsbdb, Planespotters.net, TeleGeography, OSM datacenters/dams/roads, NASA FIRMS, CelesTrak, USGS, City of Austin, Fintraffic, GBFS, Radio Browser, OpenSky, AISStream) are registered into the expandable **"Data attribution"** popover on that credit line via `viewer.creditDisplay.addStaticCredit(new Cesium.Credit(html, /* showOnScreen */ false))` — see `src/data/dataCredits.js`. When you add a new data source, add its license and attribution to this file **and** append an entry to `DATA_CREDITS` in `src/data/dataCredits.js` so it surfaces in the app.
The required Google Maps / Cesium credit renders on the on-globe credit line (`#cesium-credits`, bottom-left) and must stay visible — including in clean-view and recording modes (the whole line, logo + "Google Maps" + the "Data attribution" link, stays on screen; only the GEV panels/HUD fade). The layer-specific credits (adsb.lol, adsbdb, Planespotters.net, Open Vessel Photos, TeleGeography, OSM datacenters/dams/roads, NASA FIRMS, CelesTrak, USGS, City of Austin, Fintraffic, GBFS, Radio Browser, OpenSky, AISStream) are registered into the expandable **"Data attribution"** popover on that credit line via `viewer.creditDisplay.addStaticCredit(new Cesium.Credit(html, /* showOnScreen */ false))` — see `src/data/dataCredits.js`. When you add a new data source, add its license and attribution to this file **and** append an entry to `DATA_CREDITS` in `src/data/dataCredits.js` so it surfaces in the app.
+2
View File
@@ -0,0 +1,2 @@
- Show a new CCTV camera's frame the moment it is decoded, with no fade, so
switching cameras no longer lingers on an empty preview (samehkhamis, #1693).
@@ -0,0 +1,3 @@
- End a CCTV camera's monitor plane where its view meets the ground on globe
maps too, instead of a kilometre-wide plane hundreds of metres up
(samehkhamis, #1694).
+3
View File
@@ -0,0 +1,3 @@
- Show a selected vessel's photo from Open Vessel Photos, credited with its
photographer and open licence, and its MMSI beside its name in the CONTACTS
view (samehkhamis, #1695).
+3
View File
@@ -0,0 +1,3 @@
- Add an `./i18n` entry so an application with its own language menu can
start, follow and switch the interface language as the globe picker does
(samehkhamis, #1696).
+3
View File
@@ -0,0 +1,3 @@
- The AIS vessel store no longer walks every vessel for each position message.
Expiry runs on the existing 15 s tick, the cap evicts in update order, and a
vessel's static data is dropped with it (mazy1998, #1712).
+3 -1
View File
@@ -224,7 +224,9 @@ leaving out `command-dock` the voice control and its pointer reticle;
leaving out `context` the Bhote Koshi reconstruction panel; and leaving out
`intel-hud` the Intel HUD overlay (`#intel-hud`), whose readouts the HUD
implementation publishes to the `gev-hud` store. An unknown
view name is an error. A host that does not initialize Core's locale passes
view name is an error. An application that offers its own language choice
starts and switches the language with the `./i18n` entry (`startPageLocale`,
`followPageLocale`, `switchLocale`; see [I18N.md](./I18N.md)) and passes
`localePicker: false` to `createApplicationControls` instead of editing the
markup. Node tests that import application modules register the component
loader with `node --import=<core package>/build/register-vue`.
+20 -1
View File
@@ -2224,7 +2224,9 @@ Frame loading, calibration editing and status display have separate modules;
providers, camera placement and navigation policy retain their existing owners.
Changing cameras invalidates old image callbacks and cancels an unfinished
calibration edit. Failed refreshes preserve settled pixels for the same camera,
while a newly selected camera never shows the prior camera's image. Disposal
while a newly selected camera never shows the prior camera's image. A frame is
shown without a fade once it is decoded (or after one second if its decode never
settles), so a new camera's preview is blank only while its frame loads. Disposal
releases listeners, subscriptions, image handlers, summary timers and chip-hide timers.
## UI disposal
@@ -3199,6 +3201,15 @@ stays in view or tracked; an answer, found or not, and a permanent refusal
stay final for the session. A route belongs to the callsign it was looked up
for, so a callsign change drops the old route. See `DATA_SOURCES.md`.
A selected vessel gets a photo the same way. The browser asks Open Vessel
Photos for it by MMSI (`fetchOpenVesselPhoto` in
`src/sources/live/standalone.js`, read by `src/data/openVesselPhoto.js`), once
per MMSI (`src/layers/vessels/photos.js`), and the CONTACTS view shows it under
the vessel's name and MMSI ("NAME · MMSI 366999709") with the photographer,
the photo's open licence and a link to the vessel's page. A vessel without an
MMSI is never looked up; a miss stays final for the session, and a failed
lookup is asked again after five minutes.
`gods-eye-view/server/providers/live` is a Node-only entry for the existing
plugins and shared request helpers. Importing it starts no sockets or timers.
The existing aircraft normalizer is separately available through the portable
@@ -5069,6 +5080,10 @@ Shipped locales: **en** (source and fallback), **ar**, **de**, **es**, **fr**, *
views re-render, code that published translated text words it again through
`onLocaleChange`, and `<html lang>`/`dir` and the page's `data-i18n` markup
follow. Nothing is lost; a toast already on screen keeps its words.
An application that offers the language elsewhere (a menu) uses the
`./i18n` entry (`src/i18n/page.js`): `startPageLocale` at boot,
`followPageLocale` for the markup and `switchLocale`, which does what a
picker choice does, with `localePicker: false`.
- **Right to left.** Arabic (`ar`) and Hebrew (`he`) are in `RTL_LOCALES`, so
`<html dir="rtl">`: the title, style indicator, both panel stacks and their
icon rails swap sides through logical properties (`inset-inline-*`,
@@ -6570,6 +6585,10 @@ silently demoting every later lookup for the session.
far cap, retargeting the existing video/canvas texture pipeline. Stills are drawn at their source aspect, centered on the placeholder dark (`#01070c`), instead of being stretched to the 16:9 canvas. Manual calibration only —
auto-calibration and the drape mesh pipeline are deleted. A one-shot activation obstruction
probe (`pickFromRay` on camera activation, clamping the plane short of the first hit) remains;
a hit at or beyond the camera's range counts as a miss, and on a globe map the plane also clamps
short of the globe's terrain along the axis (flat ground at the mount's ground when terrain is
missed or met beyond the range), whichever is nearer, so it never stands at the full range there
(about a kilometre wide and hundreds of metres up);
ground placement is superseded by the shared-floor v3 behavior below. Calibration persists to
`godsEyeView.cctv.calibration.v2` (wiped clean, no v1 import); a panel-only CAL badge shows
`CALIBRATED`/`CURATED`/`RAW PRIOR` (no in-world tint). Panel is titled "CCTV" (not "CCTV
+25
View File
@@ -59,6 +59,30 @@ The language picker switches in place, without a reload. A view that calls `t()`
A toast already on screen keeps its words.
## An application with its own language choice
An application that composes Core and offers the language somewhere else (a menu, a settings page) imports the `./i18n` entry (`src/i18n/page.js`) and passes `localePicker: false` to `createApplicationControls`:
```js
import {
LOCALES,
LOCALE_NAMES,
followPageLocale,
getLocale,
onLocaleChange,
startPageLocale,
switchLocale,
} from '<core package>/i18n';
startPageLocale(document); // before any view renders: ?lang=, stored choice, browser, English; translates data-i18n markup
const stopFollowing = followPageLocale(document); // <html lang>/dir and data-i18n markup follow each switch
for (const code of LOCALES) addMenuItem(LOCALE_NAMES[code], code === getLocale());
menu.onChoose = (code) => switchLocale(code); // switched in place and stored (in ?lang when storage is blocked)
```
`switchLocale` does what a choice in the globe picker does, and returns `'unchanged'` for the active language. `onLocaleChange` tells the application's own menu to mark the new language.
## Rules
- **Pass literals.** `t('Close')`, not `t(label)` (unless `label` holds a `msg()` value) and never a template literal with `${…}`.
@@ -109,6 +133,7 @@ Icons (`aria-hidden="true"`, Material Symbols), comments, CSS values and lowerca
| `src/ui/i18n.js` | the page's vue-i18n instance: the active locale and the catalogs |
| `src/i18n/marker.js` | `msg` alone, for modules the server or tools import (no catalogs) |
| `src/i18n/locale.js` | shipped languages, their names, choosing the language at boot |
| `src/i18n/page.js` | the `./i18n` entry: start, follow and switch the page's language |
| `src/i18n/locales/<code>.json` | one catalog per language, keyed by English text |
| `src/i18n/same-as-english.json` | per language, the entries that stay as in English on purpose |
| `scripts/i18n.mjs` | `npm run i18n`: extracts messages, checks the catalogs, finds unmarked UI text |
+1
View File
@@ -99,6 +99,7 @@
"./application": "./src/app/application.js",
"./application/viewer": "./src/app/viewer.js",
"./time": "./src/time/worldClock.js",
"./i18n": "./src/i18n/page.js",
"./build/vite": {
"node": "./build/vite.js"
},
+6
View File
@@ -385,6 +385,8 @@
"src/layers/vessels/index.js",
"src/layers/vessels/ingestion.js",
"src/layers/vessels/lifecycle.js",
"src/layers/vessels/photos.js",
"src/layers/vessels/photos.test.mjs",
"src/layers/vessels/policy.js",
"src/layers/vessels/queries.js",
"src/layers/vessels/rendering.js",
@@ -1335,9 +1337,13 @@
"src/app/sourceComposition.js",
"src/app/sourceComposition.test.mjs",
"src/data/dataCredits.js",
"src/data/openVesselPhoto.js",
"src/data/openVesselPhoto.test.mjs",
"src/data/layerState.js",
"src/data/layerState.test.mjs",
"src/data/spriteOrder.js",
"src/i18n/page.js",
"src/i18n/page.test.mjs",
"src/i18n/locales/ar.json",
"src/i18n/locales/de.json",
"src/i18n/locales/es.json",
+35 -5
View File
@@ -175,6 +175,28 @@
],
"external": ["vue", "pinia", "vue-i18n"]
},
"i18n": {
"exports": ["./i18n"],
"modules": [
"src/i18n/page.js",
"src/i18n/index.js",
"src/i18n/locale.js",
"src/i18n/locales/ar.json",
"src/i18n/locales/de.json",
"src/i18n/locales/es.json",
"src/i18n/locales/fr.json",
"src/i18n/locales/he.json",
"src/i18n/locales/it.json",
"src/i18n/locales/ja.json",
"src/i18n/locales/pt.json",
"src/i18n/locales/ru.json",
"src/i18n/locales/sv.json",
"src/i18n/locales/uk.json",
"src/i18n/locales/zh-CN.json",
"src/i18n/locales/zh-Hant.json"
],
"external": []
},
"time": {
"exports": ["./time"],
"modules": ["src/time/worldClock.js"],
@@ -1474,7 +1496,8 @@
"src/sources/live/index.js",
"src/sources/live/standalone.js",
"src/sources/live/vessels.js",
"src/data/planespottersPhoto.js"
"src/data/planespottersPhoto.js",
"src/data/openVesselPhoto.js"
],
"external": []
},
@@ -1696,7 +1719,9 @@
"src/i18n/locales/sv.json",
"src/i18n/locales/uk.json",
"src/i18n/locales/zh-CN.json",
"src/i18n/locales/zh-Hant.json"
"src/i18n/locales/zh-Hant.json",
"src/layers/vessels/photos.js",
"src/data/openVesselPhoto.js"
],
"external": ["cesium"]
},
@@ -3757,7 +3782,9 @@
"src/data/ucsSatellites.js",
"src/data/imagingSensors.js",
"src/data/planespottersPhoto.js",
"src/ui/stores/dataLibrary.js"
"src/ui/stores/dataLibrary.js",
"src/data/openVesselPhoto.js",
"src/layers/vessels/photos.js"
],
"external": [
"hls.js",
@@ -4467,7 +4494,9 @@
"src/layers/satellites/sensors.js",
"src/data/ucsSatellites.js",
"src/data/imagingSensors.js",
"src/data/planespottersPhoto.js"
"src/data/planespottersPhoto.js",
"src/layers/vessels/photos.js",
"src/data/openVesselPhoto.js"
],
"external": [
"hls.js",
@@ -5719,7 +5748,8 @@
"src/layers/satellites/sensors.js",
"src/data/ucsSatellites.js",
"src/data/imagingSensors.js",
"src/data/planespottersPhoto.js"
"src/data/planespottersPhoto.js",
"src/data/openVesselPhoto.js"
],
"external": ["@mapbox/vector-tile", "pbf"]
},
+4
View File
@@ -10,6 +10,7 @@ import {
readAisTrack,
aisStreamRows,
newestAisPositionAt,
pruneAisStreamCache,
} from './ais-store.js';
// ---------------------------------------------------------------------------
// AISStream live vessel cache state
@@ -338,6 +339,9 @@ function startAisStreamWatchdogTick() {
} catch (error) {
console.warn('[AISStream] watchdog tick failed', error?.message || '');
}
// The store no longer prunes per message; this tick is its expiry clock,
// so a silent feed still releases vessels it stopped hearing from.
pruneAisStreamCache();
}, AISSTREAM_TICK_MS);
_aisStreamTickTimer.unref?.();
}
+56 -19
View File
@@ -16,6 +16,8 @@ const _aisStreamStatic = new Map();
const _aisStreamTracks = new Map();
/** @type {Map<string,{lat:number,lon:number,epochSec:number}>} mmsi -> first fix awaiting second (lazy buffer allocation) */
const _aisStreamTrackPending = new Map();
/** Full prune walks so far; diagnostics only (see aisStreamCacheStats). */
let _aisStreamPruneWalks = 0;
/**
* Store one parsed AIS envelope.
@@ -105,6 +107,10 @@ export function ingestAisStreamEnvelope(envelope) {
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return true;
const staticData = _aisStreamStatic.get(mmsi) || {};
// Re-insert rather than overwrite: a Map iterates in insertion order, so
// this keeps the least recently updated vessel first and the cap can evict
// from the front instead of sorting every row.
_aisStreamVessels.delete(mmsi);
_aisStreamVessels.set(mmsi, {
lat,
lon,
@@ -132,10 +138,22 @@ export function ingestAisStreamEnvelope(envelope) {
aisEpochSeconds(metadata.time_utc ?? metadata.TimeUtc),
);
pruneAisStreamCache();
// Only the cap is enforced per message, and that is O(1). Expiry needs a
// walk of every row, so it runs on the caller's timer (pruneAisStreamCache);
// readers check age themselves in between.
while (_aisStreamVessels.size > AISSTREAM_CACHE_MAX)
dropAisVessel(_aisStreamVessels.keys().next().value);
return true;
}
/** Forget one vessel entirely, so no side map can outgrow the vessel map. */
function dropAisVessel(mmsi) {
_aisStreamVessels.delete(mmsi);
_aisStreamStatic.delete(mmsi);
_aisStreamTracks.delete(mmsi);
_aisStreamTrackPending.delete(mmsi);
}
/**
* Parses an AISStream UTC timestamp into epoch seconds (fallback: now).
*/
@@ -157,7 +175,12 @@ function appendAisTrackSample(mmsi, lat, lon, epochSec) {
let track = _aisStreamTracks.get(mmsi);
if (!track) {
const pending = _aisStreamTrackPending.get(mmsi);
if (!pending) {
// A first fix older than the retention window is treated as absent: the
// timed prune may not have removed it yet, and it must not seed a track.
const pendingCutoffSec = Math.floor(
(Date.now() - AISSTREAM_STALE_MS) / 1000,
);
if (!pending || pending.epochSec < pendingCutoffSec) {
_aisStreamTrackPending.set(mmsi, { lat, lon, epochSec });
return;
}
@@ -207,6 +230,10 @@ function writeAisTrackSample(track, lat, lon, epochSec) {
export function readAisTrack(mmsi) {
const track = _aisStreamTracks.get(mmsi);
if (!track || !track.len) return [];
// An expired vessel stays in the maps until the next timed prune; its track
// must read as gone straight away, as its row does in aisStreamRows.
const row = _aisStreamVessels.get(mmsi);
if (!row || row._updatedAt < Date.now() - AISSTREAM_STALE_MS) return [];
const samples = [];
const start =
(track.head - track.len + AIS_TRACK_SAMPLES) % AIS_TRACK_SAMPLES;
@@ -267,14 +294,18 @@ export function aisStreamRows(maxRows) {
return rows.slice(0, maxRows).map(({ _updatedAt, ...row }) => row);
}
function pruneAisStreamCache() {
/**
* Drop expired vessels and everything kept for them.
*
* This walks every row, so it runs on a timer (the AIS watchdog tick in
* ais-live.js) and not per message. Nothing depends on it for correctness:
* readers filter by age and ingest enforces the cap. It only frees memory.
*/
export function pruneAisStreamCache() {
_aisStreamPruneWalks++;
const cutoff = Date.now() - AISSTREAM_STALE_MS;
for (const [mmsi, row] of _aisStreamVessels) {
if (row._updatedAt < cutoff) {
_aisStreamVessels.delete(mmsi);
_aisStreamTracks.delete(mmsi);
_aisStreamTrackPending.delete(mmsi);
}
if (row._updatedAt < cutoff) dropAisVessel(mmsi);
}
// Pending single-fix entries for vessels never seen again must not leak
const pendingCutoffSec = Math.floor(cutoff / 1000);
@@ -282,20 +313,26 @@ function pruneAisStreamCache() {
if (pending.epochSec < pendingCutoffSec)
_aisStreamTrackPending.delete(mmsi);
}
if (_aisStreamVessels.size <= AISSTREAM_CACHE_MAX) return;
const ordered = [..._aisStreamVessels.entries()].sort(
(a, b) => a[1]._updatedAt - b[1]._updatedAt,
);
for (const [mmsi] of ordered.slice(
0,
_aisStreamVessels.size - AISSTREAM_CACHE_MAX,
)) {
_aisStreamVessels.delete(mmsi);
_aisStreamTracks.delete(mmsi);
_aisStreamTrackPending.delete(mmsi);
// Static data that arrived without a position has no vessel row to be
// dropped with. It is kept for the position that may follow, but only up to
// the vessel cap, oldest first, so the static map is bounded too.
for (const mmsi of _aisStreamStatic.keys()) {
if (_aisStreamStatic.size <= AISSTREAM_CACHE_MAX) break;
if (!_aisStreamVessels.has(mmsi)) _aisStreamStatic.delete(mmsi);
}
}
/** Map sizes and the number of prune walks, for tests and diagnostics. */
export function aisStreamCacheStats() {
return {
vessels: _aisStreamVessels.size,
statics: _aisStreamStatic.size,
tracks: _aisStreamTracks.size,
pendingTracks: _aisStreamTrackPending.size,
pruneWalks: _aisStreamPruneWalks,
};
}
export function newestAisPositionAt(rows) {
return rows[0]?.last_position_UTC || null;
}
+177
View File
@@ -0,0 +1,177 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as store from './ais-store.js';
const { AISSTREAM_CACHE_MAX, AISSTREAM_STALE_MS } = store;
// One clock for the whole file, only ever moved forward. The store is module
// state shared by every test here, so each test starts by stepping past the
// retention window: whatever an earlier test left behind is already expired.
let now = Date.parse('2030-01-01T00:00:00Z');
const useClock = (t) => {
now += AISSTREAM_STALE_MS + 60_000;
t.mock.method(Date, 'now', () => now);
};
const position = (mmsi, lat = 53.4, extraMetaData = {}) =>
store.ingestAisStreamEnvelope({
MessageType: 'PositionReport',
Message: { PositionReport: { UserID: Number(mmsi), Sog: 10, Cog: 90 } },
MetaData: {
MMSI: mmsi,
latitude: lat,
longitude: 6.2,
time_utc: new Date(now).toISOString(),
...extraMetaData,
},
});
// No position in the header, so this never creates a vessel row by itself.
const staticData = (mmsi, body) =>
store.ingestAisStreamEnvelope({
MessageType: 'ShipStaticData',
Message: { ShipStaticData: { UserID: Number(mmsi), ...body } },
MetaData: { MMSI: mmsi },
});
const rows = () => store.aisStreamRows(AISSTREAM_CACHE_MAX);
const rowFor = (mmsi) => rows().find((row) => row.mmsi === mmsi);
const mmsiAt = (index) => String(300000000 + index);
/** Fill the store to exactly the cap with vessels 0..cap-1, oldest first. */
const fillToCap = () => {
for (let index = 0; index < AISSTREAM_CACHE_MAX; index++) {
now += 1;
position(mmsiAt(index));
}
};
test('ingesting messages does not walk the whole cache per message', (t) => {
useClock(t);
const before = store.aisStreamCacheStats().pruneWalks;
for (let index = 0; index < 2000; index++) {
now += 1;
position(String(210000000 + (index % 200)));
}
assert.equal(store.aisStreamCacheStats().pruneWalks, before);
store.pruneAisStreamCache();
assert.equal(store.aisStreamCacheStats().pruneWalks, before + 1);
});
test('readers never see an expired vessel between timed prunes', (t) => {
useClock(t);
const mmsi = '211000001';
position(mmsi, 53.4);
now += 60_000;
position(mmsi, 53.5);
assert.equal(rowFor(mmsi).mmsi, mmsi);
assert.equal(store.readAisTrack(mmsi).length, 2);
// No prune and no other message: the entry is still in the maps.
now += AISSTREAM_STALE_MS + 1;
assert.equal(rowFor(mmsi), undefined);
assert.deepEqual(store.readAisTrack(mmsi), []);
});
test('a first fix older than the retention window never seeds a track', (t) => {
useClock(t);
const mmsi = '211000002';
const old = new Date(now - AISSTREAM_STALE_MS - 60_000).toISOString();
position(mmsi, 53.4, { time_utc: old });
now += 60_000;
position(mmsi, 53.5);
assert.deepEqual(store.readAisTrack(mmsi), []);
});
test('past the cap the least recently updated vessels are evicted', (t) => {
useClock(t);
fillToCap();
// Vessel 1 reports again, so it is no longer among the oldest.
now += 1;
position(mmsiAt(1));
for (let index = 0; index < 3; index++) {
now += 1;
position(mmsiAt(AISSTREAM_CACHE_MAX + index));
}
const kept = new Set(rows().map((row) => row.mmsi));
assert.equal(kept.size, AISSTREAM_CACHE_MAX);
assert.deepEqual(
[0, 1, 2, 3, 4].map((index) => kept.has(mmsiAt(index))),
[false, true, false, false, true],
);
for (let index = 0; index < 3; index++)
assert.ok(kept.has(mmsiAt(AISSTREAM_CACHE_MAX + index)));
});
test('an evicted vessel takes its static entry with it', (t) => {
useClock(t);
const evicted = mmsiAt(0);
staticData(evicted, { Type: 70, Destination: 'HAMBURG' });
fillToCap();
assert.equal(rowFor(evicted).type, '70');
now += 1;
position(mmsiAt(AISSTREAM_CACHE_MAX));
assert.equal(rowFor(evicted), undefined);
// Were the static entry still cached, the next position would pick it up.
now += 1;
position(evicted);
assert.equal(rowFor(evicted).type, '');
assert.equal(rowFor(evicted).destination, '');
});
test('the timed prune drops expired vessels and their static entries', (t) => {
useClock(t);
store.pruneAisStreamCache();
assert.deepEqual(
{ ...store.aisStreamCacheStats(), pruneWalks: 0 },
{ vessels: 0, statics: 0, tracks: 0, pendingTracks: 0, pruneWalks: 0 },
);
const mmsi = '211000003';
// Static data ahead of the first position must still reach the row, and
// must survive a prune while it waits.
staticData(mmsi, { Type: 70, Destination: 'HAMBURG' });
store.pruneAisStreamCache();
position(mmsi, 53.4);
now += 60_000;
position(mmsi, 53.5);
assert.equal(rowFor(mmsi).type, '70');
assert.equal(rowFor(mmsi).destination, 'HAMBURG');
const live = store.aisStreamCacheStats();
assert.deepEqual(
[live.vessels, live.statics, live.tracks],
[1, 1, 1],
);
now += AISSTREAM_STALE_MS + 1;
store.pruneAisStreamCache();
const pruned = store.aisStreamCacheStats();
assert.deepEqual(
[pruned.vessels, pruned.statics, pruned.tracks, pruned.pendingTracks],
[0, 0, 0, 0],
);
position(mmsi, 53.6);
assert.equal(rowFor(mmsi).type, '');
});
test('static entries that never get a position are capped, oldest first', (t) => {
useClock(t);
store.pruneAisStreamCache();
for (let index = 0; index < AISSTREAM_CACHE_MAX + 5; index++)
staticData(mmsiAt(index), { Type: 70 });
// A vessel with a row keeps its static entry however old that entry is.
position(mmsiAt(0));
assert.equal(store.aisStreamCacheStats().statics, AISSTREAM_CACHE_MAX + 5);
store.pruneAisStreamCache();
assert.equal(store.aisStreamCacheStats().statics, AISSTREAM_CACHE_MAX);
now += 1;
position(mmsiAt(0));
position(mmsiAt(3));
position(mmsiAt(AISSTREAM_CACHE_MAX));
assert.equal(rowFor(mmsiAt(0)).type, '70');
assert.equal(rowFor(mmsiAt(3)).type, '');
assert.equal(rowFor(mmsiAt(AISSTREAM_CACHE_MAX)).type, '70');
});
+2 -1
View File
@@ -9,7 +9,8 @@ import { t } from '../i18n/index.js';
* Construct the existing controls and camera presentation. `initialShareCode`
* opens a share code (the `<code>` of `/share/<code>`) at start-up, for a host
* whose address does not carry one. `localePicker: false` removes the language
* picker, for a host that does not initialize Core's locale.
* picker, for a host that offers its own language choice (`switchLocale` from
* the `./i18n` entry).
*/
export function createApplicationControls({
scene: { viewer, mapStackController, operations },
+1
View File
@@ -29,6 +29,7 @@ export const writeCalibrationStoreV2 = layer.writeCalibrationStoreV2;
export const deriveCalBadge = layer.deriveCalBadge;
export const computeFrustumGeometry = layer.computeFrustumGeometry;
export const activationProbeClampRange = layer.activationProbeClampRange;
export const flatGroundAxisDistance = layer.flatGroundAxisDistance;
export const frameSignatureFromPixels = layer.frameSignatureFromPixels;
export const _createCctvProjectionPlaneForTest =
layer._createCctvProjectionPlaneForTest;
+12
View File
@@ -35,6 +35,7 @@ import cctvLayer, {
_pushAmbientCardEntriesForTest,
_setCctvOverlayHostForTest,
activationProbeClampRange,
flatGroundAxisDistance,
bindCctvWorldClickGesture,
clearProbeClampOnDeactivation,
computeFrustumGeometry,
@@ -655,6 +656,17 @@ test('activation obstruction clamp uses the field-derived 12 m floor', () => {
assert.equal(activationProbeClampRange(210, 250), null);
});
test('on a globe map the axis ends on flat ground at the mount ground', () => {
// A 24 m mount pitched 30° down meets the ground 48 m along its axis.
assert.ok(Math.abs(flatGroundAxisDistance(24, -30) - 48) < 1e-9);
// The default 700 m range then clamps just short of that, not 700 m out.
const clamp = activationProbeClampRange(700, flatGroundAxisDistance(24, -30));
assert.ok(Math.abs(clamp - 44) < 1e-9);
assert.equal(flatGroundAxisDistance(24, 0), null);
assert.equal(flatGroundAxisDistance(24, 10), null);
assert.equal(flatGroundAxisDistance(0, -30), null);
});
test('deactivation clears the probe clamp and restores nominal frustum geometry', () => {
const record = {
camera: { ...UNCLAMPED_CAMERA },
+7
View File
@@ -141,6 +141,13 @@ export const DATA_CREDITS = [
'<a href="https://www.planespotters.net" target="_blank" rel="noopener">Planespotters.net</a> ' +
'· each photo is © its photographer, credited beside it',
},
{
key: 'openvesselphotos',
html:
'Vessel photos: ' +
'<a href="https://openvesselphotos.org" target="_blank" rel="noopener">Open Vessel Photos</a> ' +
"· each photo keeps its author's open licence, credited beside it",
},
{
key: 'aisstream',
html:
+7
View File
@@ -51,6 +51,13 @@ test('Planespotters is credited with a plain followable link', () => {
assert.doesNotMatch(credit.html, /nofollow/);
});
test('Open Vessel Photos is credited with a plain followable link', () => {
const credit = DATA_CREDITS.find((entry) => entry.key === 'openvesselphotos');
assert.ok(credit, 'the selected vessel photos come from Open Vessel Photos');
assert.match(credit.html, /href="https:\/\/openvesselphotos\.org"/);
assert.doesNotMatch(credit.html, /nofollow/);
});
test('the UCS Satellite Database is acknowledged with its version and webpage', () => {
// UCS database manual, section 3: references name the version (the Excel
// file's name) and link www.ucsusa.org/satellite_database.
+135
View File
@@ -0,0 +1,135 @@
/**
* @module openVesselPhoto
* @description Reads an Open Vessel Photos answer into the one photo every
* surface shows. Open Vessel Photos (https://openvesselphotos.org) serves a
* free, keyless JSON and image API by MMSI. Every photo keeps the open licence
* its author chose (CC BY, CC BY-SA, CC0 or public domain), so it is shown
* with its credit and licence and links back to the vessel's page. A photo
* whose image is not on Open Vessel Photos' own host, or whose answer names
* no licence, is "no photo": nothing arbitrary is ever shown or linked.
*
* Accepts the upstream answer (`GET https://openvesselphotos.org/v1/mmsi/{mmsi}`,
* `{mmsi, photos: [...]}`) and an already-read photo
* (`{found, src, width, height, photographer, licence, link}`).
* Pure: no fetch, no DOM.
*/
/** The only host a photo may come from or link to. */
const HOST = 'openvesselphotos.org';
/** The API's per-vessel answer. */
const API = `https://${HOST}/v1/mmsi/`;
/** The image width asked for: sharp in the panel on a 2× screen, ~60 KB. */
const IMAGE_SIZE = '800';
const NO_PHOTO = Object.freeze({ found: false });
/** A vessel's MMSI: nine digits. */
export const MMSI = /^\d{9}$/;
/** The API answer for one MMSI. */
export function openVesselPhotosUrl(mmsi) {
return API + mmsi;
}
/** The vessel's page on Open Vessel Photos. */
function vesselPage(mmsi) {
return `https://${HOST}/vessels/mmsi/${mmsi}`;
}
/** The parsed `https:` URL on the Open Vessel Photos host, or null. */
function ownUrl(value) {
if (typeof value !== 'string' || !value) return null;
let url;
try {
url = new URL(value);
} catch {
return null;
}
return url.protocol === 'https:' &&
!url.username &&
!url.password &&
!url.port &&
url.hostname === HOST
? url
: null;
}
function dimension(value) {
const number = Number(value);
return value != null && Number.isFinite(number) && number > 0
? Math.round(number)
: null;
}
function text(value) {
return typeof value === 'string' ? value.trim() : '';
}
/** One upstream photo of the vessel `mmsi`, checked. */
function checkedUpstream(photo, mmsi) {
if (!photo || typeof photo !== 'object') return null;
const image = ownUrl(photo.urls?.mmsi);
const licence = text(photo.licenceName) || text(photo.licence);
if (!image || !licence) return null;
image.search = '';
image.hash = '';
image.searchParams.set('size', IMAGE_SIZE);
// The answer gives the full image's size; the 800 px one keeps its shape.
const width = dimension(photo.width);
const height = dimension(photo.height);
const scale =
width && width > Number(IMAGE_SIZE) ? Number(IMAGE_SIZE) / width : 1;
return {
found: true,
src: image.href,
width: width ? Math.round(width * scale) : null,
height: height ? Math.round(height * scale) : null,
photographer: text(photo.credit),
licence,
link: vesselPage(mmsi),
};
}
/** An already-read photo, checked again. */
function checkedRead(photo) {
const image = ownUrl(photo.src);
const page = ownUrl(photo.link);
const licence = text(photo.licence);
if (!image || !page || !licence) return null;
return {
found: true,
src: image.href,
width: dimension(photo.width),
height: dimension(photo.height),
photographer: text(photo.photographer),
licence,
link: page.href,
};
}
/**
* Read an Open Vessel Photos answer into the first photo that passes the
* checks.
* @param {*} payload Upstream answer or already-read photo.
* @param {?string} [requestedMmsi] The MMSI asked for; an upstream answer
* naming another is no photo.
* @returns {{found: true, src: string, width: ?number, height: ?number,
* photographer: string, licence: string, link: string} | {found: false}}
*/
export function parseOpenVesselPhoto(payload, requestedMmsi = null) {
if (!payload || typeof payload !== 'object') return NO_PHOTO;
if (Array.isArray(payload.photos)) {
const mmsi = String(payload.mmsi ?? '');
if (!MMSI.test(mmsi)) return NO_PHOTO;
// An answer about another vessel is no photo of this one.
if (requestedMmsi != null && mmsi !== String(requestedMmsi))
return NO_PHOTO;
for (const photo of payload.photos) {
const checked = checkedUpstream(photo, mmsi);
if (checked) return checked;
}
return NO_PHOTO;
}
if (payload.found !== true) return NO_PHOTO;
return checkedRead(payload) || NO_PHOTO;
}
+120
View File
@@ -0,0 +1,120 @@
// src/data/openVesselPhoto.test.mjs — an Open Vessel Photos answer is read
// into one credited, licensed photo, and nothing outside Open Vessel Photos'
// own host is ever shown or linked.
import test from 'node:test';
import assert from 'node:assert/strict';
import {
openVesselPhotosUrl,
parseOpenVesselPhoto,
} from './openVesselPhoto.js';
const UPSTREAM = Object.freeze({
mmsi: '366999709',
name: '01 USCGC Sockeye WPB87337',
photos: [
{
n: 1,
urls: {
cfr: null,
mmsi: 'https://openvesselphotos.org/v1/mmsi/366999709/photos/1.jpg',
},
credit: 'Gordon Leggett',
licence: 'CC-BY-4.0',
licenceName: 'CC BY 4.0',
width: 1600,
height: 1200,
},
],
});
const PHOTO = Object.freeze({
found: true,
src: 'https://openvesselphotos.org/v1/mmsi/366999709/photos/1.jpg?size=800',
width: 800,
height: 600,
photographer: 'Gordon Leggett',
licence: 'CC BY 4.0',
link: 'https://openvesselphotos.org/vessels/mmsi/366999709',
});
const withPhoto = (overrides) => ({
...UPSTREAM,
photos: [{ ...UPSTREAM.photos[0], ...overrides }],
});
test('the upstream answer maps to the 800 px image, its credit, licence and page', () => {
assert.deepEqual(parseOpenVesselPhoto(UPSTREAM), PHOTO);
assert.equal(
openVesselPhotosUrl('366999709'),
'https://openvesselphotos.org/v1/mmsi/366999709',
);
});
test('an image narrower than 800 px keeps its own size', () => {
const photo = parseOpenVesselPhoto(withPhoto({ width: 640, height: 480 }));
assert.equal(photo.width, 640);
assert.equal(photo.height, 480);
});
test('an already-read photo passes through its checks again', () => {
assert.deepEqual(parseOpenVesselPhoto(PHOTO), PHOTO);
assert.deepEqual(parseOpenVesselPhoto({ ...PHOTO, licence: '' }), {
found: false,
});
});
test('a photo off the Open Vessel Photos host, or without a licence, is no photo', () => {
for (const overrides of [
{ urls: { mmsi: 'https://example.com/1.jpg' } },
{
urls: {
mmsi: 'http://openvesselphotos.org/v1/mmsi/366999709/photos/1.jpg',
},
},
{ urls: { mmsi: 'https://openvesselphotos.org.evil.com/1.jpg' } },
{ urls: { mmsi: 'https://[email protected]/1.jpg' } },
{ licence: '', licenceName: '' },
])
assert.deepEqual(parseOpenVesselPhoto(withPhoto(overrides)), {
found: false,
});
assert.deepEqual(
parseOpenVesselPhoto({ ...PHOTO, link: 'https://example.com/' }),
{ found: false },
);
});
test('a vessel without photos, or an answer with a bad MMSI, is no photo', () => {
assert.deepEqual(parseOpenVesselPhoto({ ...UPSTREAM, photos: [] }), {
found: false,
});
assert.deepEqual(parseOpenVesselPhoto({ ...UPSTREAM, mmsi: '12/../x' }), {
found: false,
});
assert.deepEqual(parseOpenVesselPhoto(null), { found: false });
});
test('the next photo stands in when the first fails its checks', () => {
const second = {
...UPSTREAM.photos[0],
n: 2,
urls: {
mmsi: 'https://openvesselphotos.org/v1/mmsi/366999709/photos/2.jpg',
},
};
const photo = parseOpenVesselPhoto({
...UPSTREAM,
photos: [{ ...UPSTREAM.photos[0], licenceName: '', licence: '' }, second],
});
assert.equal(
photo.src,
'https://openvesselphotos.org/v1/mmsi/366999709/photos/2.jpg?size=800',
);
});
test('an answer about another vessel than the one asked for is no photo', () => {
assert.deepEqual(parseOpenVesselPhoto(UPSTREAM, '366999709'), PHOTO);
assert.deepEqual(parseOpenVesselPhoto(UPSTREAM, '227000101'), {
found: false,
});
});
+2
View File
@@ -3804,6 +3804,8 @@
"(+{minutes} min late)": "(تأخير {minutes} د)",
"Exit cockpit to fly to a train": "اخرج من القمرة للانتقال إلى قطار",
"Photo © {photographer}": "صورة © {photographer}",
"Photo: {photographer} · {licence}": "صورة: {photographer} · {licence}",
"Photo · {licence}": "صورة · {licence}",
"The shared flight isn't reporting now — showing where it was last seen": "الرحلة المشتركة: لا بيانات واردة الآن — يُعرض آخر موضع معروف",
"The shared flight isn't reporting now — showing where it was at {time}": "الرحلة المشتركة: لا بيانات واردة الآن — يُعرض موضعها عند {time}",
"The shared military flight isn't reporting now — showing where it was last seen": "الرحلة العسكرية المشتركة: لا بيانات واردة الآن — يُعرض آخر موضع معروف",
+2
View File
@@ -3480,6 +3480,8 @@
"(+{minutes} min late)": "(+{minutes} min Verspätung)",
"Exit cockpit to fly to a train": "Cockpit verlassen, um zu einem Zug zu fliegen",
"Photo © {photographer}": "Foto © {photographer}",
"Photo: {photographer} · {licence}": "Foto: {photographer} · {licence}",
"Photo · {licence}": "Foto · {licence}",
"The shared flight isn't reporting now — showing where it was last seen": "Der geteilte Flug sendet gerade nicht – letzte bekannte Position wird gezeigt",
"The shared flight isn't reporting now — showing where it was at {time}": "Der geteilte Flug sendet gerade nicht – Position um {time} wird gezeigt",
"The shared military flight isn't reporting now — showing where it was last seen": "Der geteilte Militärflug sendet gerade nicht – letzte bekannte Position wird gezeigt",
+2
View File
@@ -3561,6 +3561,8 @@
"(+{minutes} min late)": "(+{minutes} min de retraso)",
"Exit cockpit to fly to a train": "Sal de la cabina para volar a un tren",
"Photo © {photographer}": "Foto © {photographer}",
"Photo: {photographer} · {licence}": "Foto: {photographer} · {licence}",
"Photo · {licence}": "Foto · {licence}",
"The shared flight isn't reporting now — showing where it was last seen": "El vuelo compartido no está transmitiendo ahora; se muestra dónde se vio por última vez",
"The shared flight isn't reporting now — showing where it was at {time}": "El vuelo compartido no está transmitiendo ahora; se muestra dónde estaba a las {time}",
"The shared military flight isn't reporting now — showing where it was last seen": "El vuelo militar compartido no está transmitiendo ahora; se muestra dónde se vio por última vez",
+2
View File
@@ -3561,6 +3561,8 @@
"(+{minutes} min late)": "(+{minutes} min de retard)",
"Exit cockpit to fly to a train": "Quittez le cockpit pour rejoindre un train",
"Photo © {photographer}": "Photo © {photographer}",
"Photo: {photographer} · {licence}": "Photo : {photographer} · {licence}",
"Photo · {licence}": "Photo · {licence}",
"The shared flight isn't reporting now — showing where it was last seen": "Le vol partagé n'émet pas actuellement — affichage de sa dernière position connue",
"The shared flight isn't reporting now — showing where it was at {time}": "Le vol partagé n'émet pas actuellement — affichage de sa position à {time}",
"The shared military flight isn't reporting now — showing where it was last seen": "Le vol militaire partagé n'émet pas actuellement — affichage de sa dernière position connue",
+2
View File
@@ -3385,6 +3385,8 @@
"(+{minutes} min late)": "(+{minutes} דק׳ איחור)",
"Exit cockpit to fly to a train": "צא מתא הטייס כדי לטוס לרכבת",
"Photo © {photographer}": "צילום © {photographer}",
"Photo: {photographer} · {licence}": "צילום: {photographer} · {licence}",
"Photo · {licence}": "צילום · {licence}",
"1 h/s": "שעה/שנ׳",
"1 d/s": "יום/שנ׳",
"1 wk/s": "שבוע/שנ׳",
+2
View File
@@ -3561,6 +3561,8 @@
"(+{minutes} min late)": "(+{minutes} min di ritardo)",
"Exit cockpit to fly to a train": "Esci dal cockpit per volare a un treno",
"Photo © {photographer}": "Foto © {photographer}",
"Photo: {photographer} · {licence}": "Foto: {photographer} · {licence}",
"Photo · {licence}": "Foto · {licence}",
"The shared flight isn't reporting now — showing where it was last seen": "Il volo condiviso non sta trasmettendo ora: viene mostrata l'ultima posizione nota",
"The shared flight isn't reporting now — showing where it was at {time}": "Il volo condiviso non sta trasmettendo ora: viene mostrata la posizione alle {time}",
"The shared military flight isn't reporting now — showing where it was last seen": "Il volo militare condiviso non sta trasmettendo ora: viene mostrata l'ultima posizione nota",
+2
View File
@@ -3399,6 +3399,8 @@
"(+{minutes} min late)": "({minutes}分遅れ)",
"Exit cockpit to fly to a train": "列車へ移動するにはコックピットを終了してください",
"Photo © {photographer}": "写真 © {photographer}",
"Photo: {photographer} · {licence}": "写真:{photographer} · {licence}",
"Photo · {licence}": "写真 · {licence}",
"The shared flight isn't reporting now — showing where it was last seen": "共有されたフライトは現在報告していません。最後に確認された位置を表示しています",
"The shared flight isn't reporting now — showing where it was at {time}": "共有されたフライトは現在報告していません。{time}時点の位置を表示しています",
"The shared military flight isn't reporting now — showing where it was last seen": "共有された軍用機は現在報告していません。最後に確認された位置を表示しています",
+2
View File
@@ -3561,6 +3561,8 @@
"(+{minutes} min late)": "(+{minutes} min de atraso)",
"Exit cockpit to fly to a train": "Saia da cabine para voar até um trem",
"Photo © {photographer}": "Foto © {photographer}",
"Photo: {photographer} · {licence}": "Foto: {photographer} · {licence}",
"Photo · {licence}": "Foto · {licence}",
"The shared flight isn't reporting now — showing where it was last seen": "O voo compartilhado não está transmitindo agora — mostrando a última posição conhecida",
"The shared flight isn't reporting now — showing where it was at {time}": "O voo compartilhado não está transmitindo agora — mostrando onde estava às {time}",
"The shared military flight isn't reporting now — showing where it was last seen": "O voo militar compartilhado não está transmitindo agora — mostrando a última posição conhecida",
+2
View File
@@ -3642,6 +3642,8 @@
"(+{minutes} min late)": "(+{minutes} мин опоздания)",
"Exit cockpit to fly to a train": "Выйдите из кабины, чтобы перелететь к поезду",
"Photo © {photographer}": "Фото © {photographer}",
"Photo: {photographer} · {licence}": "Фото: {photographer} · {licence}",
"Photo · {licence}": "Фото · {licence}",
"The shared flight isn't reporting now — showing where it was last seen": "Общий рейс сейчас не передаёт данные — показано последнее известное место",
"The shared flight isn't reporting now — showing where it was at {time}": "Общий рейс сейчас не передаёт данные — показано место в {time}",
"The shared military flight isn't reporting now — showing where it was last seen": "Общий военный рейс сейчас не передаёт данные — показано последнее известное место",
+2
View File
@@ -3472,6 +3472,8 @@
"(+{minutes} min late)": "(+{minutes} min försenad)",
"Exit cockpit to fly to a train": "Lämna cockpiten för att flyga till ett tåg",
"Photo © {photographer}": "Foto © {photographer}",
"Photo: {photographer} · {licence}": "Foto: {photographer} · {licence}",
"Photo · {licence}": "Foto · {licence}",
"The shared flight isn't reporting now — showing where it was last seen": "Den delade flygningen rapporterar inte just nu – visar senast kända position",
"The shared flight isn't reporting now — showing where it was at {time}": "Den delade flygningen rapporterar inte just nu – visar positionen från {time}",
"The shared military flight isn't reporting now — showing where it was last seen": "Den delade militärflygningen rapporterar inte just nu – visar senast kända position",
+2
View File
@@ -3642,6 +3642,8 @@
"(+{minutes} min late)": "(+{minutes} хв запізнення)",
"Exit cockpit to fly to a train": "Вийдіть із кабіни, щоб перелетіти до поїзда",
"Photo © {photographer}": "Фото © {photographer}",
"Photo: {photographer} · {licence}": "Фото: {photographer} · {licence}",
"Photo · {licence}": "Фото · {licence}",
"The shared flight isn't reporting now — showing where it was last seen": "Спільний рейс зараз не передає даних — показано останнє відоме місце",
"The shared flight isn't reporting now — showing where it was at {time}": "Спільний рейс зараз не передає даних — показано місце о {time}",
"The shared military flight isn't reporting now — showing where it was last seen": "Спільний військовий рейс зараз не передає даних — показано останнє відоме місце",
+2
View File
@@ -3399,6 +3399,8 @@
"(+{minutes} min late)": "(晚点 {minutes} 分钟)",
"Exit cockpit to fly to a train": "请先退出座舱,再飞往列车",
"Photo © {photographer}": "照片 © {photographer}",
"Photo: {photographer} · {licence}": "照片:{photographer} · {licence}",
"Photo · {licence}": "照片 · {licence}",
"The shared flight isn't reporting now — showing where it was last seen": "共享的航班目前没有发送信号——显示其最后出现的位置",
"The shared flight isn't reporting now — showing where it was at {time}": "共享的航班目前没有发送信号——显示其在 {time} 的位置",
"The shared military flight isn't reporting now — showing where it was last seen": "共享的军用航班目前没有发送信号——显示其最后出现的位置",
+2
View File
@@ -3399,6 +3399,8 @@
"(+{minutes} min late)": "(誤點 {minutes} 分鐘)",
"Exit cockpit to fly to a train": "請先退出座艙,再飛往列車",
"Photo © {photographer}": "照片 © {photographer}",
"Photo: {photographer} · {licence}": "照片:{photographer} · {licence}",
"Photo · {licence}": "照片 · {licence}",
"The shared flight isn't reporting now — showing where it was last seen": "共享的航班目前沒有發送信號——顯示其最後出現的位置",
"The shared flight isn't reporting now — showing where it was at {time}": "共享的航班目前沒有發送信號——顯示其在 {time} 的位置",
"The shared military flight isn't reporting now — showing where it was last seen": "共享的軍用航班目前沒有發送信號——顯示其最後出現的位置",
+81
View File
@@ -0,0 +1,81 @@
/**
* @module i18n/page
* @description The page's interface language, for an application that
* composes Core and offers its own language choice (a menu item, a settings
* page) instead of the globe picker. It starts the language the standalone
* application starts, keeps `<html lang>`/`<html dir>` and the page's
* `data-i18n` markup in step, and switches in place, stored for the next
* visit, exactly as the picker does. Guide: docs/I18N.md.
*/
import {
DEFAULT_LOCALE,
LOCALES,
LOCALE_NAMES,
applyDocumentLanguage,
isRtlLocale,
normalizeLocale,
resolveLocale,
} from './locale.js';
import {
applyDocumentTranslations,
getLocale,
onLocaleChange,
persistLocale,
setLocale,
} from './index.js';
export {
DEFAULT_LOCALE,
LOCALES,
LOCALE_NAMES,
applyDocumentTranslations,
getLocale,
isRtlLocale,
onLocaleChange,
};
/**
* Start the page in its language: `?lang=`, then the stored choice, then the
* browser's languages, then English. Call it before any view renders, so
* every lookup and `<html lang>`/`<html dir>` agree from the first frame; the
* page's static `data-i18n` markup (a loading screen) is translated now.
* @param {Document} [doc]
* @param {Parameters<typeof resolveLocale>[0]} [inputs] Location, storage
* and languages, for tests.
* @returns {string} The active locale.
*/
export function startPageLocale(doc = globalThis.document, inputs) {
const locale = setLocale(resolveLocale(inputs));
applyDocumentLanguage(doc, locale);
applyDocumentTranslations(doc);
return locale;
}
/**
* Keep `<html lang>`/`<html dir>` and the page's `data-i18n` markup in step
* with every language switch.
* @param {Document} [doc]
* @returns {() => void} Stops following.
*/
export function followPageLocale(doc = globalThis.document) {
return onLocaleChange(() => {
applyDocumentLanguage(doc, getLocale());
applyDocumentTranslations(doc);
});
}
/**
* Switch the page to `locale` in place and keep it for the next visit. The
* active language, or an unknown code that would fall back to it, changes
* nothing.
* @param {string} locale One of LOCALES.
* @param {Parameters<typeof persistLocale>[1]} [options] Location, history
* and storage, for tests.
* @returns {'unchanged'|'switched'}
*/
export function switchLocale(locale, options) {
const next = normalizeLocale(locale) || DEFAULT_LOCALE;
if (next === getLocale()) return 'unchanged';
setLocale(persistLocale(next, options));
return 'switched';
}
+106
View File
@@ -0,0 +1,106 @@
// src/i18n/page.test.mjs — an application with its own language choice starts,
// follows and switches the page's language as the globe picker does.
import { afterEach, test } from 'node:test';
import assert from 'node:assert/strict';
import { LOCALE_STORAGE_KEY } from './locale.js';
import {
followPageLocale,
getLocale,
startPageLocale,
switchLocale,
} from './page.js';
import { setLocale } from './index.js';
afterEach(() => setLocale('en'));
function memoryStorage() {
const data = new Map();
return {
data,
getItem: (key) => data.get(key) ?? null,
setItem: (key, value) => data.set(key, String(value)),
};
}
function page(elements = []) {
return {
documentElement: { lang: '', dir: '' },
querySelectorAll: (selector) =>
selector === '[data-i18n]' ? elements : [],
};
}
/** A data-i18n element, as applyDocumentTranslations reads one. */
function marked(text) {
return {
textContent: text,
hasAttribute: (name) => name === 'data-i18n',
getAttribute: () => null,
};
}
test('the page starts in ?lang=, else the stored choice, with lang and dir set', () => {
const doc = page();
const storage = memoryStorage();
storage.setItem(LOCALE_STORAGE_KEY, 'de');
assert.equal(
startPageLocale(doc, {
location: { search: '?lang=ar' },
storage,
languages: ['ru'],
}),
'ar',
);
assert.equal(getLocale(), 'ar');
assert.deepEqual(doc.documentElement, { lang: 'ar', dir: 'rtl' });
assert.equal(
startPageLocale(doc, { location: { search: '' }, storage, languages: [] }),
'de',
);
assert.deepEqual(doc.documentElement, { lang: 'de', dir: 'ltr' });
});
test("the page's data-i18n markup is in its language from the start", () => {
const close = marked('Close');
startPageLocale(page([close]), {
location: { search: '?lang=de' },
storage: memoryStorage(),
languages: [],
});
assert.equal(close.textContent, 'Schließen');
});
test('a switch is stored, drops ?lang, and the followed page takes it', () => {
const doc = page();
const stop = followPageLocale(doc);
const storage = memoryStorage();
const replaced = [];
const options = {
location: { href: 'https://example.test/?lang=fr#view' },
history: { replaceState: (_s, _t, url) => replaced.push(url) },
storage,
};
assert.equal(switchLocale('he', options), 'switched');
assert.equal(getLocale(), 'he');
assert.equal(storage.data.get(LOCALE_STORAGE_KEY), 'he');
assert.deepEqual(replaced, ['https://example.test/#view']);
assert.deepEqual(doc.documentElement, { lang: 'he', dir: 'rtl' });
stop();
switchLocale('ja', options);
assert.deepEqual(doc.documentElement, { lang: 'he', dir: 'rtl' });
});
test('choosing the active language, or one that falls back to it, changes nothing', () => {
const storage = memoryStorage();
const options = {
location: { href: 'https://example.test/' },
history: { replaceState() {} },
storage,
};
assert.equal(switchLocale('en', options), 'unchanged');
assert.equal(switchLocale('xx', options), 'unchanged');
assert.equal(storage.data.size, 0);
assert.equal(switchLocale('pt-BR', options), 'switched');
assert.equal(getLocale(), 'pt');
assert.equal(switchLocale('pt', options), 'unchanged');
});
+1
View File
@@ -625,6 +625,7 @@
"▲ {frp} MW",
"SATELLITE",
"Photo © {photographer}",
"Photo · {licence}",
"PACK",
"{count} packs",
"Orthophoto",
+17 -5
View File
@@ -182,7 +182,22 @@ export function createPanel({ state: layerState, parts }) {
: null;
}
/** The tracked airliner's photo with its credit, or null. The subject
/** The credit line: the photographer, and an open photo's licence. A
* photo whose answer names no photographer shows no photographer. */
function photoCredit(photo) {
if (photo.licence)
return photo.photographer
? t('Photo: {photographer} · {licence}', {
photographer: photo.photographer,
licence: photo.licence,
})
: t('Photo · {licence}', { licence: photo.licence });
return photo.photographer
? t('Photo © {photographer}', { photographer: photo.photographer })
: '';
}
/** The subject's photo with its credit, or null. The subject
* refresh resolves it; only the subject it was resolved for shows it. */
function presentPhoto(subject) {
const held = layerState.subjectPhoto;
@@ -198,10 +213,7 @@ export function createPanel({ state: layerState, parts }) {
width: photo.width ?? null,
height: photo.height ?? null,
link: photo.link,
// A photo whose answer names no photographer shows no credit line.
credit: photo.photographer
? t('Photo © {photographer}', { photographer: photo.photographer })
: '',
credit: photoCredit(photo),
};
}
+46 -1
View File
@@ -113,7 +113,52 @@ test('the Contacts view has no photo without one, or with another subject’s',
);
});
test('only the tracked flight has a photo: not a vessel, an installation, a military aircraft or another flight', () => {
test('the selected vessel shows its own photo, by its id', () => {
const asked = [];
const { resolveSubjectPhoto, subjectFromContext } = createSubject({
state: {},
services: {
flights: {},
military: {},
vessels: {
getVesselPhoto: (id) => {
asked.push(id);
return id === 'uuid-1' ? PHOTO : null;
},
},
installations: {},
},
parts: { navigation: { isFlightLayer: () => false } },
});
assert.deepEqual(
resolveSubjectPhoto({ layerId: 'ais-live-vessels', id: 'uuid-1' }),
PHOTO,
);
assert.equal(
resolveSubjectPhoto({ layerId: 'ais-live-vessels', id: 'uuid-2' }),
null,
);
assert.deepEqual(asked, ['uuid-1', 'uuid-2']);
const vessel = (label, mmsi) =>
subjectFromContext({
layerId: 'ais-live-vessels',
id: 'ais-uuid-1',
label,
latitude: 38.3,
longitude: -123.05,
properties: { vesselId: 'uuid-1', mmsi },
});
assert.equal(
vessel('USCGC SOCKEYE', '366999709').label,
'USCGC SOCKEYE · MMSI 366999709',
);
assert.equal(vessel('USCGC SOCKEYE', '366999709').id, 'uuid-1');
// A vessel named by its MMSI, or without one, is not given it twice.
assert.equal(vessel('MMSI 366999709', '366999709').label, 'MMSI 366999709');
assert.equal(vessel('USCGC SOCKEYE', null).label, 'USCGC SOCKEYE');
});
test('only the tracked flight has a flight photo: not an installation, a military aircraft or another flight', () => {
const tracked = {
layerId: 'flights',
id: 'abc123',
+14 -6
View File
@@ -406,17 +406,20 @@ export function createSubject({ state: layerState, services, parts, source }) {
}
/**
* The tracked airliner's Planespotters photo, for the Contacts panel.
* The subject's photo, for the Contacts panel: the tracked airliner's
* Planespotters photo, or the selected vessel's Open Vessel Photos photo.
*
* Only the flights layer looks photos up, and only for the plane it tracks;
* a vessel, an installation, a military aircraft or an untracked flight has
* none.
* The flights layer looks photos up only for the plane it tracks, the
* vessel layer only for the vessel selected; an installation, a military
* aircraft or an untracked flight has none.
* @param {{layerId: string, id: string}|null} subject Current subject.
* @param {?object} [tracked] The subject's tracked descriptor, when the
* caller already has it.
* @returns {?{src: string, width: ?number, height: ?number, photographer: string, link: string}}
* @returns {?{src: string, width: ?number, height: ?number, photographer: string, link: string, licence?: string}}
*/
function resolveSubjectPhoto(subject, tracked = trackedSubjectOf(subject)) {
if (subject?.layerId === 'ais-live-vessels')
return aisLiveVesselsLayer.getVesselPhoto?.(subject.id) ?? null;
return subject?.layerId === 'flights' && tracked?.photo
? tracked.photo
: null;
@@ -517,10 +520,15 @@ export function createSubject({ state: layerState, services, parts, source }) {
const latitude = Number(record.latitude);
const longitude = Number(record.longitude);
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;
// A vessel reads as its name and MMSI; a vessel named by its MMSI alone
// already carries it.
const label = String(record.label || record.id);
const mmsi = String(record.properties?.mmsi || '');
return {
layerId: record.layerId,
id: record.properties?.vesselId || record.id,
label: record.label || record.id,
// i18n-ignore: MMSI is a radio identity code, as on the vessel card
label: mmsi && !label.includes(mmsi) ? `${label} · MMSI ${mmsi}` : label,
memberNames: record.properties?.memberNames || [],
position: Cesium.Cartesian3.fromDegrees(longitude, latitude, 0),
};
+51 -7
View File
@@ -260,6 +260,21 @@ export function createGeometry({ state: layerState, services, parts, source }) {
return Math.max(PROBE_MIN_RANGE_M, hitDistance - PROBE_CLEARANCE_M);
}
/**
* Distance along a pitched-down view axis to flat ground at the mount's own
* ground height, or null for an axis at or above the horizon.
* @param {number} mountHeightM Mount height above its ground.
* @param {number} pitchDeg Axis pitch (negative looks down).
* @returns {number|null}
*/
function flatGroundAxisDistance(mountHeightM, pitchDeg) {
const height = Number(mountHeightM);
const pitch = Number(pitchDeg);
if (!Number.isFinite(height) || height <= 0 || !(pitch < 0)) return null;
return height / Math.sin(Cesium.Math.toRadians(Math.min(89, -pitch)));
}
/**
* Converts a computeFrustumGeometry result into the Cartesian3 positions the
* entities consume. Fresh objects per call (geometry updates are rare —
@@ -616,10 +631,14 @@ export function createGeometry({ state: layerState, services, parts, source }) {
* range, clamp the plane's effective range just short of the first hit so the
* "big and dramatic" true end cap never clips into downtown buildings.
*
* This is the ONLY raycast in the whole CCTV subsystem — once per activation,
* never per-frame (the zero-raycast invariant applies to steady state). The
* per-camera range slider overrides the clamp: a user-set rangeScale skips the
* probe entirely. Probe failure/miss keeps the unclamped range.
* On a globe map it also picks the globe's terrain along the same axis
* (flat ground at the mount's ground when terrain is missed or met beyond
* the range) and clamps at the nearer end. These are the ONLY raycasts in the
* whole CCTV subsystem — once per activation, never per-frame (the
* zero-raycast invariant applies to steady state). The per-camera range
* slider overrides the clamp: a user-set rangeScale skips the probe
* entirely. A miss on the photoreal stack or a probe failure keeps the
* unclamped range.
* @param {Object} record - Camera record being activated.
*/
@@ -646,9 +665,33 @@ export function createGeometry({ state: layerState, services, parts, source }) {
for (const runtime of layerState._projectionEntities) {
if (runtime?.planeEntity) exclude.push(runtime.planeEntity);
}
const hit = scene.pickFromRay(new Cesium.Ray(mountPos, dir), exclude);
if (!hit?.position) return;
const dist = Cesium.Cartesian3.distance(mountPos, hit.position);
const ray = new Cesium.Ray(mountPos, dir);
// pickFromRay hits only primitives (the photoreal tiles), never the
// globe: on a globe map the ray runs on through the Earth and can meet
// a primitive thousands of kilometres away, which blocks nothing. Such
// a hit or none left the plane at the full nominal range, about a
// kilometre wide and hundreds of metres up. A hit at or beyond the range
// counts as none. On a globe map the axis also ends on the globe's
// terrain, the nearer of that and any primitive hit (a primitive behind
// a hill the axis has already entered blocks nothing). Terrain still
// loading at a coarse level can be missed or met beyond the range; then
// flat ground at the mount's own ground stands in for it.
const inRange = (distance) =>
Number.isFinite(distance) && distance > 0 && distance < camera.rangeM;
const hit = scene.pickFromRay(ray, exclude)?.position;
const hitDist = hit ? Cesium.Cartesian3.distance(mountPos, hit) : NaN;
const distances = inRange(hitDist) ? [hitDist] : [];
if (scene.globe?.show) {
const terrain = scene.globe.pick(ray, scene);
const terrainDist = terrain
? Cesium.Cartesian3.distance(mountPos, terrain)
: NaN;
const ground = inRange(terrainDist)
? terrainDist
: flatGroundAxisDistance(camera.mountHeightM, camera.pitchDeg);
if (Number.isFinite(ground) && ground > 0) distances.push(ground);
}
const dist = distances.length ? Math.min(...distances) : null;
record.probeClampRangeM = activationProbeClampRange(camera.rangeM, dist);
} catch {
// probe failure → keep the unclamped range
@@ -831,6 +874,7 @@ export function createGeometry({ state: layerState, services, parts, source }) {
hasShippedFootprint,
footprintPose,
activationProbeClampRange,
flatGroundAxisDistance,
frustumCartesians,
frustumFrameEcef,
applyFrustumGeometry,
+1
View File
@@ -73,6 +73,7 @@ export function createCctvLayer({ services, source }) {
deriveCalBadge: parts.calibration.deriveCalBadge,
computeFrustumGeometry: parts.geometry.computeFrustumGeometry,
activationProbeClampRange: parts.geometry.activationProbeClampRange,
flatGroundAxisDistance: parts.geometry.flatGroundAxisDistance,
frameSignatureFromPixels: parts.frames.frameSignatureFromPixels,
_createCctvProjectionPlaneForTest:
parts.testing._createCctvProjectionPlaneForTest,
+5
View File
@@ -7,6 +7,7 @@ import { createRendering } from './rendering.js';
import { createSelection } from './selection.js';
import { createTracking } from './tracking.js';
import { createCards } from './cards.js';
import { createPhotos } from './photos.js';
import { createTesting } from './testing.js';
import { createEvidence } from './evidence.js';
import { createQueries } from './queries.js';
@@ -24,6 +25,7 @@ export function createVesselLayer({ source, services, options = {} } = {}) {
parts.selection = createSelection(context);
parts.tracking = createTracking(context);
parts.cards = createCards(context);
parts.photos = createPhotos(context);
parts.testing = createTesting(context);
parts.evidence = createEvidence(context);
parts.queries = createQueries(context);
@@ -90,6 +92,9 @@ export function createVesselLayer({ source, services, options = {} } = {}) {
buildVesselCard: parts.cards.buildVesselCard,
buildSelectedVesselCard: parts.cards.buildSelectedVesselCard,
cardScreenSeparated: parts.cards.cardScreenSeparated,
/** The vessel's Open Vessel Photos photo, once its lookup answered. */
getVesselPhoto: (id) =>
parts.photos.vesselPhoto(vesselState.state.records.byId.get(id)),
});
Object.defineProperty(layer, 'testing', { value: parts.testing });
return layer;
+56
View File
@@ -0,0 +1,56 @@
import { MMSI, parseOpenVesselPhoto } from '../../data/openVesselPhoto.js';
/** A failed lookup is asked again after this long; a miss is final. */
const PHOTO_RETRY_MS = 5 * 60 * 1000;
/** Lookups remembered per session, oldest dropped first. */
const PHOTO_CACHE_LIMIT = 500;
/**
* The selected vessel's photo, looked up once per MMSI when it is selected.
* The answer is read with `parseOpenVesselPhoto` whatever shape the source
* returns, so only a checked photo is ever kept. A source without
* `getEnrichment` has no photos.
*/
export function createPhotos({ vesselState }) {
/** MMSI → photo, `null` for a final miss, or `{failedAtMs}`/`{pending}`. */
const answers = new Map();
function remember(mmsi, answer) {
answers.delete(mmsi);
answers.set(mmsi, answer);
if (answers.size > PHOTO_CACHE_LIMIT)
answers.delete(answers.keys().next().value);
}
/** Ask for the record's photo unless it is known, asked or cooling down. */
function requestVesselPhoto(record, now = Date.now()) {
const mmsi = String(record?.mmsi || '');
const source = vesselState._source;
if (!MMSI.test(mmsi) || typeof source?.getEnrichment !== 'function') return;
const known = answers.get(mmsi);
if (known !== undefined) {
if (known?.pending || known === null || known.found) return;
if (now - known.failedAtMs < PHOTO_RETRY_MS) return;
}
remember(mmsi, { pending: true });
Promise.resolve()
.then(() => source.getEnrichment({ kind: 'photo', id: mmsi }))
.then(
(answer) => {
const photo = parseOpenVesselPhoto(answer);
remember(mmsi, photo.found ? photo : null);
},
() => remember(mmsi, { failedAtMs: Date.now() }),
);
}
/** The vessel's checked photo, or null. */
function vesselPhoto(record) {
const answer = answers.get(String(record?.mmsi || ''));
if (!answer?.found) return null;
const { src, width, height, photographer, licence, link } = answer;
return { src, width, height, photographer, licence, link };
}
return { requestVesselPhoto, vesselPhoto };
}
+87
View File
@@ -0,0 +1,87 @@
// src/layers/vessels/photos.test.mjs — a selected vessel's photo is asked for
// once per MMSI; a miss is final and a failure is retried only after a pause.
import test from 'node:test';
import assert from 'node:assert/strict';
import { createPhotos } from './photos.js';
const ANSWER = Object.freeze({
mmsi: '366999709',
photos: [
{
urls: {
mmsi: 'https://openvesselphotos.org/v1/mmsi/366999709/photos/1.jpg',
},
credit: 'Gordon Leggett',
licenceName: 'CC BY 4.0',
width: 1600,
height: 1200,
},
],
});
const settle = () => new Promise((resolve) => setImmediate(resolve));
function fixture(answer) {
const asked = [];
const source = {
getSnapshot() {},
async getEnrichment(query) {
asked.push(query);
return answer(query);
},
};
const photos = createPhotos({ vesselState: { _source: source } });
return { photos, asked };
}
test('a selected vessel is asked once and shows its checked photo', async () => {
const { photos, asked } = fixture(() => ANSWER);
const record = { id: 'v1', mmsi: '366999709' };
photos.requestVesselPhoto(record);
photos.requestVesselPhoto(record);
await settle();
photos.requestVesselPhoto(record);
assert.deepEqual(asked, [{ kind: 'photo', id: '366999709' }]);
assert.deepEqual(photos.vesselPhoto(record), {
src: 'https://openvesselphotos.org/v1/mmsi/366999709/photos/1.jpg?size=800',
width: 800,
height: 600,
photographer: 'Gordon Leggett',
licence: 'CC BY 4.0',
link: 'https://openvesselphotos.org/vessels/mmsi/366999709',
});
});
test('a vessel without a valid MMSI, or a source without lookups, is never asked', async () => {
const { photos, asked } = fixture(() => ANSWER);
photos.requestVesselPhoto({ id: 'v1', mmsi: '' });
photos.requestVesselPhoto({ id: 'v2', mmsi: '12345' });
await settle();
assert.equal(asked.length, 0);
const bare = createPhotos({ vesselState: { _source: { getSnapshot() {} } } });
bare.requestVesselPhoto({ id: 'v3', mmsi: '366999709' });
assert.equal(bare.vesselPhoto({ mmsi: '366999709' }), null);
});
test('a miss is final; a failure is asked again only after the pause', async () => {
let fail = true;
const { photos, asked } = fixture(({ id }) => {
if (id === '111111111') return { mmsi: id, photos: [] };
if (fail) throw new Error('down');
return ANSWER;
});
const missing = { mmsi: '111111111' };
const flaky = { mmsi: '366999709' };
photos.requestVesselPhoto(missing);
photos.requestVesselPhoto(flaky, 0);
await settle();
photos.requestVesselPhoto(missing);
photos.requestVesselPhoto(flaky, Date.now() + 1000);
assert.equal(asked.length, 2);
fail = false;
photos.requestVesselPhoto(flaky, Date.now() + 10 * 60 * 1000);
await settle();
assert.equal(asked.length, 3);
assert.equal(photos.vesselPhoto(missing), null);
assert.equal(photos.vesselPhoto(flaky).photographer, 'Gordon Leggett');
});
+1
View File
@@ -186,6 +186,7 @@ export function createSelection({
// click, not up to VISIBILITY_UPDATE_MS later.
components.rendering.updateVisibility(true);
components.cards.updateSelectedVesselHud(record);
components.photos.requestVesselPhoto(record);
if (registerSelectedContext(record)) {
selectEntityContext(record);
}
+2 -5
View File
@@ -64,12 +64,9 @@ async function standaloneStartup(Cesium, credentials, fetchImpl) {
document: {
getElementById: () => ({ querySelector: () => ({}) }),
},
resolveLocale: () => 'en',
setLocale() {},
getLocale: () => 'en',
onLocaleChange: () => () => {},
startPageLocale: () => 'en',
followPageLocale: () => () => {},
mountApplicationViews() {},
applyDocumentLanguage() {},
applyDocumentTranslations() {},
CITY_POIS: [],
createApplication: (options) => options,
+1
View File
@@ -16,4 +16,5 @@ export {
createFlightSource,
createMilitarySource,
createVesselSource,
fetchOpenVesselPhoto,
} from './standalone.js';
+38
View File
@@ -12,6 +12,11 @@ import {
} from './aircraft.js';
import { normalizeVesselTrack, vesselSnapshot } from './vessels.js';
import { parsePlanespottersPhoto } from '../../data/planespottersPhoto.js';
import {
MMSI,
openVesselPhotosUrl,
parseOpenVesselPhoto,
} from '../../data/openVesselPhoto.js';
const defaultFetch = (...args) => globalThis.fetch(...args);
const header = (response, name) => response.headers?.get?.(name);
@@ -42,6 +47,34 @@ async function planespottersPhoto(fetchImpl, hex, signal) {
return parsePlanespottersPhoto(payload);
}
/**
* A vessel's Open Vessel Photos photo, read and host-checked. The API is
* keyless and answers with `access-control-allow-origin: *`, so the browser
* asks it straight. An MMSI it does not know answers 404: no photo.
* @param {Function} fetchImpl fetch.
* @param {string} mmsi The vessel's nine-digit MMSI.
* @param {AbortSignal} [signal] Abort signal.
* @returns {Promise<object>} A `parseOpenVesselPhoto` result.
*/
export async function fetchOpenVesselPhoto(fetchImpl, mmsi, signal) {
const id = String(mmsi || '');
if (!MMSI.test(id))
throw new LiveSourceError('unsupported', 'Enrichment unavailable');
const timeout = AbortSignal.timeout(PHOTO_TIMEOUT_MS);
const { response, payload } = await readResponse(
fetchImpl,
openVesselPhotosUrl(id),
{
signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
credentials: 'omit',
},
'Open Vessel Photos',
);
if (response.status === 404) return parseOpenVesselPhoto(null);
if (!response.ok) throw httpError(response, 'Open Vessel Photos');
return parseOpenVesselPhoto(payload, id);
}
function openSkyError(response) {
const error = httpError(response, 'Flights');
const mode = String(
@@ -235,6 +268,11 @@ export function createVesselSource({
status: response.status,
};
},
async getEnrichment(query, { signal } = {}) {
if (query.kind !== 'photo')
throw new LiveSourceError('unsupported', 'Enrichment unavailable');
return fetchOpenVesselPhoto(fetchImpl, query.id, signal);
},
async getTrack(reference, { signal } = {}) {
const { response, payload } = await readResponse(
fetchImpl,
+5 -14
View File
@@ -6,13 +6,11 @@ import { createStandaloneScene } from './scene.js';
import { createStandaloneControls } from './controls.js';
import { createStandaloneData } from './data.js';
import { createStandaloneTools } from './tools.js';
import { resolveLocale, applyDocumentLanguage } from '../i18n/locale.js';
import {
applyDocumentTranslations,
getLocale,
onLocaleChange,
setLocale,
} from '../i18n/index.js';
followPageLocale,
startPageLocale,
} from '../i18n/page.js';
import { mountApplicationViews } from '../ui/views/index.js';
import { createGoogleTokenSource } from '../maps/googleTokens.js';
@@ -37,9 +35,7 @@ export function createStandaloneApplication({
// scripts execute after parsing, so the DOM is ready here: the views
// translate as they render, and the page's static data-i18n* markup (the
// loading screen) is translated here and after every language switch.
const activeLocale = resolveLocale();
setLocale(activeLocale);
applyDocumentLanguage(document, activeLocale);
startPageLocale(document);
// Views render the page's markup; wiring reads it.
mountApplicationViews(document);
applyDocumentTranslations(document);
@@ -50,12 +46,7 @@ export function createStandaloneApplication({
return createApplication({
createScene: async (context) => {
// A language switch applies in place; the page's own markup follows.
context.defer(
onLocaleChange(() => {
applyDocumentLanguage(document, getLocale());
applyDocumentTranslations(document);
}),
);
context.defer(followPageLocale(document));
placeSearch = createStandalonePlaceSearch({
// The bundled city and landmark data the offline name provider reads.
// The search package takes it as plain data rather than importing it,
+2 -2
View File
@@ -96,7 +96,7 @@ export class StyleManager extends ShellFacade {
* @param {Cesium.Viewer} viewer - The CesiumJS viewer instance.
* @param {object} [options]
* @param {boolean} [options.localePicker=true] - false removes the language
* picker, for a host that does not initialize Core's locale.
* picker, for a host that offers its own language choice.
*/
constructor(
viewer,
@@ -764,7 +764,7 @@ export class StyleManager extends ShellFacade {
this._lifetime.own(
onLocaleChange(() => nextTick(() => this._sizeDisplayLabelColumn())),
);
// A host that does not initialize Core's locale shows no picker.
// A host that offers its own language choice shows no picker.
if (this._localePickerEnabled === false) return;
this._publishLocalePicker();
}
+45
View File
@@ -1,6 +1,7 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { CctvControls } from './cctvControls.js';
import { CCTV_FRAME_DECODE_WAIT_MS } from './cctvFrames.js';
function element() {
const classes = new Set();
@@ -59,6 +60,50 @@ test('a late image completion cannot replace a newer camera preview', (t) => {
assert.equal(controls._frame.cameraId, 'b');
});
test('a camera frame settles once decoded, and a stale decode cannot land', async (t) => {
const { controls, requests } = fixture(t);
const decodes = [];
const queue = (src, id) => {
controls._queueCctvFrame(src, id, true);
const request = requests.at(-1);
request.decode = () =>
new Promise((resolve) => decodes.push({ src, resolve }));
return request;
};
const first = queue('first.jpg', 'a');
first.onload();
assert.equal(controls._frame.hasFrame, false);
const second = queue('second.jpg', 'b');
second.onload();
decodes[1].resolve();
await Promise.resolve();
decodes[0].resolve();
await Promise.resolve();
assert.equal(controls._frame.src, 'second.jpg');
assert.equal(controls._frame.cameraId, 'b');
assert.equal(controls._frame.hasFrame, true);
});
test('a loaded frame shows when its decode rejects or never settles', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
const { controls, requests } = fixture(t);
controls._queueCctvFrame('broken.jpg', 'a', true);
requests[0].decode = () => Promise.reject(new Error('EncodingError'));
requests[0].onload();
await Promise.resolve();
await Promise.resolve();
assert.equal(controls._frame.src, 'broken.jpg');
assert.equal(controls._frame.hasFrame, true);
controls._queueCctvFrame('hidden.jpg', 'b', true);
requests[1].decode = () => new Promise(() => {});
requests[1].onload();
assert.equal(controls._frame.hasFrame, false);
t.mock.timers.tick(CCTV_FRAME_DECODE_WAIT_MS);
assert.equal(controls._frame.src, 'hidden.jpg');
assert.equal(controls._frame.hasFrame, true);
});
test('failed refresh preserves settled pixels, but changing cameras clears them', (t) => {
const { controls, requests } = fixture(t);
controls._queueCctvFrame('first.jpg', 'a', true);
+25 -1
View File
@@ -77,6 +77,9 @@ export function cctvSourceLabelText(label) {
return SOURCE_LABELS[text] ? t(SOURCE_LABELS[text]) : text;
}
/** Longest wait for a loaded frame's decode before it is shown anyway. */
export const CCTV_FRAME_DECODE_WAIT_MS = 1000;
/** The preview before any frame: nothing requested, nothing shown. */
export const EMPTY_CCTV_FRAME = Object.freeze({
cameraId: '',
@@ -127,7 +130,28 @@ export function _queueCctvFrame(src, cameraId, cameraChanged) {
const preloader = new Image();
this._cctvFramePreloader = preloader;
preloader.onload = () => this._settleCctvFrame(token, src, true);
// Settle once the image is decoded, not merely loaded: the panel's <img>
// then paints the frame the moment it takes the src, instead of showing
// its empty box for the decode.
// A decode that rejects after a load still has drawable data, as it was
// before decoding was awaited. A decode that never settles (a hidden tab may
// hold it until the page draws) shows the loaded frame after
// CCTV_FRAME_DECODE_WAIT_MS rather than leaving the preview loading.
preloader.onload = () => {
if (typeof preloader.decode !== 'function') {
this._settleCctvFrame(token, src, true);
return;
}
let settled = false;
const settle = () => {
if (settled) return;
settled = true;
clearTimeout(timer);
this._settleCctvFrame(token, src, true);
};
const timer = setTimeout(settle, CCTV_FRAME_DECODE_WAIT_MS);
preloader.decode().then(settle, settle);
};
preloader.onerror = () => this._settleCctvFrame(token, src, false);
preloader.src = src;
}
+4 -1
View File
@@ -250,8 +250,11 @@ html:not([lang='en']) .cctv-controls .scene-btn {
height: auto;
object-fit: contain;
display: block;
/* No fade: a camera change hides the old frame at once (never its pixels
under the new camera) and shows the new one as soon as it is decoded. A
180 ms fade-in after every arriving frame made each camera click linger
on black. */
opacity: 0;
transition: opacity 180ms ease;
}
#cctv-video {