Compare commits

..
Author SHA1 Message Date
Claude afdecfbd6d docs(changelog): add fragment for #1883
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DLPqdcmfWbcfzrXmBKZc5z
2026-11-20 17:54:52 +00:00
Claude 4cded65064 fix(satellites): stop requesting the CelesTrak sar group, which does not exist
The core catalog asked CelesTrak for GROUP=sar on every update. CelesTrak
has no such group (sarsat is search and rescue), so that read failed each
time and the layer row read DEGRADED with "1 CelesTrak group unavailable"
even when every real group loaded. Each failed read also put the TLE feed
into a 60 s cooldown.

Drop sar from the catalog groups, the client allowlist, the proxy
allowlist and the group-to-class table.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DLPqdcmfWbcfzrXmBKZc5z
2026-11-20 17:54:30 +00:00
German Khokhlov 41c792208e Merge pull request #1543 from Byrd-IT/byrdit/cctv-visible-only-fetch
perf(cctv): fetch the active camera's pictures only while they can be seen
2026-11-20 19:42:08 +04:00
German Khokhlov b94e556693 Merge branch 'main' into byrdit/cctv-visible-only-fetch 2026-11-20 19:26:40 +04:00
German Khokhlov 20647f6549 Merge origin/main into byrdit/cctv-visible-only-fetch
# Conflicts:
#	src/layers/cctv/frames.test.mjs
2026-11-20 17:33:48 +04:00
German Khokhlov 2c5f9f89f7 fix(cctv): keep the camera card's bigger view refreshing
An open bigger view now counts as a viewer of the camera's still, so it
keeps refreshing after the layout turns phone and the Cameras sheet is
not the one open. The card releases it in the watcher's cleanup, which
also runs when the card unmounts in the same tick the popup closes.
2026-11-20 03:35:32 +04:00
German Khokhlov d19ae89630 Merge origin/main into byrdit/cctv-visible-only-fetch 2026-11-19 18:33:29 +04:00
German Khokhlov 99a70a0e0c fix(cctv): keep the Context camera card's still and tidy the visibility port
The still preview gate looked only at the CCTV panel, so the Context
camera card, which reads the same frame, stopped updating while the
panel was collapsed or another phone sheet was open. A mounted card now
counts itself in the CCTV store, and the still is requested while the
panel or a card is shown; live video still follows the panel only.

Review follow-ups in the same area:
- visiblePoints is registered once, in createCesiumPorts, and drops
  checks for input that cannot happen; the contract documents
  horizonMarginM and when it answers false or null.
- The layer passes the mount and the four corners once each and asks
  findCamera for the port.
- Phone sheet names come from a shared module instead of literals.
- Layer tests cover the fetch gate; the geometry cases moved to the
  camera port tests. Comments and CURRENT-STATE match the code.
2026-11-19 18:28:51 +04:00
brandonabyrd b020a1cd91 docs: describe camera point visibility capability 2026-11-18 17:13:06 -06:00
brandonabyrd 28007e20ef fix(cctv): register camera point visibility capability 2026-11-18 17:13:06 -06:00
brandonabyrd 02c60c0a20 fix(cctv): fail open before projection geometry exists 2026-11-18 17:13:06 -06:00
brandonabyrd b98b9d390f fix(cctv): reuse renderer visibility scratch state 2026-11-18 17:13:06 -06:00
brandonabyrd c0752784d2 fix(cctv): cull frames through renderer camera port 2026-11-18 17:13:06 -06:00
Byrd-IT 147d1f5e4e docs: CURRENT-STATE describes the 200 m horizon margin and the phone Cameras sheet rule (#1543) 2026-11-18 17:13:06 -06:00
brandonabyrd 5887235894 docs(cctv): describe conservative horizon geometry 2026-11-18 17:13:06 -06:00
brandonabyrd 564383e4b5 fix(cctv): retain far-side culling below ellipsoid 2026-11-18 17:13:06 -06:00
brandonabyrd b1b66e9717 fix(cctv): keep below-ellipsoid planes refreshing 2026-11-18 17:13:06 -06:00
Byrd-IT 9a3fc84935 fix(cctv): address review of #1543 (horizon test, resume guard, no per-frame allocation, mobile sheet)
- frames.test: viewerAt uses Cesium's default far (5e8) so the below-horizon
  test fails without occluder.isPointVisible
- cctvControls: install the resume observer for a still-only panel too
- cctvPresentation: panelShown also requires the Cameras sheet on phones;
  the observer watches body class/data-mobile-sheet
- frames.projectionInView: shared horizonOccluder + scratch sphere/array
2026-11-18 17:13:06 -06:00
Byrd-IT 0151c178a4 docs: changelog fragment for #1543 2026-11-18 17:13:06 -06:00
Byrd-IT 3bda877a8a perf(cctv): fetch the active camera's pictures only while they can be seen 2026-11-18 17:13:06 -06:00
56 changed files with 961 additions and 490 deletions

No files matched your search

-3
View File
@@ -205,9 +205,6 @@ AISSTREAM_API_KEY=
# Traffic Flow & Incidents tile requests per MONTH, not per day; no credit card
# required. Get a key at https://my.tomtom.com/keys). SERVER-SIDE ONLY:
# the browser fetches same-origin /api/tomtom/* and never sees the key.
# The key needs a traffic product assigned at my.tomtom.com: either the
# TomTom Maps Traffic API or the Orbis Maps one works (the proxy tries the
# first and falls back to Orbis on HTTP 403).
# Keyless fallback: the traffic layer runs its built-in simulation (white dots,
# hardcoded per-road-class speeds) — no key required for the layer to work.
# TOMTOM_API_KEY=
+1 -1
View File
@@ -281,7 +281,7 @@ The optional Local ADS-B layer and the broadcast-FM receiver use radio you recei
- **Radio country coverage (optional).** Set `RADIO_PRIORITY_COUNTRIES=IN,PL` in the local `.env` and restart to include stations beyond the global click charts. The operator may choose up to eight unique ISO alpha-2 country codes; no key is needed. Each country adds one bounded query (at most 200 rows) and reserves up to 40 unique, usable stations inside the existing 750-station catalog. Country seeds precede specialist-tag seeds and global popularity fill; unused slots return to the shared pool. This is a coverage preference, not an exhaustive national directory or a guarantee of stations in every city. Countries with no eligible HTTPS MP3/AAC geolocated stations remain empty. An unset list preserves global selection. Country requests share the directory cache and three-worker pool; failed country queries are reported in coverage without blocking a healthy global refresh. Failed/degraded refreshes back off for one minute, with at most three mirrors per query.
- **Radio Browser.** In every installation, including when `RADIO_PRIORITY_COUNTRIES` is unset, each request tries at most three mirror candidates (later fallback candidates are skipped), and failed or partial catalog refreshes back off for 60 seconds. A cold-start failure therefore continues returning 503 during that delay even if upstream recovers. `/api/radio/stations` discovers official API mirrors, makes bounded and coalesced healthy/geolocated HTTPS-station queries, caches the normalized public-domain directory for 45 minutes, and may serve the last good catalog for up to seven days during an outage. Refreshes must meet minimum accepted-query and station coverage before replacing a warm catalog; broad/specialist responses whose rows all fail the product's health policy do not count as successful queries. Optional priority-country outcomes are advisory: valid, in-limit responses with no eligible stations succeed as empty results, while failed or malformed country queries report unsuccessful coverage without degrading the global catalog. A usable partial cold catalog is explicitly `DEGRADED`, and non-array or empty broad/specialist payloads are rejected atomically. Individual structurally malformed rows are skipped rather than failing the whole query; the response carries their bounded `rejectedStationCount` (at most 10,000), which the client adds to its own rejected rows and reports as degraded coverage without discarding the accepted generation. Every directory and click-count request rejects redirects, validates all resolved addresses as globally routable (including reserved/documentation IPv4 and special/non-global IPv6 exclusions), and pins the TLS connection to a validated address. Only MP3/AAC non-HLS directory rows with public HTTPS stream targets are returned; favicons are intentionally omitted. Pressing play connects one browser audio element directly to the selected broadcaster and calls the directory's click counter through known-ID-only `POST /api/radio/click/:uuid`. GEV never proxies, caches, records, bundles, or redistributes audio. Radio Browser supplies station-level tags, not dependable current-song or upcoming-program metadata, so Radio filtering never claims either. Direct playback exposes the listener's IP address to the broadcaster, whose own stream terms apply.
- **TomTom Traffic.** Optional and BYOK: without `TOMTOM_API_KEY` the traffic layer runs its built-in simulation and no TomTom data (or attribution) appears. With a key, flow vector tiles are fetched through the server-side `/api/tomtom` proxy (from the TomTom Maps Traffic API, or the TomTom Orbis Maps Traffic API when the key is only assigned that product; 120 s cache + a daily tile-budget governor — `TOMTOM_DAILY_TILE_BUDGET`, default 6,000 — sized so a 31-day month stays inside TomTom's 200K monthly free allowance; still a configurable application safety ceiling, not a guarantee; TomTom's [current pricing](https://docs.tomtom.com/pricing/) lists 200K free tile requests per month) and the "Traffic flow data © TomTom" credit is registered in the Data attribution popover the moment live mode activates. TomTom data is served live and cached only transiently (≤120 s TTL under `.gev-cache/`, gitignored) — it is not bundled or redistributed. One 23 KB point-in-time tile snapshot is committed as a decode-test fixture (`src/data/fixtures/`, © TomTom, never served to the app).
- **TomTom Traffic.** Optional and BYOK: without `TOMTOM_API_KEY` the traffic layer runs its built-in simulation and no TomTom data (or attribution) appears. With a key, flow vector tiles are fetched through the server-side `/api/tomtom` proxy (120 s cache + a daily tile-budget governor — `TOMTOM_DAILY_TILE_BUDGET`, default 6,000 — sized so a 31-day month stays inside TomTom's 200K monthly free allowance; still a configurable application safety ceiling, not a guarantee; TomTom's [current pricing](https://docs.tomtom.com/pricing/) lists 200K free tile requests per month) and the "Traffic flow data © TomTom" credit is registered in the Data attribution popover the moment live mode activates. TomTom data is served live and cached only transiently (≤120 s TTL under `.gev-cache/`, gitignored) — it is not bundled or redistributed. One 23 KB point-in-time tile snapshot is committed as a decode-test fixture (`src/data/fixtures/`, © TomTom, never served to the app).
- **Routing (OSRM / FOSSGIS).** `/api/route` proxies the public OSRM instances FOSSGIS e.V. runs for the OpenStreetMap community (car, bike, foot profiles). They are keyless and intended for fair, interactive use — the proxy rate-limits clients (60/min, 200/min total), caps route span and response size, caches each route for 10 minutes, and identifies itself in the User-Agent. Heavy or automated use must run its own OSRM. Routes are computed from OpenStreetMap data (ODbL); the Directions layer and voice routes never redistribute them. A route the router cannot find is reported as such; the Directions layer draws nothing in that case, and voice routes fall back to a clearly labeled straight line.
- **Re:Earth Terrain.** Keyless (no API key). Used two ways: (1) `src/mapStackController.js` swaps in a `Cesium.CesiumTerrainProvider` pointed at Re:Earth's `cesium-mesh/ellipsoid` quantized-mesh endpoint for globe stacks without a Cesium ion token (e.g. OSM), replacing a flat `EllipsoidTerrainProvider`; falls back to the flat provider if the endpoint can't be reached. (2) The server-side `/api/terrain/heights` proxy (disk-cached, serve-stale) resolves per-point ellipsoidal ground height for entity placement. Both are best-effort with a keyless-safe fallback (bundled EGM96 geoid math) if Re:Earth is unreachable.
- **OSRM on the FOSSGIS routing servers.** Keyless (no API key). Every route is requested by a person: clicking A and B in the Directions layer, or a voice "route from A to B". The server-side `/api/route` proxy sends an identifying `User-Agent`, pins the upstream host, accepts 2-12 coordinates, rejects any leg over 600 km or a total over 2,500 km, caps the buffered response at 8 MB, times the upstream out at 12 s, rate-limits per client, caches each route for 10 minutes, and coalesces identical requests that are in flight at the same time. Turn-by-turn maneuvers are asked for only when a caller wants them (`steps=1`), so the callers that do not read them send the smaller request. The "fix the map" link the policy asks for is in the Data attribution popover beside the OpenStreetMap credit.
@@ -0,0 +1,4 @@
- Stop fetching the active CCTV camera's pictures when nobody can see them. The
monitor plane skips its 10 s still while it is off screen or below the
horizon, and the still preview waits for a visible tab and an open panel or
Context camera card (on phones, the open Cameras or Context sheet) (Byrd-IT, #1543).
@@ -1,5 +0,0 @@
- Live traffic works with TomTom keys that are only assigned the Orbis Maps
traffic product: when TomTom refuses the key on the TomTom Maps flow tile
endpoint (HTTP 403), the proxy uses the Orbis one and keeps it. A key both
endpoints refuse now reads "TomTom key rejected" instead of "TomTom upstream
unreachable", and stops spending the daily tile budget on retries (#1809).
@@ -0,0 +1,3 @@
- Stop the Satellites layer row reading `DEGRADED` with "1 CelesTrak group
unavailable" on every update: the core catalog asked CelesTrak for a `sar`
group that does not exist, so that read always failed (asturksever, #1883).
+11 -9
View File
@@ -2087,6 +2087,16 @@ already shows, so the list cannot pick that camera: FOCUS does, and so does
NEAREST when that camera is the nearest. Closing the list without a choice
keeps automatic selection.
The active camera's pictures follow what can be seen. The monitor plane skips
its 10 s still while the renderer reports it off screen or below the horizon,
and fetches on the first refresh tick after it is back. Activating or
calibrating a camera bypasses visibility and the usual refresh interval, but
still waits for an in-flight request and the provider's minimum interval.
The panel's still and live video run only while the tab is visible and the
panel is open (on phones, the Cameras sheet). The still also loads while
Context shows the camera's card (on phones, the Context sheet) or its bigger
view is open.
Traffic owns its rendered-surface observer only while enabled, removes it on disable/destroy, and rebuilds no cached heights on frames where the surface identity is unchanged. Its dots and heat-lines are two renderer draw sets, it animates on the frame port's preRender, and it follows the camera through the camera port at its own 5% threshold rather than the shared `percentageChanged` ledger. The surface identity is the globe port's `surfaceVersion()` and tile readiness its `isSettled('surface')`, so the layer no longer reaches Cesium. Heat-lines are always asked for draped: where the Cesium renderer cannot drape (no depth textures) its draw port draws them (and every other draped line) over the surface, in their colour where the surface hides them and hidden past the horizon, recolouring a line in place when only its colour changes, rather than the layer dropping them.
Traffic and bikeshare expose factories through `./layers/traffic` and
@@ -4027,14 +4037,6 @@ The TomTom `/api/tomtom/*` routes run the shared same-site admission gate before
status, cache or upstream work, refusing cross-site browser requests while
preserving same-origin app requests and non-browser local callers. The browser
layers and their rendering remain in their existing modules.
The proxy asks the TomTom Maps flow endpoint (`traffic/map/4/tile/flow/relative`)
first. On HTTP 403, which TomTom answers when a key is not assigned that
product, it asks the Orbis Maps one (`maps/orbis/traffic/flow/vector/tile`,
`apiVersion=2`) and keeps whichever answered until the key changes or the
process restarts; `flowDecode.js` reads both tile schemas into one segment
shape. When both refuse the key, tiles answer `403 {error:'key_rejected'}`
(shown as "TomTom key rejected"), `/api/tomtom/status` reports
`keyRejected: true`, and upstream is left alone for five minutes.
Past the daily tile budget, or while TomTom fails, the proxy answers with its
last copy of a tile (`x-tomtom-cache: STALE-BUDGET` / `STALE-ERROR`) however old
it is, and every tile carries `x-tomtom-fetched-at`, the proxy fetch time
@@ -7801,7 +7803,7 @@ silently demoting every later lookup for the session.
- **Satellite classes** (`src/layers/satellites/classes.js`): every satellite is filed under one of six classes, each with its own point colour, legend swatch and toggle: STATIONS (warm white), IMAGING (cyan), TELECOM (violet; communications and navigation, so GPS, GLONASS, Galileo and BeiDou read as one family), STARLINK (dim slate), PROBES (muted blue-gray) and DEBRIS (receding brown-gray). That module is the single source of truth for class, label and colour, so the dot, the card and the legend swatch cannot disagree. Two deliberate palette rules: no class may sit in the 40–48° amber band, which is the app-wide known-military convention; and STARLINK stays far below PROBES in Rec.601 luminance so the dense shell stays separable when NVG/FLIR collapse the scene to one channel. The ISS keeps its long-standing red hero dot rather than the STATIONS colour — it carries a permanent name label and its card still reads `STATIONS · ISS`; it is a station whichever group ingested it, so a stations-feed outage cannot refile it. `src/data/satelliteClass.js` keeps the group-based labels beneath the classes: the constellation subtype and a group's own label for a satellite with no class. The tracked satellite's dot keeps that colour too: tracking draws it larger (14 px), white-outlined and over everything, never in another colour (`_addTrackedEntity`, `src/layers/satellites/rendering.js`).
- Class is also a **text field**, not just a color: `TELECOM · GPS` / `STARLINK` / `STATIONS · ISS` leads the tracked card's detail block and replaces the raw CelesTrak tag on the detection-overlay label. Because that canvas composites above the post-FX chain, the class stays readable in NVG/FLIR after the in-scene dot colors are flattened.
- The satellites row in DATA LAYERS carries per-layer sub-controls (`DataLayerManager._syncRowControls`, the first consumer of the optional `getRowControls()` layer hook): one chip per class (the STARLINK chip exposes the existing `catalog` param), a swatch legend with live per-class counts, and an info line while SATCAT is stale or unavailable (`Classes may lag: SATCAT is a cached copy` / `Classes may lag: SATCAT unavailable`). Default is the sparse core catalog. The chips are stateless — each declares the params to apply and the manager owns the write — so the Space Missions capture/restore path over the same param stays authoritative. Controls stay hidden while the layer is off. An explicit CORE or DENSE choice participates in versioned local and share-link state; temporary Space Missions overrides do not.
- **Class toggles** (`src/layers/satellites/classes.js`): the layer row carries one chip per class — STATIONS, IMAGING, TELECOM (communications and navigation), PROBES (science, technology development and demonstration, unknown purpose) and DEBRIS (rocket bodies, fragments, unknown objects launched before last year and dead payloads) on by default, so the layer shows what it did before classes; STARLINK off, as DENSE was. Points of a hidden class stay built and are only hidden, so a toggle needs no reload; hidden classes are left out of the detection overlay, the voice/framing position lists and analyst answers (the tracked satellite still answers), and the legend keys only the classes on screen. The class comes, strongest evidence first, from CelesTrak SATCAT (object type and operational status, fetched per group through `/api/celestrak-satcat/<group>`, cached a day by the proxy; the layer keeps a current read six hours rather than asking on every five-minute update), the bundled UCS Satellite Database pack (UCS-Satellite-Database 5-1-2023: operator, owner country and purpose; `src/data/local_data/ucs_satellites/`), name patterns for satellites launched after May 2023, and finally the CelesTrak groups the TLE came in (a mission group such as `weather` before the orbit group `geo`; a UCS purpose of "Unknown" counts as none). Only crewed stations and the craft that visit them, by name, are STATIONS: the CubeSats CelesTrak's stations group also carries after their deployment from the ISS are classed like any other satellite. A payload whose SATCAT record gives no status, with no UCS record and no recognisable name, that launched 20 or more years ago (SATCAT's launch date, else the TLE designator's year) is presumed dead and filed as debris; without a SATCAT record (a failed read) nothing is presumed. To cover imaging launched after the UCS snapshot the core catalog also reads CelesTrak's `resource`, `weather`, `planet`, `sar` and `science` groups. Debris can be tracked but is never ridden: the orbital entry gate (`orbitEntryAllowed`) refuses it, so no ORBIT entry is offered and double-click does nothing for it. Retired stations and the shuttles have re-entered and have no orbit to show. An explicit class choice is kept in local and share-link state as the `classes` option, one letter per class shown (`sitpd`: stations, imaging, telecom, probes, debris; `0`: none; `src/data/satelliteClassMask.js`), and the layer takes those letters back through `setParams({classes})`; STARLINK maps to the existing `catalog: 'dense'` param instead.
- **Class toggles** (`src/layers/satellites/classes.js`): the layer row carries one chip per class — STATIONS, IMAGING, TELECOM (communications and navigation), PROBES (science, technology development and demonstration, unknown purpose) and DEBRIS (rocket bodies, fragments, unknown objects launched before last year and dead payloads) on by default, so the layer shows what it did before classes; STARLINK off, as DENSE was. Points of a hidden class stay built and are only hidden, so a toggle needs no reload; hidden classes are left out of the detection overlay, the voice/framing position lists and analyst answers (the tracked satellite still answers), and the legend keys only the classes on screen. The class comes, strongest evidence first, from CelesTrak SATCAT (object type and operational status, fetched per group through `/api/celestrak-satcat/<group>`, cached a day by the proxy; the layer keeps a current read six hours rather than asking on every five-minute update), the bundled UCS Satellite Database pack (UCS-Satellite-Database 5-1-2023: operator, owner country and purpose; `src/data/local_data/ucs_satellites/`), name patterns for satellites launched after May 2023, and finally the CelesTrak groups the TLE came in (a mission group such as `weather` before the orbit group `geo`; a UCS purpose of "Unknown" counts as none). Only crewed stations and the craft that visit them, by name, are STATIONS: the CubeSats CelesTrak's stations group also carries after their deployment from the ISS are classed like any other satellite. A payload whose SATCAT record gives no status, with no UCS record and no recognisable name, that launched 20 or more years ago (SATCAT's launch date, else the TLE designator's year) is presumed dead and filed as debris; without a SATCAT record (a failed read) nothing is presumed. To cover imaging launched after the UCS snapshot the core catalog also reads CelesTrak's `resource`, `weather`, `planet` and `science` groups. Debris can be tracked but is never ridden: the orbital entry gate (`orbitEntryAllowed`) refuses it, so no ORBIT entry is offered and double-click does nothing for it. Retired stations and the shuttles have re-entered and have no orbit to show. An explicit class choice is kept in local and share-link state as the `classes` option, one letter per class shown (`sitpd`: stations, imaging, telecom, probes, debris; `0`: none; `src/data/satelliteClassMask.js`), and the layer takes those letters back through `setParams({classes})`; STARLINK maps to the existing `catalog: 'dense'` param instead.
- The satellite Cockpit subject (`getCockpitSubject()`) also carries `satelliteClass`, `cosparId` (from SATCAT, else TLE line 1), `tle` (`{line1, line2, epochMs}`), `owner` (`{countryCode, label}`: ISO 3166-1 alpha-2 for a single country, `null` code for organisations such as ESA, EUMETSAT or Intelsat and for joint owners) and `operator` (UCS; SpaceX for Starlink). UCS names the operator's country and wins over the SATCAT owner code; CelesTrak's CIS (former USSR) is filed under Russia.
- **The STARLINK chip (formerly DENSE) reports the dense LOAD, not the catalog param.** The param flips synchronously while the Starlink shell takes seconds to arrive over a chunked load, and CelesTrak 502s that feed regularly. So the chip reads `STARLINK ···` (busy, disabled) while loading, ACTIVE only once dense points are actually on screen, and `STARLINK ✕` with the reason on hover when the load fails — a failure also reverts `catalog` to `core`, drops any partial chunk, and leaves the chip clickable to retry. A load is judged by points added, not by HTTP status: a 200 carrying an empty body, a passed-through HTML error page, or only TLEs the core catalog already owns fails with the same revert semantics as a 502. Any explicit request for `core` clears a latched error even when the mode does not change, so a Space Missions restore of an already-core snapshot never leaves the user with a failure they did not cause. Because the load settles asynchronously, the layer pushes a re-render through the optional `setRowControlsListener()` hook; nothing else would repaint that row before the 5-minute catalog refresh, so the count and legend would otherwise sit stale.
- **A dependency owner takes the row with it.** Space Missions borrows this layer for TLE lookup with `showPoints:false`; while points are hidden the layer returns empty row controls, so the legend never describes an empty sky and the chip cannot accept a write that the owner's restore would silently revert.
+7
View File
@@ -81,6 +81,13 @@ optional:
target's east-north-up frame, or the identity. `setView` keeps that frame
while it places a world pose. A share link's follow offset is
re-expressed in it, satellites included.
- `camera.visiblePoints(points, horizonMarginM)` (capability `pointVisibility`)
is whether any of the points may be on screen: `false` only when their
bounding sphere is outside the view or all of them are below the horizon
of the WGS84 ellipsoid shrunk by `horizonMarginM` metres; `null` when it
cannot tell (not a 3D scene, an empty point set, or a non-finite point or
camera vector), and callers count that as visible. Supply a finite,
nonnegative margin smaller than the shortest WGS84 radius.
- `globe.surfaceVersion()` (capability `surfaceIdentity`) is a number that
changes whenever what surface heights answer against changes (base,
terrain or photoreal route swapped, the globe shown or hidden) and never
-1
View File
@@ -1214,7 +1214,6 @@
"src/sources/militaryTileGeometry.test.mjs",
"src/layers/traffic/surface.test.mjs",
"src/layers/traffic/roadModes.test.mjs",
"src/layers/traffic/flowDecode.test.mjs",
"scripts/qa-traffic-motion.mjs",
"src/layers/traffic/motion.test.mjs",
"scripts/qa-journey-recorder.mjs",
+3
View File
@@ -1103,6 +1103,7 @@
"src/ui/cctv.js",
"src/ui/cctvBindings.js",
"src/ui/cctvCalibration.js",
"src/ui/mobileSheets.js",
"src/ui/cctvControls.js",
"src/ui/cctvFrames.js",
"src/ui/cctvVideo.js",
@@ -1343,6 +1344,7 @@
"src/data/distanceFormat.js",
"src/i18n/marker.js",
"src/ui/mobileShell.js",
"src/ui/mobileSheets.js",
"src/exclusiveSurfaces.js",
"src/ui/placeNames.js",
"src/hudLayouts.js",
@@ -4795,6 +4797,7 @@
"src/ui/applicationShell.js",
"src/ui/railEdgeScroll.js",
"src/ui/mobileShell.js",
"src/ui/mobileSheets.js",
"src/ui/localePicker.js",
"src/ui/cyberSonarControls.js",
"src/ui/locationNavigation.js",
-1
View File
@@ -49,7 +49,6 @@ export function celestrakProxy() {
'resource',
'weather',
'planet',
'sar',
'science',
];
const feeds = [
+7 -99
View File
@@ -18,18 +18,6 @@ import { admitSameSite } from './common/same-site.js';
* "Traffic flow"). The key comes from TOMTOM_API_KEY server-side only — the
* browser fetches same-origin `/api/tomtom/flow/{z}/{x}/{y}.pbf`.
*
* Orbis fallback: TomTom keys are assigned products, and a key without the
* TomTom Maps traffic product gets 403 on the endpoint above while the same
* key works on the TomTom Orbis Maps one,
* https://api.tomtom.com/maps/orbis/traffic/flow/vector/tile/{z}/{x}/{y}?apiVersion=2
* (same "Traffic flow" layer; `relative_speed` and `road_category` replace
* `traffic_level` and `road_type`, which the client decoder reads either
* way). On 403 the proxy asks the other endpoint and keeps whichever
* answered for the rest of the process. When both refuse the key, tiles
* answer 403 {error:'key_rejected'} and upstream is left alone for
* KEY_REJECTED_TTL_MS, so a rejected key does not spend the daily budget one
* tile at a time. Changing the key clears both.
*
* Cache: memory + disk (.gev-cache/tomtom/), TTL 120 s (traffic is fresh
* data), single-flight per tile, serve-stale-on-failure — the celestrakProxy
* pattern. Cache hits never count against the budget.
@@ -55,7 +43,7 @@ import { admitSameSite } from './common/same-site.js';
* at distinct tiles, spend the TomTom quota and leave the traffic layer on
* 429 budget for the rest of the UTC day.
*
* GET /api/tomtom/status → {hasKey, keyRejected, dailyCount, budget, date}. Keyless mode:
* GET /api/tomtom/status → {hasKey, dailyCount, budget, date}. Keyless mode:
* status reports hasKey:false and the tile endpoint 503s {error:'no_key'}
* without touching upstream — the traffic layer then stays in simulation mode.
*
@@ -71,37 +59,6 @@ export function tomtomProxy() {
const UPSTREAM_TIMEOUT_MS = 15000;
/** Flow tiles are well under 1 MB; this bounds a runaway body, not a budget. */
const TOMTOM_TILE_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
/** How long a key both endpoints refused is left alone before a retry. */
const KEY_REJECTED_TTL_MS = 5 * 60_000;
/** Upstream flow-tile endpoints, in the order a new key is tried. */
const ENDPOINTS = {
legacy: (z, x, y, key) => ({
url:
'https://api.tomtom.com/traffic/map/4/tile/flow/relative/' +
`${z}/${x}/${y}.pbf?key=${encodeURIComponent(key)}`,
}),
orbis: (z, x, y, key) => ({
url:
'https://api.tomtom.com/maps/orbis/traffic/flow/vector/tile/' +
`${z}/${x}/${y}?apiVersion=2`,
headers: { 'TomTom-Api-Key': key },
}),
};
/**
* What is known about the configured key: the endpoint that last served
* it, and until when both endpoints are known to refuse it. Reset when the
* key changes (Provider Settings rewrites process.env at runtime).
* @type {{key:string, endpoint:'legacy'|'orbis', rejectedUntil:number}}
*/
let keyState = { key: '', endpoint: 'legacy', rejectedUntil: 0 };
function currentKeyState() {
const key = process.env.TOMTOM_API_KEY || '';
if (keyState.key !== key)
keyState = { key, endpoint: 'legacy', rejectedUntil: 0 };
return keyState;
}
const isKeyRejected = () => Date.now() < currentKeyState().rejectedUntil;
/** @type {Map<string, {at:number, buf:Buffer}>} tile key `z/x/y` -> cached tile (kept past TTL for serve-stale). */
const mem = new Map();
@@ -192,17 +149,14 @@ export function tomtomProxy() {
mem.set(key, entry);
}
async function fetchEndpoint(name, z, x, y, key) {
const { url, headers } = ENDPOINTS[name](z, x, y, key);
async function fetchUpstream(z, x, y) {
const url =
'https://api.tomtom.com/traffic/map/4/tile/flow/relative/' +
`${z}/${x}/${y}.pbf?key=${encodeURIComponent(process.env.TOMTOM_API_KEY)}`;
recordUpstreamFetch(); // attempts count — upstream bills the request either way
const signal = AbortSignal.timeout(UPSTREAM_TIMEOUT_MS);
const res = await fetch(url, { signal, ...(headers ? { headers } : {}) });
if (!res.ok) {
await res.body?.cancel().catch(() => {});
throw Object.assign(new Error(`HTTP ${res.status}`), {
status: res.status,
});
}
const res = await fetch(url, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const bytes = await readResponseBytesCapped(
res,
TOMTOM_TILE_MAX_RESPONSE_BYTES,
@@ -213,41 +167,6 @@ export function tomtomProxy() {
return buf;
}
/**
* Fetch one tile from the endpoint this key last worked on, asking the
* other one only when TomTom refuses the key (403). Both refusing marks
* the key rejected; any other failure is an ordinary upstream error.
*/
async function fetchUpstream(z, x, y) {
const state = currentKeyState();
const other = state.endpoint === 'legacy' ? 'orbis' : 'legacy';
try {
return await fetchEndpoint(state.endpoint, z, x, y, state.key);
} catch (err) {
if (err?.status !== 403) throw err;
}
try {
const buf = await fetchEndpoint(other, z, x, y, state.key);
if (keyState === state) {
state.endpoint = other;
console.warn(
`[tomtom-proxy] key refused on the ${other === 'orbis' ? 'TomTom Maps' : 'Orbis'} flow endpoint (HTTP 403); using the ${other === 'orbis' ? 'Orbis' : 'TomTom Maps'} one`,
);
}
return buf;
} catch (err) {
if (err?.status !== 403) throw err;
if (keyState === state)
state.rejectedUntil = Date.now() + KEY_REJECTED_TTL_MS;
throw Object.assign(
new Error(
'HTTP 403 on both flow endpoints: check the products assigned to the key and its domain whitelist at https://my.tomtom.com/keys',
),
{ status: 403 },
);
}
}
const installMiddleware = (server) => {
server.middlewares.use('/api/tomtom', async (req, res) => {
// Gate first: a cross-site <img>/fetch must not reach the budget counter.
@@ -285,7 +204,6 @@ export function tomtomProxy() {
const b = currentBudget();
sendJson(200, {
hasKey,
keyRejected: hasKey && isKeyRejected(),
dailyCount: b.count,
budget: dailyBudgetLimit(),
date: b.date,
@@ -324,14 +242,6 @@ export function tomtomProxy() {
return;
}
// TomTom refused the key on both endpoints: asking again per tile
// would only spend the budget. Last-good data still beats nothing.
if (isKeyRejected()) {
if (entry) sendTile(entry, 'STALE-ERROR');
else sendJson(403, { error: 'key_rejected' });
return;
}
// Budget governor: over the soft cap, last-good data beats a dead layer.
if (isTomTomOverBudget(currentBudget(), dailyBudgetLimit())) {
if (entry) {
@@ -367,8 +277,6 @@ export function tomtomProxy() {
sendTile(fresh, 'MISS');
} else if (entry) {
sendTile(entry, 'STALE-ERROR'); // upstream down — stale beats empty
} else if (isKeyRejected()) {
sendJson(403, { error: 'key_rejected' });
} else {
sendJson(502, { error: 'upstream' });
}
-3
View File
@@ -46,9 +46,6 @@ test('hosted account limits and service failures name their own reason', () => {
assert.equal(failure(429, 'budget'), 'TomTom daily budget reached');
assert.equal(failure(503, 'no_key'), 'TomTom key unavailable');
assert.equal(failure(503, null), 'TomTom key unavailable');
// TomTom refused the key itself: not the generic HTTP 403 line.
assert.equal(failure(403, 'key_rejected'), 'TomTom key rejected');
assert.equal(failure(403, null), 'TomTom flow error (HTTP 403)');
assert.equal(
failure(503, 'USAGE_UNAVAILABLE'),
'Traffic service unavailable',
-1
View File
@@ -1983,7 +1983,6 @@
"Moving dots colored by live flow": "نقاط متحركة ملوّنة حسب التدفق المباشر",
"Moving dots": "نقاط متحركة",
"TomTom key unavailable": "مفتاح TomTom غير متاح",
"TomTom key rejected": "تم رفض مفتاح TomTom",
"TomTom daily budget reached": "بلغت الحصة اليومية لـ TomTom",
"Monthly traffic allowance used": "تم استهلاك حصة حركة المرور الشهرية",
"Traffic rate limit reached": "تم بلوغ حد طلبات حركة المرور",
-1
View File
@@ -1860,7 +1860,6 @@
"Moving dots colored by live flow": "Bewegte Punkte nach Live-Verkehrsfluss gefärbt",
"Moving dots": "Bewegte Punkte",
"TomTom key unavailable": "TomTom-Schlüssel nicht verfügbar",
"TomTom key rejected": "TomTom-Schlüssel abgelehnt",
"TomTom daily budget reached": "TomTom-Tagesbudget erreicht",
"Monthly traffic allowance used": "Monatliches Verkehrskontingent aufgebraucht",
"Traffic rate limit reached": "Verkehrs-Anfragelimit erreicht",
-1
View File
@@ -2463,7 +2463,6 @@
"Military area": "Zona militar",
"SIMULATED — {reason}": "SIMULADO — {reason}",
"TomTom key unavailable": "Clave de TomTom no disponible",
"TomTom key rejected": "Clave de TomTom rechazada",
"TomTom daily budget reached": "Se alcanzó el límite diario de TomTom",
"Monthly traffic allowance used": "Cupo mensual de tráfico agotado",
"Traffic rate limit reached": "Límite de peticiones de tráfico alcanzado",
-1
View File
@@ -1247,7 +1247,6 @@
"Moving dots colored by live flow": "Points mobiles colorés selon le trafic en direct",
"Moving dots": "Points mobiles",
"TomTom key unavailable": "Clé TomTom indisponible",
"TomTom key rejected": "Clé TomTom refusée",
"TomTom daily budget reached": "Quota quotidien TomTom atteint",
"Monthly traffic allowance used": "Quota mensuel de trafic épuisé",
"Traffic rate limit reached": "Limite de requêtes de trafic atteinte",
-1
View File
@@ -1092,7 +1092,6 @@
"TomTom roads first; OpenStreetMap fills the rest, simulated (needs a TomTom key)": "כבישי TomTom קודם; OpenStreetMap משלים את היתר, מדומים (דורש מפתח TomTom)",
"Hybrid": "היברידי",
"TomTom key unavailable": "מפתח TomTom אינו זמין",
"TomTom key rejected": "מפתח TomTom נדחה",
"TomTom daily budget reached": "תקציב TomTom היומי אזל",
"TomTom upstream unreachable": "שירות TomTom אינו נגיש",
"TomTom flow unavailable": "זרימת TomTom אינה זמינה",
-1
View File
@@ -1247,7 +1247,6 @@
"Moving dots colored by live flow": "Punti in movimento colorati in base al flusso live",
"Moving dots": "Punti in movimento",
"TomTom key unavailable": "Chiave TomTom non disponibile",
"TomTom key rejected": "Chiave TomTom rifiutata",
"TomTom daily budget reached": "Budget giornaliero TomTom esaurito",
"Monthly traffic allowance used": "Quota mensile del traffico esaurita",
"Traffic rate limit reached": "Limite di richieste del traffico raggiunto",
-1
View File
@@ -1201,7 +1201,6 @@
"Moving dots colored by live flow": "ライブの交通流で色分けした移動ドット",
"Moving dots": "移動ドット",
"TomTom key unavailable": "TomTomキーを利用できません",
"TomTom key rejected": "TomTomキーが拒否されました",
"TomTom daily budget reached": "TomTomの1日の上限に達しました",
"Monthly traffic allowance used": "今月の交通情報の上限に達しました",
"Traffic rate limit reached": "交通情報のリクエスト上限に達しました",
-1
View File
@@ -1245,7 +1245,6 @@
"Moving dots colored by live flow": "Pontos em movimento coloridos pelo fluxo ao vivo",
"Moving dots": "Pontos em movimento",
"TomTom key unavailable": "Chave do TomTom indisponível",
"TomTom key rejected": "Chave do TomTom recusada",
"TomTom daily budget reached": "Limite diário do TomTom atingido",
"Monthly traffic allowance used": "Cota mensal de trânsito esgotada",
"Traffic rate limit reached": "Trânsito: limite de requisições atingido",
-1
View File
@@ -2512,7 +2512,6 @@
"Military area": "Военная зона",
"SIMULATED — {reason}": "СИМУЛЯЦИЯ — {reason}",
"TomTom key unavailable": "Ключ TomTom недоступен",
"TomTom key rejected": "Ключ TomTom отклонён",
"TomTom daily budget reached": "Исчерпан дневной лимит TomTom",
"Monthly traffic allowance used": "Месячный лимит данных о трафике исчерпан",
"Traffic rate limit reached": "Достигнут лимит запросов данных о трафике",
-1
View File
@@ -1776,7 +1776,6 @@
"Moving dots colored by live flow": "Rörliga punkter färgade efter trafikflödet live",
"Moving dots": "Rörliga punkter",
"TomTom key unavailable": "TomTom-nyckel otillgänglig",
"TomTom key rejected": "TomTom-nyckeln avvisades",
"TomTom daily budget reached": "TomTom-dagsbudgeten är förbrukad",
"Monthly traffic allowance used": "Månadens trafikkvot är förbrukad",
"Traffic rate limit reached": "Trafiktjänsten har nått gränsen för förfrågningar",
-1
View File
@@ -1269,7 +1269,6 @@
"Moving dots colored by live flow": "Рухомі точки, забарвлені за потоком онлайн",
"Moving dots": "Рухомі точки",
"TomTom key unavailable": "Ключ TomTom недоступний",
"TomTom key rejected": "Ключ TomTom відхилено",
"TomTom daily budget reached": "Вичерпано денний ліміт TomTom",
"Monthly traffic allowance used": "Місячний ліміт даних про дорожній рух вичерпано",
"Traffic rate limit reached": "Перевищено ліміт запитів до сервісу руху",
-1
View File
@@ -1178,7 +1178,6 @@
"Moving dots colored by live flow": "按实时路况着色的移动圆点",
"Moving dots": "移动圆点",
"TomTom key unavailable": "TomTom 密钥不可用",
"TomTom key rejected": "TomTom 密钥被拒绝",
"TomTom daily budget reached": "已达 TomTom 每日配额",
"Monthly traffic allowance used": "本月交通数据配额已用完",
"Traffic rate limit reached": "已达到交通数据请求频率上限",
-1
View File
@@ -1178,7 +1178,6 @@
"Moving dots colored by live flow": "按實時路況著色的移動圓點",
"Moving dots": "移動圓點",
"TomTom key unavailable": "TomTom 密鑰不可用",
"TomTom key rejected": "TomTom 密鑰被拒絕",
"TomTom daily budget reached": "已達 TomTom 每日配額",
"Monthly traffic allowance used": "本月交通數據配額已用完",
"Traffic rate limit reached": "已達到交通數據請求頻率上限",
+24
View File
@@ -1,3 +1,4 @@
import { findCamera } from '../../render/rendererOf.js';
import {
FRAME_SIGNATURE_W,
FRAME_SIGNATURE_H,
@@ -41,6 +42,11 @@ export function fitToProjection(sourceW, sourceH) {
};
}
const PLANE_POINTS = ['mount', 'tl', 'tr', 'br', 'bl'];
const _scratchPoints = [];
// Keep the occluding surface below common negative geoid undulations.
const HORIZON_MARGIN_M = 200;
export function createFrames({ state: layerState, services, parts, source }) {
/**
* FNV-1a over the RGB channels of a downsampled frame. Pure (takes the raw
@@ -236,6 +242,22 @@ export function createFrames({ state: layerState, services, parts, source }) {
ctx.fillText(status.slice(0, 58), 46, h - 42);
}
/**
* Whether a camera's monitor plane may be on screen; what cannot be judged counts as visible.
* @param {Object} record - Camera record.
* @returns {boolean}
*/
function projectionInView(record) {
const camera = findCamera(layerState._viewer);
if (typeof camera?.visiblePoints !== 'function') return true;
const placed = record.frustumPositions;
if (!placed) return true;
const points = _scratchPoints;
points.length = 0;
for (const key of PLANE_POINTS) points.push(placed[key]);
return camera.visiblePoints(points, HORIZON_MARGIN_M) !== false;
}
/**
* Triggers a new frame fetch for an image-mode projection if the refresh
* interval has elapsed. Active cameras refresh more frequently than idle ones.
@@ -269,6 +291,8 @@ export function createFrames({ state: layerState, services, parts, source }) {
// bypass a provider's explicit minimum between image requests.
if (sourceRefreshMs > 0 && sinceLastRefresh < sourceRefreshMs) return;
if (!force && sinceLastRefresh < refreshMs) return;
// Skip before stamping lastImageRefreshAt, so the first tick back in view fetches.
if (!force && !projectionInView(record)) return;
runtime.lastImageRefreshAt = now;
const frameUrl = frameUrlFor(record.camera, refreshMs);
+108
View File
@@ -3,6 +3,7 @@
// 1920x1080 projection canvas, instead of being stretched to fill it.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { bindRenderer } from '../../render/rendererOf.js';
import { createFrames, fitToProjection } from './frames.js';
import {
FRAME_SIGNATURE_W,
@@ -170,3 +171,110 @@ test('a failed pixel signature redraws rather than assuming equal content', () =
assert.deepEqual(load(640, 480).at(-1), ['drawImage', 240, 0, 1440, 1080]);
assert.equal(runtime.canvasStamp, 2);
});
const MOUNT = { x: 0, y: 0, z: 0 };
function planeRecord() {
return {
camera: { id: 'plane' },
position: MOUNT,
frustumPositions: {
mount: MOUNT,
capCenter: { x: 1, y: 0, z: 0 },
tl: { x: 1, y: -1, z: 1 },
tr: { x: 1, y: 1, z: 1 },
br: { x: 1, y: 1, z: -1 },
bl: { x: 1, y: -1, z: -1 },
},
projection: {
mode: 'image',
image: {},
imageLoading: false,
imageReady: false,
lastImageRefreshAt: 0,
},
};
}
function framesFor(viewer) {
const state = {
_viewer: viewer,
_healthById: new Map(),
_activeCameraId: 'plane',
};
return createFrames({
state,
services: {},
parts: {
model: {
safeNumber: (value, fallback) =>
Number.isFinite(Number(value)) ? Number(value) : fallback,
},
},
source: { getFrameUrl: () => '/api/cctv/frame?id=plane' },
});
}
function framesWithCamera(t, camera) {
const host = {};
t.after(bindRenderer(host, { camera }));
return framesFor(host);
}
test('a plane the renderer may show fetches its picture', (t) => {
const visiblePoints = t.mock.fn(() => true);
const frames = framesWithCamera(t, { visiblePoints });
const record = planeRecord();
frames.refreshProjectionImage(record);
assert.match(
record.projection.image.src,
/^\/api\/cctv\/frame\?id=plane&projTs=/,
);
assert.equal(record.projection.imageLoading, true);
assert.equal(visiblePoints.mock.callCount(), 1);
const [points, margin] = visiblePoints.mock.calls[0].arguments;
const { mount, tl, tr, br, bl } = record.frustumPositions;
assert.deepEqual(points, [mount, tl, tr, br, bl]);
assert.equal(points[0], mount);
assert.equal(margin, 200);
});
test('a plane the renderer cannot show is not fetched, but a forced refresh is', (t) => {
const frames = framesWithCamera(t, { visiblePoints: () => false });
const record = planeRecord();
frames.refreshProjectionImage(record);
assert.equal(record.projection.image.src, undefined);
assert.equal(record.projection.lastImageRefreshAt, 0);
frames.refreshProjectionImage(record, true);
assert.match(record.projection.image.src, /projTs=/);
});
test('a skipped refresh does not use up the interval', (t) => {
let visible = false;
const frames = framesWithCamera(t, { visiblePoints: () => visible });
const record = planeRecord();
frames.refreshProjectionImage(record);
assert.equal(record.projection.image.src, undefined);
visible = true;
frames.refreshProjectionImage(record);
assert.match(record.projection.image.src, /projTs=/);
});
test('what cannot be judged counts as visible', (t) => {
for (const frames of [
framesWithCamera(t, { visiblePoints: () => null }),
framesWithCamera(t, { pose: () => ({}) }),
framesFor(null),
]) {
const record = planeRecord();
frames.refreshProjectionImage(record);
assert.match(record.projection.image.src, /projTs=/);
}
const noGeometry = planeRecord();
delete noGeometry.frustumPositions;
const visiblePoints = t.mock.fn(() => false);
framesWithCamera(t, { visiblePoints }).refreshProjectionImage(noGeometry);
assert.equal(visiblePoints.mock.callCount(), 0);
assert.match(noGeometry.projection.image.src, /projTs=/);
});
-1
View File
@@ -136,7 +136,6 @@ const GROUP_CLASS = Object.freeze({
resource: 'imaging',
weather: 'imaging',
planet: 'imaging',
sar: 'imaging',
'gps-ops': 'telecom',
glonass: 'telecom',
'glo-ops': 'telecom',
-1
View File
@@ -381,7 +381,6 @@ test('every ingested group names the class its unnamed members fall back to', ()
resource: 'imaging',
weather: 'imaging',
planet: 'imaging',
sar: 'imaging',
science: 'probes',
};
assert.deepEqual(
+1 -1
View File
@@ -16,7 +16,7 @@ export const SATCAT_WAIT_MS = 3000;
/**
* How long a complete, current SATCAT read is kept before the layer asks
* again, ms. SATCAT changes daily and the proxy caches it a day, so the
* five-minute TLE update does not read all eleven groups each time.
* five-minute TLE update does not read all ten groups each time.
*/
export const SATCAT_KEEP_MS = 6 * 60 * 60 * 1000;
+6 -4
View File
@@ -5,9 +5,9 @@ import { SATELLITE_CLASS_DISPLAY, SATELLITE_CLASS_IDS } from './classes.js';
/**
* Satellite Orbits — Real-time positions via CelesTrak TLE + SGP4 propagation.
*
* Loads eleven CelesTrak groups: stations, visual, GPS, GLONASS, Galileo, the
* geosynchronous belt, and the Earth resources, weather, Planet, SAR and
* science groups. Each object is filed under one of six classes
* Loads ten CelesTrak groups: stations, visual, GPS, GLONASS, Galileo, the
* geosynchronous belt, and the Earth resources, weather, Planet and science
* groups. Each object is filed under one of six classes
* (src/layers/satellites/classes.js) whose visibility the layer row toggles; dense mode
* (setParams catalog:'dense', the STARLINK toggle) adds the Starlink shell as
* points-only extras.
@@ -211,6 +211,9 @@ export const RING_ROTATION_MS = 1000;
* proxy; `tag` is the internal group key used for POINT_STYLES lookup.
* Note: CelesTrak's GLONASS group is named 'glo-ops' (not
* 'glonass-operational' — that name 404s upstream).
* Every entry must be a group CelesTrak serves: one that is not fails on every
* update, so the layer row reads DEGRADED ("1 CelesTrak group unavailable")
* for good. CelesTrak has no `sar` group (`sarsat` is search and rescue).
*/
export const CATALOG_GROUPS = [
@@ -225,7 +228,6 @@ export const CATALOG_GROUPS = [
{ tag: 'resource', path: 'resource' },
{ tag: 'weather', path: 'weather' },
{ tag: 'planet', path: 'planet' },
{ tag: 'sar', path: 'sar' },
{ tag: 'science', path: 'science' },
];
-1
View File
@@ -10,7 +10,6 @@ const GROUPS = new Set([
'resource',
'weather',
'planet',
'sar',
'science',
]);
-1
View File
@@ -34,7 +34,6 @@ const GROUPS = [
'resource',
'weather',
'planet',
'sar',
'science',
];
/** The core catalog's groups, one owned satellite each. */
-2
View File
@@ -50,8 +50,6 @@ export function createFlow({ state: layerState, services, parts, source }) {
if (code === 'RATE_LIMITED') return msg('Traffic rate limit reached');
if (status === 503 && code && code !== 'no_key')
return msg('Traffic service unavailable');
// TomTom refused the key on both of its flow endpoints.
if (code === 'key_rejected') return msg('TomTom key rejected');
if (status === 503) return msg('TomTom key unavailable');
if (status === 429) return msg('TomTom daily budget reached');
if (status === 502 || status === 504)
+4 -45
View File
@@ -15,15 +15,6 @@ import { VectorTile } from '@mapbox/vector-tile';
* ratio (1 = free flow). Features with a missing/non-finite `traffic_level`
* are skipped unless `road_closure` is true (closures decode with level 0).
*
* The proxy serves tiles from either TomTom flow endpoint, and they name
* things differently. TomTom Maps (`traffic/map/4`, style `relative`):
* `traffic_level`, `road_type` ("Motorway", "Major road", …) and
* `traffic_road_coverage` (`full` when one line carries both directions).
* TomTom Orbis Maps (`maps/orbis/traffic`, apiVersion 2): `relative_speed`
* (the same ratio), `road_category` (OpenStreetMap-style, with `_link`
* ramps) and one line per travel direction. Orbis features are decoded into
* the TomTom Maps vocabulary, so nothing downstream tells them apart.
*
* Deps: `pbf@5` (PbfReader) + `@mapbox/vector-tile@3` — both tiny and
* tree-shakeable; decoding happens client-side so the proxy stays a dumb
* binary cache.
@@ -32,35 +23,6 @@ import { VectorTile } from '@mapbox/vector-tile';
*/
const FLOW_LAYER_NAME = 'Traffic flow';
/**
* Orbis `road_category` → the TomTom Maps `road_type` and `road_category`
* the traffic layer classifies roads by. A ramp takes its road's class;
* service roads and tracks stay unmapped, as TomTom Maps tiles left
* parking and private roads out of the drivable set.
*/
const ORBIS_ROAD_CATEGORIES = Object.freeze({
motorway: ['Motorway', 'motorway'],
trunk: ['International road', 'trunk'],
primary: ['Major road', 'primary'],
secondary: ['Secondary road', 'secondary'],
tertiary: ['Connecting road', 'tertiary'],
street: ['Local road', 'street'],
});
/** Road class of a feature, in TomTom Maps terms, from either schema. */
function roadClassOf(props) {
if (typeof props.road_type === 'string')
return [props.road_type, props.road_category ?? null];
const category =
typeof props.road_category === 'string'
? props.road_category.replace(/_link$/, '')
: null;
if (category && Object.hasOwn(ORBIS_ROAD_CATEGORIES, category))
return ORBIS_ROAD_CATEGORIES[category];
// Kept as sent, so the drivable filter drops it by category.
return ['', props.road_category ?? null];
}
/** Decode flow geometry; strict mode distinguishes damaged tiles from valid empty coverage. */
export function decodeFlowTile(data, z, x, y, { strict = false } = {}) {
let layer;
@@ -87,15 +49,13 @@ export function decodeFlowTile(data, z, x, y, { strict = false } = {}) {
const props = feature.properties || {};
const closure =
props.road_closure === true || props.road_closure === 'true';
const orbis =
props.traffic_level === undefined && props.road_type === undefined;
const rawLevel = orbis ? props.relative_speed : props.traffic_level;
const rawLevel = props.traffic_level;
const hasLevel = typeof rawLevel === 'number' && Number.isFinite(rawLevel);
// Skip features we can't color — unless closed (closures render dot-free
// regardless of level, so they stay useful without one).
if (!hasLevel && !closure) continue;
const trafficLevel = hasLevel ? Math.min(1, Math.max(0, rawLevel)) : 0;
const [roadType, roadCategory] = roadClassOf(props);
const roadType = typeof props.road_type === 'string' ? props.road_type : '';
const lines =
geometry.type === 'LineString'
@@ -109,11 +69,10 @@ export function decodeFlowTile(data, z, x, y, { strict = false } = {}) {
coords,
trafficLevel,
roadType,
roadCategory,
roadCategory: props.road_category ?? null,
roadSubcategory: props.road_subcategory ?? null,
closure,
// Orbis draws each travel direction as its own line.
coverage: props.traffic_road_coverage ?? (orbis ? 'one_side' : null),
coverage: props.traffic_road_coverage ?? null,
leftHandTraffic:
props.left_hand_traffic === true ||
props.left_hand_traffic === 'true',
-136
View File
@@ -1,136 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { PbfWriter } from 'pbf';
import { decodeFlowTile } from './flowDecode.js';
import { flowSegmentsToRoads, isDrivableFlowSegment } from './roadModes.js';
/**
* One "Traffic flow" layer; each feature is a two-point line carrying the
* given properties (string, number or boolean values).
*/
function flowTile(features) {
const keys = [];
const values = [];
const tags = features.map((props) =>
Object.entries(props).flatMap(([key, value]) => {
if (!keys.includes(key)) keys.push(key);
values.push(value);
return [keys.indexOf(key), values.length - 1];
}),
);
const writer = new PbfWriter();
writer.writeMessage(
3,
(_, layer) => {
layer.writeVarintField(15, 2);
layer.writeStringField(1, 'Traffic flow');
layer.writeVarintField(5, 4096);
for (const key of keys) layer.writeStringField(3, key);
for (const value of values)
layer.writeMessage(
4,
(_, out) => {
if (typeof value === 'string') out.writeStringField(1, value);
else if (typeof value === 'boolean')
out.writeBooleanField(7, value);
else out.writeDoubleField(3, value);
},
null,
);
tags.forEach((featureTags, i) =>
layer.writeMessage(
2,
(_, feature) => {
feature.writeVarintField(3, 2);
feature.writePackedVarint(2, featureTags);
// MoveTo (100, 100 + i), LineTo +200 east.
feature.writePackedVarint(4, [9, 200, 200 + 2 * i, 10, 400, 0]);
},
null,
),
);
},
null,
);
return writer.finish();
}
const decode = (features) => decodeFlowTile(flowTile(features), 12, 935, 1686);
test('TomTom Maps flow features decode as before', () => {
const [segment] = decode([
{
traffic_level: 0.6,
road_type: 'Major road',
road_category: 'primary',
traffic_road_coverage: 'full',
},
]);
assert.equal(segment.trafficLevel, 0.6);
assert.equal(segment.roadType, 'Major road');
assert.equal(segment.roadCategory, 'primary');
assert.equal(segment.coverage, 'full');
// A TomTom Maps line with no coverage tag still reports none.
assert.equal(
decode([{ traffic_level: 1, road_type: 'Motorway' }])[0].coverage,
null,
);
});
test('Orbis flow features decode into the TomTom Maps road vocabulary', () => {
const segments = decode([
{ relative_speed: 0.42, road_category: 'motorway' },
{ relative_speed: 0.9, road_category: 'trunk_link' },
{
relative_speed: 0.7,
road_category: 'street',
road_subcategory: 'residential',
left_hand_traffic: true,
},
{ relative_speed: 1.4, road_category: 'tertiary' },
{ road_category: 'secondary', road_closure: true },
]);
assert.deepEqual(
segments.map((s) => [s.roadType, s.roadCategory, s.trafficLevel]),
[
['Motorway', 'motorway', 0.42],
['International road', 'trunk', 0.9],
['Local road', 'street', 0.7],
['Connecting road', 'tertiary', 1], // clamped like traffic_level
['Secondary road', 'secondary', 0], // closures need no speed
],
);
assert.equal(segments[2].roadSubcategory, 'residential');
assert.equal(segments[2].leftHandTraffic, true);
assert.equal(segments[4].closure, true);
// Orbis draws one line per travel direction.
assert.ok(segments.every((s) => s.coverage === 'one_side'));
assert.ok(segments.every(isDrivableFlowSegment));
assert.deepEqual(
flowSegmentsToRoads(segments).map((road) => [road.type, road.oneway]),
[
['motorway', 1],
['trunk', 1],
['residential', 1],
['tertiary', 1],
['secondary', 1],
],
);
});
test('Orbis service roads, tracks and speedless lines never become traffic', () => {
const segments = decode([
{ relative_speed: 0.5, road_category: 'service' },
{ relative_speed: 0.5, road_category: 'track' },
{ relative_speed: 0.5 },
{ road_category: 'primary' }, // no speed and not closed: nothing to draw
]);
assert.deepEqual(
segments.map((s) => [s.roadType, s.roadCategory]),
[
['', 'service'],
['', 'track'],
['', null],
],
);
assert.equal(segments.filter(isDrivableFlowSegment).length, 0);
});
+56
View File
@@ -86,6 +86,62 @@ function sameMatrix(array, matrix) {
return true;
}
const finiteVector = (v) =>
!!v && Number.isFinite(v.x) && Number.isFinite(v.y) && Number.isFinite(v.z);
/** Conservative globe/frustum visibility; null means unknown. */
export function createPointsVisibility(scene, camera) {
const visibilitySphere = new Cesium.BoundingSphere();
let visibilityMargin = null;
let visibilityEllipsoid = null;
let visibilityOccluder = null;
return function visiblePoints(points, marginM) {
const eye = camera.positionWC;
const direction = camera.directionWC;
const up = camera.upWC;
if (
scene.mode !== Cesium.SceneMode.SCENE3D ||
!points?.length ||
!finiteVector(eye) ||
!finiteVector(direction) ||
!finiteVector(up) ||
!points.every(finiteVector)
)
return null;
if (visibilityMargin !== marginM) {
const radii = Cesium.Ellipsoid.WGS84.radii;
visibilityMargin = marginM;
visibilityEllipsoid = new Cesium.Ellipsoid(
radii.x - marginM,
radii.y - marginM,
radii.z - marginM,
);
visibilityOccluder = new Cesium.EllipsoidalOccluder(visibilityEllipsoid);
}
const inverse = visibilityEllipsoid.oneOverRadii;
// Inside the ellipsoid Cesium's occluder hides nearby points; judge by the frustum alone.
const outside =
Math.hypot(eye.x * inverse.x, eye.y * inverse.y, eye.z * inverse.z) >= 1;
if (outside) {
visibilityOccluder.cameraPosition = eye;
let visible = false;
for (const p of points) {
if (visibilityOccluder.isPointVisible(p)) {
visible = true;
break;
}
}
if (!visible) return false;
}
const culling = camera.frustum.computeCullingVolume(eye, direction, up);
return (
culling.computeVisibility(
Cesium.BoundingSphere.fromPoints(points, visibilitySphere),
) !== Cesium.Intersect.OUTSIDE
);
};
}
/**
* @param {{scene: object, camera: object, report: (error: unknown) => void,
* widget?: object, capabilities?: ReadonlySet<string>,
+142 -1
View File
@@ -19,7 +19,7 @@ import {
headlessCamera,
withVirtualClock,
} from './cameraGoldens.js';
import { createCesiumCamera } from './camera.js';
import { createCesiumCamera, createPointsVisibility } from './camera.js';
import { createCesiumPorts } from './ports.js';
import { bindRenderer, cameraOf } from '../rendererOf.js';
@@ -337,6 +337,147 @@ test('the camera port gives the clock its own tick back as it goes', () => {
}
});
test('visiblePoints is there only with its capability, and unknown outside 3D', (t) => {
const { scene } = headlessCamera();
for (const name of ['preUpdate', 'postUpdate', 'preRender', 'postRender'])
scene[name] = new Cesium.Event();
scene.primitives = { add() {}, remove() {} };
scene.requestRender = () => {};
const viewer = { scene, clock: { currentTime: Cesium.JulianDate.now() } };
const without = createCesiumPorts(viewer, { capabilities: new Set() });
assert.equal(without.camera.visiblePoints, undefined);
without.dispose();
const ports = createCesiumPorts(viewer, {
capabilities: new Set(['pointVisibility']),
});
t.after(() => ports.dispose());
const points = [Cesium.Cartesian3.fromDegrees(0, 0, 10)];
for (const mode of [
Cesium.SceneMode.SCENE2D,
Cesium.SceneMode.COLUMBUS_VIEW,
Cesium.SceneMode.MORPHING,
undefined,
]) {
scene.mode = mode;
assert.equal(ports.camera.visiblePoints(points, 200), null);
}
scene.mode = Cesium.SceneMode.SCENE3D;
assert.equal(typeof ports.camera.visiblePoints(points, 200), 'boolean');
});
const point = (lon, lat, altitude = 20) =>
Cesium.Cartesian3.fromDegrees(lon, lat, altitude);
const down = Cesium.Cartesian3.negate(
Cesium.Cartesian3.UNIT_X,
new Cesium.Cartesian3(),
);
const up = Cesium.Cartesian3.UNIT_Z;
const frustum = new Cesium.PerspectiveFrustum({
fov: Cesium.Math.toRadians(60),
aspectRatio: 16 / 9,
near: 1,
// Cesium's default far plane, as the app uses.
far: 5e8,
});
function visibility(position, direction, up) {
const visiblePoints = createPointsVisibility(
{ mode: Cesium.SceneMode.SCENE3D },
{ positionWC: position, directionWC: direction, upWC: up, frustum },
);
return (points) => visiblePoints(points, 200);
}
function directionTo(position, target) {
return Cesium.Cartesian3.normalize(
Cesium.Cartesian3.subtract(target, position, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
}
function assertInFrustum(points, position, direction) {
const culling = frustum.computeCullingVolume(position, direction, up);
assert.notEqual(
culling.computeVisibility(Cesium.BoundingSphere.fromPoints(points)),
Cesium.Intersect.OUTSIDE,
);
}
test('a plane in front of the camera is visible', () => {
assert.equal(visibility(point(0, 0, 30000), down, up)([point(0, 0)]), true);
});
test('a plane behind the camera is outside the frustum', () => {
assert.equal(
visibility(point(0, 0, 30000), Cesium.Cartesian3.UNIT_X, up)([point(0, 0)]),
false,
);
});
test('a corner can be in view when the mount and centre are outside', () => {
const visible = visibility(point(0, 0, 30000), down, up);
const mount = point(0.3, 0);
const points = [
mount,
point(0.1, 0.0001),
point(0.3, 0.0001),
point(0.3, -0.0001),
point(0.1, -0.0001),
];
assert.equal(visible(points), true);
assert.equal(visible([mount]), false);
assert.equal(visible([point(0.2, 0)]), false);
});
test('a nearby plane below the ellipsoid is visible to low and high viewers', () => {
const cap = point(0.00054, 0, -18);
const points = [point(0, 0, -18), cap];
for (const altitude of [4, 1200]) {
const position = point(0.00135, 0, altitude);
const direction = directionTo(position, cap);
assertInFrustum(points, position, direction);
assert.equal(visibility(position, direction, up)(points), true);
}
});
test('the horizon rejects a negative-height plane on the far side', () => {
const mount = point(0, 0, -18);
const points = [mount, point(0.00054, 0, -18)];
for (const altitude of [4, 30000, 2e7]) {
const position = point(180, 0, altitude);
const direction = directionTo(position, mount);
assertInFrustum(points, position, direction);
assert.equal(visibility(position, direction, up)(points), false);
}
});
test('a low viewer can see a plane beyond the WGS84 horizon', () => {
const mount = point(0, 0, 1);
const position = point(0.2, 0, 4);
assert.equal(
visibility(position, directionTo(position, mount), up)([mount]),
true,
);
});
test('deep viewers do not lose nearby planes to the horizon test', () => {
const mount = point(0, 0, -350);
const position = point(0.00135, 0, -300);
assert.equal(
visibility(position, directionTo(position, mount), up)([mount]),
true,
);
});
test('a non-finite camera direction leaves visibility unknown', () => {
const visible = visibility(
point(0, 0, 30000),
new Cesium.Cartesian3(NaN, 0, 0),
up,
);
assert.equal(visible([point(0, 0)]), null);
});
test('setFov holds the vertical angle across resizes, and waits for a first one', () => {
const { scene, camera } = headlessCamera();
scene.postUpdate = new Cesium.Event();
@@ -321,6 +321,8 @@ test('the application’s Cesium renderer runs the controller around its preUpda
const renderer = await plugin.create({ container: {} });
assert.equal(scene.screenSpaceCameraController.enableInputs, false);
assert.equal(typeof renderer.camera.native.setPose, 'function');
assert.equal(renderer.capabilities.has('pointVisibility'), true);
assert.equal(renderer.camera.visiblePoints([], 200), null);
renderer.frame.on('preUpdate', () => order.push('preUpdate'));
scene.preUpdate.raise(scene, Cesium.JulianDate.fromDate(new Date(5000)));
assert.deepEqual(order, [['before', 5000], 'preUpdate', 'after']);
+4 -1
View File
@@ -13,7 +13,7 @@
* absent, never stubbed.
*/
import * as Cesium from 'cesium';
import { createCesiumCamera } from './camera.js';
import { createCesiumCamera, createPointsVisibility } from './camera.js';
import { createControlledCamera } from './controlledCamera.js';
import { listenerList, toCartesian, uncaught } from './common.js';
import { createCesiumCredits } from './credits.js';
@@ -84,6 +84,7 @@ export function cesiumCapabilities(scene, only) {
// Raster shells; other field kinds are refused.
'fields',
'followFrame',
'pointVisibility',
// Cesium's AUTODETECT tracking frame (`follow.js`).
'followAutodetect',
'cameraChangeThreshold',
@@ -488,6 +489,8 @@ export function createCesiumPorts(
: {}),
});
const cameraPort = cameraPart.port;
if (capabilities.has('pointVisibility'))
cameraPort.visiblePoints = createPointsVisibility(scene, camera);
measureCameraChanged = cameraPart.measureChanged ?? null;
const effectsPart = createCesiumEffects(scene, {
capabilities,
+1
View File
@@ -12,6 +12,7 @@ import { createNativeClick } from './nativeClick.js';
test('capabilities follow what the scene supports', () => {
const effects = [
'followFrame',
'pointVisibility',
'followAutodetect',
'cameraChangeThreshold',
'columns',
+9
View File
@@ -234,6 +234,15 @@ export type CameraEvent =
'changed' | 'moveStart' | 'moveEnd' | 'followChanged' | 'flightEnd';
export interface CameraPort {
/**
* Whether any of the ECEF points may be on screen: false only when their
* bounding sphere is outside the view or all of them are below the horizon
* of WGS84 shrunk by `horizonMarginM` metres; null when it cannot tell
* (not a 3D scene, an empty point set, or a non-finite point or camera
* vector), which callers treat as visible. Supply a finite, nonnegative
* margin smaller than the shortest WGS84 radius.
*/
visiblePoints?(points: Ecef[], horizonMarginM: number): boolean | null;
pose(): CameraPose;
/**
* Place the eye. A position with a `{direction, up}` orientation is placed
+2
View File
@@ -183,6 +183,8 @@ export type Capability =
| 'pickPosition'
/** Points tested against the frame's depth (`query.occlusionTest`). */
| 'occlusionTest'
/** Conservative camera visibility of a point set (`camera.visiblePoints`). */
| 'pointVisibility'
/** Outward user zooms that keep the Earth framed (`controls.keepEarthFramed`). */
| 'keepEarthFramed'
/** Height sampling against tiles and terrain. */
+2
View File
@@ -50,6 +50,7 @@ export const CAPABILITIES = Object.freeze([
'followFrame',
'cameraChangeThreshold',
'occlusionTest',
'pointVisibility',
'keepEarthFramed',
]);
@@ -209,6 +210,7 @@ export const PORTS = deepFreeze({
'matrices',
),
['followFrame', 'followFrame'],
['visiblePoints', 'pointVisibility'],
['controls.keepEarthFramed', 'keepEarthFramed'],
]),
query: Object.fromEntries([
+2
View File
@@ -262,6 +262,8 @@ export function createStubRenderer(options = {}) {
camera.setViewRectangle(viewRectangle);
if (capabilities.has('followFrame'))
camera.port.followFrame = camera.eyeFrame;
if (capabilities.has('pointVisibility'))
camera.port.visiblePoints = () => null;
camera.port.setView({
destination: { lon: -97.7431, lat: 30.2672, height: 15000000 },
});
+9
View File
@@ -40,6 +40,15 @@ test('the stub passes the conformance suite', async () => {
]);
});
test('point visibility capability is optional and the stub reports unknown', () => {
const without = createStubRenderer({ capabilities: [] });
const withVisibility = createStubRenderer({
capabilities: ['pointVisibility'],
});
assert.equal(without.camera.visiblePoints, undefined);
assert.equal(withVisibility.camera.visiblePoints([], 200), null);
});
test('a frame runs the contract’s steps in order', () => {
const r = createStubRenderer();
r.frame.requestRender('test');
-111
View File
@@ -262,117 +262,6 @@ test('traffic refuses cross-site requests in dev and preview before spending the
}
});
test('traffic falls back to the Orbis flow endpoint when TomTom refuses the key on the TomTom Maps one', async (t) => {
isolate(t, { TOMTOM_API_KEY: 'orbis-only', TOMTOM_DAILY_TILE_BUDGET: '' });
const calls = [];
t.mock.method(globalThis, 'fetch', async (raw, init = {}) => {
const url = new URL(raw);
const orbis = url.pathname.startsWith('/maps/orbis/');
calls.push(orbis ? 'orbis' : 'legacy');
if (orbis) {
assert.match(
url.pathname,
/^\/maps\/orbis\/traffic\/flow\/vector\/tile\/8\/[12]\/1$/,
'no .pbf suffix or flow style on Orbis',
);
assert.equal(url.searchParams.get('apiVersion'), '2');
assert.equal(url.searchParams.get('key'), null);
assert.equal(init.headers['TomTom-Api-Key'], 'orbis-only');
return new Response(new Uint8Array([4, 5, 6]));
}
assert.equal(url.pathname, '/traffic/map/4/tile/flow/relative/8/1/1.pbf');
assert.equal(url.searchParams.get('key'), 'orbis-only');
return Response.json(
{ detailedError: { code: 'Forbidden' } },
{ status: 403 },
);
});
const request = install(tomtomProxy());
const first = await request('/flow/8/1/1.pbf');
assert.equal(first.status, 200);
assert.equal(first.headers['x-tomtom-cache'], 'MISS');
assert.deepEqual([...first.body], [4, 5, 6]);
assert.deepEqual(calls, ['legacy', 'orbis']);
assert.equal(json(await request('/status')).keyRejected, false);
// Both attempts were real upstream requests.
assert.equal(json(await request('/status')).dailyCount, 2);
// The working endpoint is remembered: no second 403 per tile.
calls.length = 0;
process.env.TOMTOM_API_KEY = 'orbis-only';
assert.equal((await request('/flow/8/2/1.pbf')).status, 200);
assert.deepEqual(calls, ['orbis']);
// A new key starts over on the TomTom Maps endpoint.
calls.length = 0;
process.env.TOMTOM_API_KEY = 'another-key';
t.mock.method(globalThis, 'fetch', async (raw) => {
calls.push(
new URL(raw).pathname.startsWith('/maps/orbis/') ? 'orbis' : 'legacy',
);
return new Response(new Uint8Array([7]));
});
assert.equal((await request('/flow/8/3/1.pbf')).status, 200);
assert.deepEqual(calls, ['legacy']);
});
test('traffic names a key both TomTom flow endpoints refuse and stops spending the budget on it', async (t) => {
isolate(t, { TOMTOM_API_KEY: 'refused', TOMTOM_DAILY_TILE_BUDGET: '' });
let now = Date.UTC(2026, 10, 20, 12);
t.mock.method(Date, 'now', () => now);
let calls = 0;
let status = 403;
t.mock.method(globalThis, 'fetch', async () => {
calls++;
return status === 200
? new Response(new Uint8Array([1]))
: new Response('{}', { status });
});
const request = install(tomtomProxy());
assert.equal(json(await request('/status')).keyRejected, false);
const refused = await request('/flow/8/1/1.pbf');
assert.equal(refused.status, 403);
assert.deepEqual(json(refused), { error: 'key_rejected' });
assert.equal(calls, 2, 'one attempt per endpoint');
// Other tiles answer from the verdict, without asking TomTom again.
for (const x of [2, 3, 4])
assert.deepEqual(json(await request(`/flow/8/${x}/1.pbf`)), {
error: 'key_rejected',
});
assert.equal(calls, 2);
const state = json(await request('/status'));
assert.equal(state.hasKey, true);
assert.equal(state.keyRejected, true);
assert.equal(state.dailyCount, 2);
// The verdict expires, so a key fixed at TomTom recovers without a restart.
now += 5 * 60_000 + 1;
status = 200;
assert.equal((await request('/flow/8/1/1.pbf')).status, 200);
assert.equal(json(await request('/status')).keyRejected, false);
// A replaced key is tried at once.
status = 403;
now += 120_001;
assert.equal((await request('/flow/8/5/1.pbf')).status, 403);
process.env.TOMTOM_API_KEY = 'replacement';
status = 200;
assert.equal((await request('/flow/8/6/1.pbf')).status, 200);
});
test('traffic keeps an ordinary upstream failure on one endpoint and reports it as upstream', async (t) => {
isolate(t, { TOMTOM_API_KEY: 'fixture-key', TOMTOM_DAILY_TILE_BUDGET: '' });
const calls = [];
t.mock.method(globalThis, 'fetch', async (raw) => {
calls.push(
new URL(raw).pathname.startsWith('/maps/orbis/') ? 'orbis' : 'legacy',
);
return new Response('', { status: 500 });
});
const request = install(tomtomProxy());
const res = await request('/flow/8/1/1.pbf');
assert.equal(res.status, 502);
assert.deepEqual(json(res), { error: 'upstream' });
assert.deepEqual(calls, ['legacy']);
assert.equal(json(await request('/status')).keyRejected, false);
});
test('traffic middleware answers 502 to an oversized tile without caching it', async (t) => {
isolate(t, { TOMTOM_API_KEY: 'fixture-key', TOMTOM_DAILY_TILE_BUDGET: '' });
const bodies = [];
+4 -1
View File
@@ -374,7 +374,10 @@ test('a SATCAT failure never holds off the TLEs, but CelesTrak throttling holds
: new Response(tle);
});
const request = install(celestrakProxy());
assert.equal((await request('/api/celestrak-satcat', '/sar')).status, 502);
assert.equal(
(await request('/api/celestrak-satcat', '/science')).status,
502,
);
const starlink = await request('/api/celestrak', '/starlink');
assert.equal(starlink.status, 200, 'the TLE feed is not cooling down');
assert.equal(starlink.body, tle);
+16 -1
View File
@@ -1,3 +1,5 @@
import { watch } from 'vue';
import { MOBILE_SHEET_ATTR } from './mobileSheets.js';
import {
EMPTY_CCTV_FRAME,
_clearCctvFrame,
@@ -73,7 +75,10 @@ export class CctvControls {
if (state) this._renderCctvState(state);
if (this._cctvChip) this._publishCctvChip({});
});
if (this._cctvVideo && typeof MutationObserver !== 'undefined') {
if (
(this._cctvVideo || this._cctvFrame) &&
typeof MutationObserver !== 'undefined'
) {
this._videoVisibilityObserver = new MutationObserver(() =>
this._renderCctvState(this._cctvState),
);
@@ -82,6 +87,15 @@ export class CctvControls {
attributes: true,
attributeFilter: ['class', 'hidden'],
});
// On phones the panel is on screen only while the Cameras sheet is open.
this._videoVisibilityObserver.observe(document.body, {
attributes: true,
attributeFilter: ['class', MOBILE_SHEET_ATTR],
});
this._offPreviewCards = watch(
() => this.store.previewCards,
() => this._renderCctvState(this._cctvState),
);
this.listen(document, 'visibilitychange', () =>
this._renderCctvState(this._cctvState),
);
@@ -154,6 +168,7 @@ export class CctvControls {
this._quebecCctvOverlay?.dispose();
this._cctvVideoSurface?.stop();
this._videoVisibilityObserver?.disconnect();
this._offPreviewCards?.();
this._actionGeneration++;
this.listeners.abort();
this._cctvUnsubscribe?.();
+152 -11
View File
@@ -20,7 +20,7 @@ const BUTTONS = {
_cctvProjectionBtn: 'cctv-projection-btn',
};
function panel(t) {
function panel(t, { video = false } = {}) {
document.body.replaceChildren();
const host = document.body.appendChild(document.createElement('div'));
const pinia = createPinia();
@@ -32,6 +32,7 @@ function panel(t) {
document.getElementById(id),
]),
);
if (video) elements._cctvVideo = document.getElementById('cctv-video');
const controls = new CctvControls({
elements: {
...elements,
@@ -377,17 +378,10 @@ test('a second edit of the same chip gets a fresh input', async (t) => {
});
test('the frame preview renders each step of a camera frame request', async (t) => {
const prior = globalThis.Image;
const requests = [];
globalThis.Image = class {
constructor() {
requests.push(this);
}
};
t.after(() => {
globalThis.Image = prior;
});
const requests = mockImages(t);
const { controls, byId } = panel(t);
// The preview loads while the panel is open; the panel starts collapsed.
byId('cctv-panel').classList.remove('collapsed');
const frame = byId('cctv-frame');
const wrap = byId('cctv-frame-wrap');
const badge = byId('cctv-source-badge');
@@ -606,3 +600,150 @@ test('the meta line of a disabled layer does not describe its last camera', () =
);
assert.match(presentCctvPanel(activeState, true).meta, /^Austin · HDG /);
});
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
function mockImages(t) {
const prior = globalThis.Image;
const requests = [];
globalThis.Image = class {
constructor() {
requests.push(this);
}
};
t.after(() => {
globalThis.Image = prior;
});
return requests;
}
const stillState = (frameUrl, id = 'a') => ({
enabled: true,
count: 2,
cameraIndex: [camera, { ...camera, id: 'b' }],
activeCameraId: id,
activeCamera: { ...camera, id, frameUrl, sourceKind: 'snapshot' },
});
test('the still preview is fetched only while the tab and the panel are shown', async (t) => {
const requests = mockImages(t);
const hidden = Object.getOwnPropertyDescriptor(document, 'hidden');
let tabHidden = false;
Object.defineProperty(document, 'hidden', {
configurable: true,
get: () => tabHidden,
});
t.after(() => {
if (hidden) Object.defineProperty(document, 'hidden', hidden);
else delete document.hidden;
});
const { controls, byId } = panel(t);
assert.equal(controls._cctvVideo, undefined);
const panelElement = byId('cctv-panel');
const state = stillState;
// Collapsed panel: nothing is requested, however often the state arrives.
assert.equal(panelElement.classList.contains('collapsed'), true);
controls._renderCctvState(state('a1.jpg'));
controls._renderCctvState(state('a2.jpg'));
assert.equal(requests.length, 0, 'collapsed panel');
// Opening it resumes through the class observer, with no manual render.
panelElement.classList.remove('collapsed');
await settle();
assert.equal(requests.length, 1, 'expanded panel');
assert.equal(requests[0].src, 'a2.jpg');
requests[0].onload();
// A background tab: refreshed URLs are not requested.
tabHidden = true;
document.dispatchEvent(new Event('visibilitychange'));
controls._renderCctvState(state('a3.jpg'));
assert.equal(requests.length, 1, 'hidden tab');
// Back in the tab: visibilitychange alone fetches the current URL.
tabHidden = false;
document.dispatchEvent(new Event('visibilitychange'));
assert.equal(requests.length, 2, 'visible tab');
assert.equal(requests[1].src, 'a3.jpg');
});
test('the still preview waits for the Cameras sheet on phones', async (t) => {
const requests = mockImages(t);
t.after(() => {
document.body.classList.remove('mobile-shell');
document.body.removeAttribute('data-mobile-sheet');
});
const { controls, byId } = panel(t);
byId('cctv-panel').classList.remove('collapsed');
document.body.classList.add('mobile-shell');
document.body.setAttribute('data-mobile-sheet', 'layers');
controls._renderCctvState(stillState('a1.jpg'));
assert.equal(requests.length, 0, 'another sheet is open');
document.body.removeAttribute('data-mobile-sheet');
controls._renderCctvState(stillState('a1.jpg'));
assert.equal(requests.length, 0, 'no sheet is open');
document.body.setAttribute('data-mobile-sheet', 'cameras');
await settle();
assert.equal(requests.length, 1, 'Cameras sheet opened');
assert.equal(requests[0].src, 'a1.jpg');
// Off a phone the sheet attribute means nothing.
requests[0].onload();
document.body.classList.remove('mobile-shell');
document.body.setAttribute('data-mobile-sheet', 'layers');
controls._renderCctvState(stillState('a2.jpg'));
assert.equal(requests.length, 2, 'desktop ignores the sheet');
});
test('a camera picked while the panel is collapsed shows its own still on expanding', async (t) => {
const requests = mockImages(t);
const { controls, byId } = panel(t);
const panelElement = byId('cctv-panel');
panelElement.classList.remove('collapsed');
controls._renderCctvState(stillState('a1.jpg'));
assert.equal(requests.length, 1);
assert.equal(requests[0].src, 'a1.jpg');
panelElement.classList.add('collapsed');
await settle();
controls._renderCctvState(stillState('b1.jpg', 'b'));
assert.equal(requests.length, 1);
requests[0].onload();
panelElement.classList.remove('collapsed');
await settle();
await nextTick();
assert.equal(requests.length, 2);
assert.equal(requests[1].src, 'b1.jpg');
assert.equal(byId('cctv-frame').dataset.cameraId, 'b');
assert.notEqual(byId('cctv-frame').getAttribute('src'), 'a1.jpg');
});
test('leaving the Cameras sheet stops the live video and coming back starts it again', async (t) => {
const { controls, byId } = panel(t, { video: true });
byId('cctv-panel').classList.remove('collapsed');
document.body.classList.add('mobile-shell');
document.body.setAttribute('data-mobile-sheet', 'cameras');
t.after(() => {
document.body.classList.remove('mobile-shell');
document.body.removeAttribute('data-mobile-sheet');
});
controls._renderCctvState({
enabled: true,
count: 1,
cameraIndex: [camera],
activeCameraId: 'a',
activeCamera: { ...camera, isVideo: true },
});
const first = controls._cctvVideoSurface;
assert.ok(first);
const stop = t.mock.method(first, 'stop');
document.body.setAttribute('data-mobile-sheet', 'layers');
await settle();
assert.equal(stop.mock.callCount(), 1);
assert.equal(controls._cctvVideoSurface, null);
document.body.setAttribute('data-mobile-sheet', 'cameras');
await settle();
assert.ok(controls._cctvVideoSurface);
assert.notEqual(controls._cctvVideoSurface, first);
});
+28 -4
View File
@@ -8,6 +8,15 @@ import {
import { createCctvVideoSurface } from './cctvVideo.js';
import { presentCctvCalibration } from './cctvCalibration.js';
import { roundHeadingDegrees } from '../data/headingDegrees.js';
import {
MOBILE_SHELL_CLASS,
MOBILE_SHEET_ATTR,
sheetForPanelId,
} from './mobileSheets.js';
const CAMERAS_SHEET = sheetForPanelId('cctv-panel');
const CONTEXT_SHEET = sheetForPanelId('global-context-panel');
export function _calBadgeLabel(badge) {
switch (badge) {
case 'calibrated':
@@ -279,11 +288,25 @@ export function _renderCctvState(state) {
const liveIntent =
enabled && !!activeCamera?.isVideo && !activeCamera?.browserMediaUrl;
this.store.setLive(liveIntent);
// A background tab, a collapsed panel or a closed phone sheet shows no
// picture; the observers and visibilitychange render again on showing.
const body = globalThis.document?.body;
const phone = body?.classList.contains(MOBILE_SHELL_CLASS);
const sheet = body?.getAttribute(MOBILE_SHEET_ATTR);
const tabShown = !!body && !document.hidden;
const panelShown =
tabShown &&
!this._cctvPanel?.classList.contains('collapsed') &&
(!phone || sheet === CAMERAS_SHEET);
// Context's camera card shows the same still.
const cardShown =
tabShown &&
this.store.previewCards > 0 &&
(!phone || sheet === CONTEXT_SHEET);
// Its bigger view is a popup over the map, shown on any phone sheet.
const popupShown = tabShown && this.store.previewPopups > 0;
if (this._cctvVideo) {
const visible =
liveIntent &&
!document.hidden &&
!this._cctvPanel?.classList.contains('collapsed');
const visible = liveIntent && panelShown;
if (!visible || this._cctvVideoCameraId !== activeId) {
this._cctvVideoSurface?.stop();
this._cctvVideoSurface = null;
@@ -308,6 +331,7 @@ export function _renderCctvState(state) {
// immediate so navigation never waits on the prior camera's request.
if (
nextSrc &&
(panelShown || cardShown || popupShown) &&
(cameraChanged || (!frameLoading && this._frame.currentSrc !== nextSrc))
) {
this._queueCctvFrame(nextSrc, nextCameraId, cameraChanged);
+281
View File
@@ -0,0 +1,281 @@
import '../testSupport/registerDom.mjs';
import assert from 'node:assert/strict';
import test from 'node:test';
import { createPinia } from 'pinia';
import { createApp, nextTick } from 'vue';
import { CctvControls } from './cctvControls.js';
import { useCctvStore } from './stores/cctv.js';
import CctvPanel from './views/panels/CctvPanel.vue';
import CctvPreview from './views/panels/CctvPreview.vue';
const settle = () => new Promise((r) => setTimeout(r, 0));
const camera = {
id: 'a',
city: 'Austin',
name: 'Congress Ave',
headingDeg: 91.6,
fovDeg: 60,
rangeM: 120.4,
sourceLabel: 'Configured Source',
calBadge: 'curated',
};
const stillState = (frameUrl, id = 'a') => ({
enabled: true,
count: 2,
cameraIndex: [camera, { ...camera, id: 'b' }],
activeCameraId: id,
activeCamera: { ...camera, id, frameUrl, sourceKind: 'snapshot' },
});
function fixture(t, { card = true } = {}) {
document.body.replaceChildren();
const host = document.body.appendChild(document.createElement('div'));
const cardHost = document.body.appendChild(document.createElement('div'));
const pinia = createPinia();
const app = createApp(CctvPanel).use(pinia);
app.mount(host);
let preview;
function mountCard() {
preview = createApp(CctvPreview, { cameraId: 'a' }).use(pinia);
preview.mount(cardHost);
}
function unmountCard() {
preview?.unmount();
preview = null;
}
if (card) mountCard();
const store = useCctvStore(pinia);
const controls = new CctvControls({
elements: {
_cctvPanel: document.getElementById('cctv-panel'),
_cctvFrame: document.getElementById('cctv-frame'),
_cctvFrameWrap: document.getElementById('cctv-frame-wrap'),
},
cctv: {},
actions: {
isEnabled: () => true,
setPanelCollapsed() {},
syncViewport() {},
},
store,
});
t.after(() => {
controls.destroy();
app.unmount();
preview?.unmount();
});
return {
controls,
cardHost,
mountCard,
unmountCard,
store,
panelEl: document.getElementById('cctv-panel'),
};
}
function mockImages(t) {
const prior = globalThis.Image;
const requests = [];
globalThis.Image = class {
constructor() {
requests.push(this);
}
};
t.after(() => {
globalThis.Image = prior;
});
return requests;
}
test('desktop: the Context card keeps refreshing while the accordion folds CCTV', async (t) => {
const requests = mockImages(t);
const { controls, cardHost, panelEl } = fixture(t);
panelEl.classList.remove('collapsed');
controls._renderCctvState(stillState('a1.jpg'));
assert.equal(requests.length, 1);
requests[0].onload();
await settle();
await nextTick();
assert.equal(cardHost.querySelector('img')?.getAttribute('src'), 'a1.jpg');
// Context opens: the desktop accordion folds CCTV (class collapsed).
panelEl.classList.add('collapsed');
await settle();
controls._renderCctvState(stillState('a2.jpg'));
assert.equal(requests.length, 2);
assert.equal(requests[1].src, 'a2.jpg');
requests[1].onload();
controls._renderCctvState(stillState('a3.jpg'));
assert.equal(requests.length, 3);
assert.equal(requests[2].src, 'a3.jpg');
requests[2].onload();
await settle();
await nextTick();
assert.equal(cardHost.querySelector('img')?.getAttribute('src'), 'a3.jpg');
});
test('phone: a camera picked with the Context sheet open gets its still', async (t) => {
const requests = mockImages(t);
t.after(() => {
document.body.classList.remove('mobile-shell');
document.body.removeAttribute('data-mobile-sheet');
});
const { controls, cardHost, panelEl } = fixture(t);
document.body.classList.add('mobile-shell');
document.body.setAttribute('data-mobile-sheet', 'context');
panelEl.classList.remove('collapsed');
controls._renderCctvState(stillState('a1.jpg'));
controls._renderCctvState(stillState('a2.jpg'));
await settle();
await nextTick();
assert.equal(
requests.length,
1,
'the Context card on the Context sheet requests the still',
);
assert.equal(requests[0].src, 'a1.jpg');
requests.at(-1).onload();
await settle();
await nextTick();
assert.ok(
cardHost.querySelector('.cctv-preview__expand'),
'the card shows a frame, not Acquiring frame…',
);
});
test('phone: the card on a closed Context sheet waits', async (t) => {
const requests = mockImages(t);
const { controls, panelEl } = fixture(t);
panelEl.classList.add('collapsed');
document.body.classList.add('mobile-shell');
document.body.setAttribute('data-mobile-sheet', 'layers');
t.after(() => {
document.body.classList.remove('mobile-shell');
document.body.removeAttribute('data-mobile-sheet');
});
controls._renderCctvState(stillState('a1.jpg'));
assert.equal(requests.length, 0);
document.body.setAttribute('data-mobile-sheet', 'context');
await settle();
assert.equal(requests.length, 1);
assert.equal(requests[0].src, 'a1.jpg');
});
test('phone: the bigger view keeps refreshing after the layout turns phone, and stops once closed', async (t) => {
const requests = mockImages(t);
t.after(() => {
document.body.classList.remove('mobile-shell');
document.body.removeAttribute('data-mobile-sheet');
});
const { controls, cardHost, panelEl } = fixture(t);
panelEl.classList.add('collapsed');
controls._renderCctvState(stillState('a1.jpg'));
assert.equal(requests.length, 1);
requests[0].onload();
await settle();
await nextTick();
cardHost.querySelector('.cctv-preview__expand').click();
await settle();
await nextTick();
const popup = document.body.querySelector('.cctv-popup');
assert.ok(popup);
assert.equal(popup.querySelector('img').getAttribute('src'), 'a1.jpg');
document.body.classList.add('mobile-shell');
await settle();
controls._renderCctvState(stillState('a2.jpg'));
await settle();
await nextTick();
assert.ok(document.body.contains(popup));
assert.equal(requests.length, 2);
assert.equal(requests[1].src, 'a2.jpg');
requests[1].onload();
await settle();
await nextTick();
assert.equal(popup.querySelector('img').getAttribute('src'), 'a2.jpg');
popup.querySelector('.cctv-popup__close').click();
await settle();
await nextTick();
assert.equal(document.body.querySelector('.cctv-popup'), null);
controls._renderCctvState(stillState('a3.jpg'));
await settle();
assert.equal(requests.length, 2);
});
test('desktop: a card that mounts asks for the still', async (t) => {
const requests = mockImages(t);
const { controls, panelEl, mountCard } = fixture(t, { card: false });
panelEl.classList.add('collapsed');
controls._renderCctvState(stillState('a1.jpg'));
await settle();
assert.equal(requests.length, 0);
mountCard();
await settle();
await nextTick();
assert.equal(requests.length, 1);
assert.equal(requests[0].src, 'a1.jpg');
});
test('desktop: a card that unmounts stops the still, and a remount resumes it', async (t) => {
const requests = mockImages(t);
const { controls, panelEl, mountCard, unmountCard, store } = fixture(t);
panelEl.classList.add('collapsed');
controls._renderCctvState(stillState('a1.jpg'));
assert.equal(requests.length, 1);
requests[0].onload();
await settle();
await nextTick();
unmountCard();
await settle();
await nextTick();
assert.equal(store.previewCards, 0);
controls._renderCctvState(stillState('a2.jpg'));
await settle();
assert.equal(requests.length, 1);
mountCard();
await settle();
await nextTick();
assert.equal(requests.length, 2);
assert.equal(requests[1].src, 'a2.jpg');
});
test('desktop: the bigger view is released when the card unmounts, also in the tick it closes', async (t) => {
const requests = mockImages(t);
const { controls, cardHost, panelEl, mountCard, unmountCard, store } =
fixture(t);
panelEl.classList.add('collapsed');
controls._renderCctvState(stillState('a1.jpg'));
requests[0].onload();
await settle();
await nextTick();
const openPopup = async () => {
cardHost.querySelector('.cctv-preview__expand').click();
await nextTick();
assert.equal(store.previewPopups, 1);
};
await openPopup();
unmountCard();
await nextTick();
assert.equal(document.body.querySelector('.cctv-popup'), null);
assert.equal(store.previewPopups, 0);
mountCard();
await nextTick();
await openPopup();
// Closed and unmounted before the watcher runs, as when one Escape closes
// the phone's Context sheet and the popup.
document.body.querySelector('.cctv-popup__close').click();
unmountCard();
await settle();
await nextTick();
assert.equal(store.previewPopups, 0);
assert.equal(store.previewCards, 0);
const before = requests.length;
controls._renderCctvState(stillState('a3.jpg'));
await settle();
assert.equal(requests.length, before);
});
+26
View File
@@ -0,0 +1,26 @@
export const MOBILE_SHELL_CLASS = 'mobile-shell';
export const MOBILE_SHEET_ATTR = 'data-mobile-sheet';
/**
* Panels each sheet expands. A sheet also shows its rail's other panels
* collapsed (Scenes under Layers), per styles/mobile-shell.css.
*/
export const MOBILE_SHEET_PANELS = Object.freeze({
layers: Object.freeze(['data-panel']),
cameras: Object.freeze(['cctv-panel', 'street-level-panel']),
context: Object.freeze(['global-context-panel']),
missions: Object.freeze(['space-missions-panel']),
search: Object.freeze(['location-bar']),
more: Object.freeze(['control-panel', 'pp-toggles']),
});
/**
* @param {string} panelId
* @returns {string|null} The sheet that presents `panelId`.
*/
export function sheetForPanelId(panelId) {
for (const [sheet, ids] of Object.entries(MOBILE_SHEET_PANELS)) {
if (ids.includes(panelId)) return sheet;
}
return null;
}
+13 -27
View File
@@ -18,23 +18,20 @@ import {
readPanelState,
} from './rail/panelState.js';
import {
MOBILE_SHELL_CLASS,
MOBILE_SHEET_ATTR,
MOBILE_SHEET_PANELS,
} from './mobileSheets.js';
export {
MOBILE_SHELL_CLASS,
MOBILE_SHEET_ATTR,
MOBILE_SHEET_PANELS,
sheetForPanelId,
} from './mobileSheets.js';
export const MOBILE_SHELL_MEDIA_QUERY = '(max-width: 720px)';
export const MOBILE_SHELL_CLASS = 'mobile-shell';
export const MOBILE_SHEET_ATTR = 'data-mobile-sheet';
/**
* Panels each sheet expands. A sheet also shows its rail's other panels
* collapsed (Scenes under Layers), per styles/mobile-shell.css.
*/
export const MOBILE_SHEET_PANELS = Object.freeze({
layers: Object.freeze(['data-panel']),
cameras: Object.freeze(['cctv-panel', 'street-level-panel']),
context: Object.freeze(['global-context-panel']),
missions: Object.freeze(['space-missions-panel']),
search: Object.freeze(['location-bar']),
more: Object.freeze(['control-panel', 'pp-toggles']),
});
export const MOBILE_TABS = Object.freeze([
Object.freeze({ sheet: 'layers', label: msg('Layers'), icon: 'layers' }),
Object.freeze({ sheet: 'cameras', label: msg('Cameras'), icon: 'videocam' }),
@@ -64,17 +61,6 @@ const BORROWED_PANELS = Object.freeze([
const BORROW_OPTIONS = Object.freeze({ persist: false, syncShare: false });
/**
* @param {string} panelId
* @returns {string|null} The sheet that presents `panelId`.
*/
export function sheetForPanelId(panelId) {
for (const [sheet, ids] of Object.entries(MOBILE_SHEET_PANELS)) {
if (ids.includes(panelId)) return sheet;
}
return null;
}
/**
* The sheet after a tab press: the same tab closes its sheet, another opens.
* @param {string|null} current
+18
View File
@@ -20,6 +20,10 @@ export const useCctvStore = defineStore('gev-cctv', () => {
/** The preview: requested and shown frame, loading and error state. */
const frame = shallowRef(null);
/** Number of camera cards outside the panel showing its preview, including Context's card. */
const previewCards = shallowRef(0);
/** Number of open bigger views of a camera card (popups over the map). */
const previewPopups = shallowRef(0);
/** Whether the live video surface replaces the still frame. */
const live = shallowRef(false);
/** `{label, state}` for the source badge; null until first synced. */
@@ -49,6 +53,16 @@ export const useCctvStore = defineStore('gev-cctv', () => {
frame.value = markRaw(next);
}
/** @param {boolean} shown */
function showPreviewCard(shown) {
previewCards.value = Math.max(0, previewCards.value + (shown ? 1 : -1));
}
/** @param {boolean} shown */
function showPreviewPopup(shown) {
previewPopups.value = Math.max(0, previewPopups.value + (shown ? 1 : -1));
}
/** @param {boolean} on */
function setLive(on) {
live.value = Boolean(on);
@@ -73,6 +87,8 @@ export const useCctvStore = defineStore('gev-cctv', () => {
view,
calEdit,
frame,
previewCards,
previewPopups,
live,
sourceBadge,
summary,
@@ -80,6 +96,8 @@ export const useCctvStore = defineStore('gev-cctv', () => {
publish,
setCalEdit,
setFrame,
showPreviewCard,
showPreviewPopup,
setLive,
setSourceBadge,
setSummary,
+15 -6
View File
@@ -1,5 +1,5 @@
<script setup>
import { computed, onBeforeUnmount, ref, watch } from 'vue';
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { t } from '../../../i18n/index.js';
import { useCctvStore } from '../../stores/cctv.js';
@@ -16,7 +16,8 @@ const props = defineProps({
cameraId: { type: String, default: '' },
});
const { view, frame, sourceBadge } = storeToRefs(useCctvStore());
const cctv = useCctvStore();
const { view, frame, sourceBadge } = storeToRefs(cctv);
const chrome = usePanelChromeStore();
const { panels } = storeToRefs(chrome);
@@ -53,11 +54,19 @@ const big = ref(false);
const onKey = (e) => {
if (e.key === 'Escape') big.value = false;
};
watch(big, (open) => {
if (open) document.addEventListener('keydown', onKey);
else document.removeEventListener('keydown', onKey);
// The cleanup also runs when the card unmounts, even if `big` turned false in
// the same tick and the watcher never saw it.
watch(big, (open, _, onCleanup) => {
if (!open) return;
cctv.showPreviewPopup(true);
document.addEventListener('keydown', onKey);
onCleanup(() => {
cctv.showPreviewPopup(false);
document.removeEventListener('keydown', onKey);
});
});
onBeforeUnmount(() => document.removeEventListener('keydown', onKey));
onMounted(() => cctv.showPreviewCard(true));
onBeforeUnmount(() => cctv.showPreviewCard(false));
function openPanel() {
if (panels.value['cctv-panel']?.collapsed !== false) chrome.act('toggle', 'cctv-panel');