Skip to content

A spy satellite simulator in your browser, except the data is real. Live open source spatial intelligence on a photorealistic 3D globe.

Merge origin/main: Google Street View, KartaView and Panoramax on the slim Street Level

German Khokhlov6390a3346ff2
diff --cc CHANGELOG.md
index 93d536677,98d32365f..0ad3a7368
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -99,6 -308,82 +308,81 @@@
The parser skips the incomplete set and resumes at the next complete named
set, instead of losing the rest of the group (#906).
+ - Satellite clouds keep Clouds only / Full as quick endpoints and add a continuous
+ cloud-filter slider: 0% is Full, 100% is the existing brightness key, and
+ intermediate values blend the keyed alpha. The slider commits on release to
+ avoid restaging imagery for every drag event. Filter percentages round-trip in
+ share links; legacy mode codes retain their old endpoint meanings. Background
+ panel refreshes preserve the pending drag value until release. Contributed by
+ [NotProniss](https://github.com/NotProniss) (#1084).
+
+ - Street Level: Panoramax is the fourth provider, keyless. Light its chip
- (orange; off by default, one provider at a time): from orbit dots show
- where the federated commons has pictures, and below about 60 km its
- sequences draw as lines from `api.panoramax.xyz` vector tiles. A click on a
++ (orange; off by default, one provider at a time): below about 60 km the
++ federated commons' sequences draw as lines from `api.panoramax.xyz` vector tiles. A click on a
+ line opens that sequence's picture nearest the click without moving the
+ camera, flat or 360°, with cones along the sequence around it and ‹ › /
+ ← → following the picture's own links. The 360° and since filters apply,
+ in the lines and in the lookup. The caption names each picture's author
+ and licence (CC BY-SA 4.0, Licence Ouverte 2.0…) and links to it in the
+ Panoramax viewer. HD originals load once, only when the viewer is wider
+ than the 2,048 px version (a panorama: expanded), and every download stops
+ when the photo changes; an image whose header declares more than 64 MP is
+ refused before it decodes. Share links carry it as
+ `0.m.0_0.r.google-0*kartaview-0*panoramax-1` (`0.m.0_0.r.panoramax-1` works
+ too). KartaView's photo viewer
+ is now shared (`photoViewer.js`, `panorama.js`); in it, for KartaView too,
+ Esc clears the selected drive before it collapses the panel. Lines are
+ simplified and drawn within a point budget (a tile's unsimplified lines
+ over Paris hung the tab), decoded in slices so the globe keeps moving,
+ and kept; the cones' tiles have their own connection, and the open
+ picture's tile draws its cones before its neighbours arrive.
+
+ - Flights and Military Flights highlight emergency transponder broadcasts in
+ fleet billboards, 3D models and Cockpit contacts. Colors update when a status
+ starts or clears. Emergency squawks outrank ADS-B priority statuses; GEV
+ reports minimum fuel and lifeguard without red tint. Cockpit names the code
+ or ADS-B status, and analyst/voice results retain broadcast provenance and
+ the latest known contact time. One omitted ADS-B status poll during a source
+ switch may retain the previous status if the squawk is unchanged; an explicit
+ clear takes effect immediately. Broadcasts are not confirmed incidents.
+ Contributed by [Leo Pechnicki](https://github.com/leopechnicki) (#856).
+
+ - Street Level: KartaView is the third provider, keyless. Light its chip
+ (purple; off by default, one provider at a time) and zoom in below about
+ 6 km: the lines are the streets KartaView has photos of (z13–14 tiles from
+ `api.kartaview.org`). A click on a line opens the photo nearest the click
+ without moving the camera, flat or 360° (a small WebGL panorama: drag to
+ look, wheel to zoom), with cones along its drive and ‹ › / ← → to step
+ through it. The caption links to the full-size photo (KartaView's photo
+ pages fail for signed-out visitors), and the globe credits "© KartaView
+ contributors, CC BY-SA 4.0". Share links carry it in the provider
+ switches (`0.m.0_0.r.google-0*kartaview-1`). Archived photos (KartaView
+ answers 409) are skipped by the click and by ‹ ›. Shift+← →, ↑ ↓, + − and
+ pinch look around a 360° photo. The open photo's marker is a purple view
+ cone pointing along the drive (KartaView's own compass headings are often
+ 0 or far off). The IMAGERY (ALL / 360° / FLAT) and SINCE filters apply to
+ KartaView as to Mapillary: its lines are filtered by KartaView's own
+ server (its filtered PNG tiles, as a mask over the JSON lines), and the
+ photo a click opens, and the cones, by each photo's projection and upload
+ date. KartaView's SINCE is the upload date (all its server can filter by);
+ a note under the slider says so while KartaView is lit (`sinceBasis:
+ 'upload'` in the provider contract).
+ Mapillary's line coverage and sequence cones are now shared by both
+ (`lineCoverage.js`, `sequenceCones.js`).
+
+ - Street Level: Google Street View is the second provider. On the Google 3D
+ map (Google's terms keep it off other maps), light its chip (off by
+ default: every panorama is billed to the Google Maps key, which needs the
+ Maps JavaScript API) and click a street, or press OPEN STREET VIEW, to
+ open Google's own panorama in
+ the panel, with its arrows, the address and month in the caption, a link
- to Google Maps and FOLLOW. Share links carry it in the provider switches
++ to Google Maps. Share links carry it in the provider switches
+ (`r.google-1`). One provider is lit at a time (lighting one switches the
+ other off), Mapillary by default since it is free. Street View's panoramas
- are all 360°, so the IMAGERY and SINCE filters and the legend apply to
++ are all 360°, so the IMAGERY and SINCE filters apply to
+ Mapillary only and hide while GOOGLE STREET VIEW is lit; its globe marker
+ is a Google-blue view cone.
+
- Add an experimental ChatGPT/Codex OAuth option for cloud voice in Provider
Settings. API-key voice remains the default. Local sign-in can start from
the auth button and reports completion, failure, timeout, or expired
@@@ -119,17 -419,33 +418,28 @@@
proposed diagnosis in #927, and [kvnloo](https://github.com/kvnloo) for identifying
the repair race. Windows/Claude Desktop Cowork confirmation remains outstanding.
-- Street Level: a street-level imagery layer modelled on the iD editor's photo
- overlay, with Mapillary as its first provider (free client token, CC BY-SA 4.0
- imagery). One right-rail panel holds a chip per provider, shared 360°/flat and
- captured-since filters, and an embedded viewer with EXPAND, FIT/FILL and
- FOLLOW (Google 3D only). Coverage lines and image cones are drawn from orbit
- down to a single street; on Google 3D they sit on the bare earth, refined
- against the rendered mesh near the camera, so trees and buildings hide them.
- Share links carry the provider switches, the filters and the panel's collapsed
- state. A server proxy caches Mapillary coverage tiles (24 h, 1 GiB on disk),
- refuses cross-site requests, rate-limits per IP and backs off when Mapillary
- rejects the token or rate-limits.
-
-- The CCTV and Street Level panels are portable: drag the header to float the
- panel, resize it from any edge or corner, and double-click the header to dock
- it again. The position persists across reloads.
+- Street Level: street-level imagery from providers, Mapillary first (free
+ client token, CC BY-SA 4.0). A right-rail panel holds a chip per provider,
+ 360°/flat and captured-since filters and an embedded viewer with EXPAND and
+ FIT/FILL. Coverage lines (below 60 km) and image cones drape on terrain and
+ Google 3D tiles; opening a photo frames it with one camera flight. Share
+ links carry the provider switches, the filters and the panel's collapsed
+ state. A server proxy adds the token to Mapillary coverage tiles, trims and
+ caches them for 24 h, refuses cross-site requests and redirects, and limits
+ load per IP and upstream. The panel reads KEY REQUIRED without a token and
+ KEY REJECTED when Mapillary refuses it.
+ - Add Norway's city bikes to the Bike Share layer: Oslo, Bergen and
+ Trondheim Bysykkel (Urban Sharing), Kolumbus Bysykkel in Stavanger and
+ Farte Bysykkel in Skien/Porsgrunn (Entur Mobility), and Bysykkel
+ Lillestrøm (JCDecaux), about 760 stations in all. Every feed is keyless
+ GBFS. `gbfs.urbansharing.com`, `api.entur.io` and `api.cyclocity.fr` join
+ the proxy allowlist; the last two are kept to their GBFS paths. The proxy
+ now sends `Client-Identifier: gods-eye-view` on every request and
+ `ET-Client-Name: gods-eye-view-bikeshare` to Entur, as the operators ask,
+ and accepts Entur's extensionless feed paths. Attributed under NLOD and
+ Licence Ouverte. `get_bike_share` covers the six systems too.
+
- Add Norway's road cameras from Statens vegvesen as a CCTV pack. The camera
list is one keyless GeoJSON request to the agency's OGC API view of its
DATEX 3.1 CCTV table, so no DATEX account is needed. Every working camera
diff --cc CONTRIBUTING.md
index 7e1adaf67,ba0d38768..442b9c1bf
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@@ -54,8 -54,9 +54,8 @@@ head -40 scripts/qa-radio.mjs # what t
Runnable gate entrypoints document what they assert and how to invoke them.
Most need a dev server; some also need a specific provider key or port. Follow
the entrypoint's header rather than assuming every matching file accepts the
- same arguments. Only a couple (`qa:map-source-tray`, `qa:transit`) have an
- `npm run` alias.
-same arguments. Five have an `npm run` alias: `qa:map-source-tray`,
-`qa:panel-resize`, `qa:street-level`, `qa:street-level:fixtures` and
-`qa:transit`.
++same arguments. Four have an `npm run` alias: `qa:map-source-tray`,
++`qa:street-level`, `qa:street-level:fixtures` and `qa:transit`.
If you aren't sure which gate covers your change, search `docs/CURRENT-STATE.md`
for the feature: it names the gate for many of them, and it's the authoritative
@@@ -63,12 -64,13 +63,12 @@@ runtime reference either way. `scripts/
release-candidate checks and selected harnesses; it does not replace the focused
gate for the feature you changed.
- > **CI does not cover this for you.** The workflow runs the setup policy
+ > **CI covers only two of these for you.** The workflow runs the setup policy
> checks, the formatting and package-boundary checks, the unit suite and the
-> production build, plus a Windows onboarding job, and against the built preview
-> it runs `qa:street-level:fixtures` and `qa:panel-resize`. It does not run
-> `npm run test:track` or any other `qa-*.mjs` gate — those need a live dev
-> server and a browser. Include the applicable local run in your PR's
-> validation evidence.
+> production build, plus a Windows onboarding job. It runs neither
+> `npm run test:track` nor any `qa-*.mjs` gate except the Street Level fixture
+> gate (`street-level-browser` job) — they need a live dev server and a
+> browser. Include the applicable local run in your PR's validation evidence.
## Share-link layer tokens
diff --cc DATA_SOURCES.md
index 9a667c8aa,d930bcb8f..37bbfeea1
--- a/DATA_SOURCES.md
+++ b/DATA_SOURCES.md
@@@ -20,7 -20,10 +20,10 @@@ How to read this
| **NOAA nowCOAST observed weather** (`nowcoast.noaa.gov/geoserver/observations/{weather_radar,satellite}/ows`, WMS 1.1.1) | Rain radar (MRMS base reflectivity, contiguous US, about 4-minute updates) and Satellite clouds (GOES-19/18 Band 14 regional infrared, about 5-minute updates; global infrared mosaic, hourly). Keyless; layer metadata refreshed every 2 minutes, exact-time images cached for up to 24 hours | [NOAA disclaimer](https://oceanservice.noaa.gov/disclaimer.html) | "NOAA nowCOAST · NWS/OAR MRMS radar; NESDIS GOES and global satellite partners" |
| **NOAA nowCOAST lightning density** (`nowcoast.noaa.gov/geoserver/observations/lightning_detection/ows`) | Lightning density: 15-minute accumulated strike density on an approximately 8 km grid, Americas and Pacific. Keyless; layer metadata refreshed every 10 minutes, exact-time images cached for up to 24 hours | NOAA Level-5 derived product from Vaisala NLDN/GLD360; the [product description](https://ocean.weather.gov/lightning/lightning_pdd.php) permits public distribution of this density product, not of raw Vaisala detections | "NOAA/NWS nowCOAST; derived from Vaisala NLDN/GLD360" |
| **NOAA NHC / CPHC advisories** (`www.nhc.noaa.gov/CurrentStorms.json` + the `mapservices.weather.noaa.gov` tropical weather summary MapServer) | Cyclone advisories: storm positions, forecast tracks, points and cones for the Atlantic and eastern/central North Pacific. Keyless through `/api/cyclones`; cached for 5 minutes | [NWS public-data terms](https://www.weather.gov/disclaimer); no endorsement implied | "NOAA/NWS NHC / CPHC" |
- | **Mapillary** (vector tiles, Graph API, MapillaryJS) | Street Level: coverage lines, image cones and the embedded viewer. Coverage tiles kept in server memory for 24 h | Imagery [CC BY-SA 4.0](https://www.mapillary.com/terms); API under the Mapillary terms with a client token | "© Mapillary contributors, CC BY-SA 4.0", shown on the globe while the layer is on |
-| **Mapillary** (vector tiles, Graph API, MapillaryJS) | Street Level: coverage lines, image cones and the embedded viewer. Coverage tiles cached for 24 h | Imagery [CC BY-SA 4.0](https://www.mapillary.com/terms); API under the Mapillary terms with a client token | "© Mapillary contributors, CC BY-SA 4.0", shown on the globe while the provider is on |
++| **Mapillary** (vector tiles, Graph API, MapillaryJS) | Street Level: coverage lines, image cones and the embedded viewer. Coverage tiles kept in server memory for 24 h | Imagery [CC BY-SA 4.0](https://www.mapillary.com/terms); API under the Mapillary terms with a client token | "© Mapillary contributors, CC BY-SA 4.0", shown on the globe while the provider is on |
+ | **Google Street View** (Maps JavaScript API) | Street Level, on the Google 3D map only (Google's terms): Google's panorama viewer and nearest-panorama lookups; panorama dates and addresses kept for the session only | Google Maps Platform ToS (your own key + billing; every panorama load is billed) | "Street View imagery © Google" on the globe while the provider is on, and Google's logo and terms in the viewer |
+ | **KartaView** (`api.kartaview.org` coverage tiles and photo API, `cdn.kartaview.org` image proxy, `storage*.openstreetcam.org` photos) | Street Level: coverage lines (z13–14 JSON tiles; with the imagery filter on, KartaView's filtered PNG tiles as a mask), nearest-photo lookups, the photo's sequence and the photo itself, fetched by the browser. Keyless; nothing cached beyond the session | Imagery [CC BY-SA 4.0](https://kartaview.org/terms) (KartaView terms §4); the public API needs no token | "© KartaView contributors, CC BY-SA 4.0", shown on the globe while the provider is on |
-| **Panoramax** (`api.panoramax.xyz` meta-catalogue: vector tiles and STAC search; pictures from the federated instance holding each one, e.g. `panoramax.openstreetmap.fr`, `panoramax.ign.fr`) | Street Level: coverage lines and density points, nearest-picture lookups, a sequence's pictures as cones, and the picture itself, fetched by the browser. Keyless; tiles cached by the browser for an hour (the API's own header) | Per picture: mostly [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/), IGN's [Licence Ouverte 2.0](https://www.etalab.gouv.fr/licence-ouverte-open-licence/); the API needs no token | "© Panoramax contributors, licence per picture" on the globe while the provider is on; the caption names each picture's author and licence |
++| **Panoramax** (`api.panoramax.xyz` meta-catalogue: vector tiles and STAC search; pictures from the federated instance holding each one, e.g. `panoramax.openstreetmap.fr`, `panoramax.ign.fr`) | Street Level: coverage lines, nearest-picture lookups, a sequence's pictures as cones, and the picture itself, fetched by the browser. Keyless; tiles cached by the browser for an hour (the API's own header) | Per picture: mostly [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/), IGN's [Licence Ouverte 2.0](https://www.etalab.gouv.fr/licence-ouverte-open-licence/); the API needs no token | "© Panoramax contributors, licence per picture" on the globe while the provider is on; the caption names each picture's author and licence |
| **OpenStreetMap** | Map and place data (roads, military areas and names, ALPR, place search, outlines); via vector tiles, hourly ALPR extract, bundled data, Nominatim and optional self-configured Overpass | [ODbL 1.0](https://opendatacommons.org/licenses/odbl/1-0/) | © OpenStreetMap contributors |
| **Google Map Tiles API** (Photorealistic 3D Tiles) + Places/Geocoding | The 3D globe, voice scene context, and on-demand nearby installation search | Google Maps Platform ToS (proprietary, your own key + billing) | "Google" / "Google Maps" logo — **shown in-app**, required |
| **OpenSky Network** | Primary worldwide live-flight snapshot | Non-commercial research/education license | Schäfer et al., _"Bringing Up OpenSky"_, IPSN 2014 + opensky-network.org |
diff --cc README.md
index bef20d281,c49c53ece..39eed1de4
--- a/README.md
+++ b/README.md
@@@ -299,12 -375,13 +375,13 @@@ Twenty layers and map sources. **Eighte
| 🚢 **Live Vessels** | Thousands of ships worldwide | AISStream | 🟡 |
| 🛰️ **Satellites** | 838-object catalog, color-coded by class with a live legend — the **DENSE** chip drops in the whole Starlink shell | CelesTrak | 🟢 |
| 🌍 **Earthquakes** | Global seismic activity, last 24h | USGS | 🟢 |
+ | ◍ **Air quality** | Live AQHI on the published 1–10+ health-risk scale, with a Weather-panel card showing the band legend and the highest readings in view. **Canada only** — ECCC is the first registered provider | ECCC MSC GeoMet | 🟢 |
| 🚗 **Traffic** | Simulated vehicles on OSM roads. With TomTom, live flow speeds drive the simulation and congestion colors below ~8 km; individual vehicle positions are not live observations | TomTom + OSM | 🟢 simulation · 🟡 live flow speeds |
- | 📹 **CCTV Mesh** | ~3,900 public cameras projected _into_ the 3D space — Austin · Texas (TxDOT) · California (Caltrans) · London (TfL) · Ontario (511) · Finland (Fintraffic) · British Columbia (DriveBC) · Estonia (Tallinn, Tarktee) · Delaware (DelDOT live video) · New South Wales (Live Traffic NSW) · Calgary · Norway (Statens vegvesen). Positions are published; poses are estimated priors **you calibrate by dragging a gizmo on the camera itself** | City APIs | 🟢 |
+ | 📹 **CCTV Mesh** | ~4,000 public cameras (shared cap) projected _into_ the 3D space — Austin · Texas (TxDOT) · California (Caltrans) · London (TfL) · Ontario (511) · Finland (Fintraffic) · British Columbia (DriveBC) · Estonia (Tallinn, Tarktee) · Delaware (DelDOT live video) · New South Wales (Live Traffic NSW) · Calgary · Norway (Statens vegvesen) · Toronto · King County (WA) · Washington (WSDOT) · Catalonia (Servei Català de Trànsit), plus opt-in New York City (NYC DOT TMC, needs your own NYC DOT agreement) and opt-in Lithuania (Via Lietuva / Eismoinfo, photo licence unconfirmed). Positions are published; poses are estimated priors **you calibrate by dragging a gizmo on the camera itself** | City APIs | 🟢 |
| 📷 **Mapped ALPR Cameras** | License-plate-reader camera locations tagged by OpenStreetMap contributors, loaded one city-sized view at a time, with **SHOW NEAREST**. Locations and tags only: no plate data, no video | OpenStreetMap (incl. DeFlock mapping) | 🟢 |
- | 📷 **Street Level** | Mapillary street-level photos in one panel: coverage on the streets, image cones and an embedded viewer with full-screen **EXPAND** | Mapillary | 🟡 Mapillary client token |
-| 📷 **Street Level** | Street-level photos behind one panel, one chip per provider: coverage on the streets, image cones, an embedded viewer and **FOLLOW**. Mapillary, Google Street View, KartaView and Panoramax | Mapillary · Google · KartaView · Panoramax | 🟢 KartaView, Panoramax · 🟡 Mapillary token · 🔴 Google Maps key |
++| 📷 **Street Level** | Street-level photos behind one panel, one chip per provider: coverage on the streets, image cones, an embedded viewer with full-screen **EXPAND**. Mapillary, Google Street View, KartaView and Panoramax | Mapillary · Google · KartaView · Panoramax | 🟢 KartaView, Panoramax · 🟡 Mapillary token · 🔴 Google Maps key |
| 📻 **Radio** | Geolocated world radio with an **analog tuner** — drag the needle across up to 750 stations and the globe flies to each broadcaster | Radio Browser / broadcasters | 🟢 |
- | 🚌 **Transit** | Live buses, trams, metros, trains and ferries with delayed playback between reports, selected-vehicle trails, and mode-coloured DETECT labels — Boston, Austin, Minneapolis, Helsinki, the Netherlands, Norway, South East Queensland | Operator GTFS-Realtime feeds | 🟢 |
+ | 🚌 **Transit** | Live buses, trams, metros, trains and ferries with delayed playback between reports, selected-vehicle trails, and mode-coloured DETECT labels — Boston, Austin, Minneapolis, Helsinki, the Netherlands, Norway, South East Queensland, and nine in Ontario: Toronto (surface vehicles; the subway publishes no positions), Mississauga, Hamilton, Durham Region, York Region, Guelph, Burlington, Barrie and Kingston | Operator GTFS-Realtime feeds | 🟢 |
| 🚲 **Bikeshare** | Live station availability | GBFS | 🟢 |
| 🧭 **Directions** | Click A and B on the globe for a street-following drive, walk or cycle route draped on the terrain with turn-by-turn steps — then FLY the camera along it. No key, no geocoder, no mic | OSRM on FOSSGIS servers (OpenStreetMap) | 🟢 |
| 🔥 **Active Fires** | Live NASA FIRMS detections, trailing 24h | NASA FIRMS | 🟡 |
@@@ -340,13 -417,13 +417,13 @@@ _The Space Missions layer replaying a F
## 📷 Street Level
- > Street-level photos from **Mapillary** in one panel. It needs a free client token.
+ > Street-level photos from any provider in one panel. This build ships **Mapillary** (a free client token), **Google Street View** (your Google Maps key), **KartaView** and **Panoramax** (no key).
- **Setup.** At [mapillary.com/dashboard/developers](https://www.mapillary.com/dashboard/developers), register an application with **Read** access and copy its **Client Token** (`MLY|…`). Paste it into **POWER UP → Mapillary**, or set `MAPILLARY_CLIENT_TOKEN` in `.env` and restart. Without it the panel reads **KEY REQUIRED**.
+ **Setup.** At [mapillary.com/dashboard/developers](https://www.mapillary.com/dashboard/developers), register an application with **Read** access and copy its **Client Token** (`MLY|…`). Paste it into **POWER UP → Mapillary**, or set `MAPILLARY_CLIENT_TOKEN` in `.env` and restart. Without it the panel reads **KEY REQUIRED**. **Google Street View** uses `GOOGLE_MAPS_API_KEY` with the **Maps JavaScript API** enabled for it in Google Cloud; its chip starts off, since every panorama is billed to the key. **KartaView** and **Panoramax** need nothing: their public APIs are keyless.
- **Use.** Turn on **Street Level** under DATA LAYERS → Cameras, or with the pill in the STREET LEVEL panel header. Zoom in to street level (below 60 km) for the green coverage lines; from orbit the panel says to zoom in. The **IMAGERY** (ALL / 360° / FLAT) and **SINCE** filters narrow the lines and cones. Click a coverage line for its image cones and a cone to open the photo. Above the photo: **EXPAND** (full screen; Esc leaves) and **FIT / FILL**. The caption links to the image on mapillary.com, and the globe credits "© Mapillary contributors, CC BY-SA 4.0" while the layer is on.
-**Use.** Turn on **Street Level** under DATA LAYERS → Cameras, or with the pill in the STREET LEVEL panel header. Each provider has a chip in its own colour (Mapillary green), and one is lit at a time: lighting one switches the others off. Mapillary, which is free, is lit by default. The **IMAGERY** (ALL / 360° / FLAT) and **SINCE** filters apply to Mapillary, KartaView and Panoramax; Street View panoramas are all 360°, so with Street View lit the filters and legend are hidden. Click a coverage line for its image cones and a cone to open the photo. Light **KARTAVIEW** (purple) and zoom in below about 6 km: its lines are the streets KartaView has photos of, and a click on one opens the photo nearest the click, flat or 360° (drag to look around), with cones along its drive; **‹ ›** or ← → step through the drive (Shift+← →, ↑ ↓ and + − look around a 360° photo; pinch zooms on a phone). Photos KartaView has archived are skipped, and where all are archived the panel says so. For KartaView, **SINCE** goes by upload date, as KartaView's own map does (it can filter by nothing else), and the panel notes it under the slider; KartaView filters its lines on its own server, and a filtered area KartaView has not drawn before can take several seconds, and the unfiltered lines show meanwhile. Light **PANORAMAX** (orange) for the open, federated commons (strongest in France and Belgium): from orbit its dots show where it has pictures, and below about 60 km its lines are sequences. A click on a line opens that sequence's picture nearest the click without moving the camera, flat or 360°, with cones along the sequence around it; **‹ ›** or ← → step through it, and both filters apply. Its caption names the picture's authors (or the instance holding it) and licence (mostly CC BY-SA 4.0; pictures on the IGN instance are Licence Ouverte 2.0). On the **Google 3D** map (Google's terms keep Street View off other maps, where it does not appear), light **GOOGLE STREET VIEW** and click a street from below 3 km, or press **OPEN STREET VIEW** for the view centre, to open Google's panorama there; step along its arrows. Above the photo: **EXPAND**, **FIT / FILL** (Mapillary, and flat KartaView and Panoramax photos), and **FOLLOW** (the globe camera follows the photo's view; Google 3D map only). The caption links to the image on the provider's site, and the globe credits each provider that is on ("© Mapillary contributors, CC BY-SA 4.0", "Street View imagery © Google", "© KartaView contributors, CC BY-SA 4.0", "© Panoramax contributors, licence per picture"). KartaView's own photo pages fail for signed-out visitors, so its link opens the full-size photo.
++**Use.** Turn on **Street Level** under DATA LAYERS → Cameras, or with the pill in the STREET LEVEL panel header. Each provider has a chip in its own colour (Mapillary green), and one is lit at a time: lighting one switches the others off. Mapillary, which is free, is lit by default. Zoom in to street level (below 60 km) for the coverage lines; from orbit the panel says to zoom in. The **IMAGERY** (ALL / 360° / FLAT) and **SINCE** filters apply to Mapillary, KartaView and Panoramax; Street View panoramas are all 360°, so with Street View lit the filters are hidden. Click a coverage line for its image cones and a cone to open the photo. Light **KARTAVIEW** (purple) and zoom in below about 6 km: its lines are the streets KartaView has photos of, and a click on one opens the photo nearest the click, flat or 360° (drag to look around), with cones along its drive; **‹ ›** or ← → step through the drive (Shift+← →, ↑ ↓ and + − look around a 360° photo; pinch zooms on a phone). Photos KartaView has archived are skipped, and where all are archived the panel says so. For KartaView, **SINCE** goes by upload date, as KartaView's own map does (it can filter by nothing else), and the panel notes it under the slider; KartaView filters its lines on its own server, and a filtered area KartaView has not drawn before can take several seconds. Light **PANORAMAX** (orange) for the open, federated commons (strongest in France and Belgium): below about 60 km its lines are sequences. A click on a line opens that sequence's picture nearest the click without moving the camera, flat or 360°, with cones along the sequence around it; **‹ ›** or ← → step through it, and both filters apply. Its caption names the picture's authors (or the instance holding it) and licence (mostly CC BY-SA 4.0; pictures on the IGN instance are Licence Ouverte 2.0). On the **Google 3D** map (Google's terms keep Street View off other maps, where it does not appear), light **GOOGLE STREET VIEW** and click a street from below 3 km, or press **OPEN STREET VIEW** for the view centre, to open Google's panorama there; step along its arrows. Above the photo: **EXPAND** (full screen; Esc leaves) and **FIT / FILL** (Mapillary, and flat KartaView and Panoramax photos). The caption links to the image on the provider's site, and the globe credits each provider that is on ("© Mapillary contributors, CC BY-SA 4.0", "Street View imagery © Google", "© KartaView contributors, CC BY-SA 4.0", "© Panoramax contributors, licence per picture"). KartaView's own photo pages fail for signed-out visitors, so its link opens the full-size photo.
- Share links carry the Mapillary switch and the filters (`0.m.0` Mapillary off, `0.p.p` panoramas only, `0.s.365` the last year).
-Drag the panel header to float the panel, and resize it from any edge. Double-click the header or collapse it to put it back in the rail. Share links carry the provider switches and filters (`0.m.0` Mapillary off, `0.m.0_0.r.google-1` Street View on, `0.m.0_0.r.google-0*kartaview-1*panoramax-0` KartaView on and `0.m.0_0.r.google-0*kartaview-0*panoramax-1` Panoramax on, as the app writes them (`0.m.0_0.r.kartaview-1` and `0.m.0_0.r.panoramax-1` work too; a link that leaves out `m` keeps Mapillary, the default, lit), `0.p.p` panoramas only, `0.s.365` the last year). To add a provider, implement the contract in `src/layers/streetLevel/registry.js` and register it in `src/app/layers/streetLevel.js`.
++Share links carry the provider switches and filters (`0.m.0` Mapillary off, `0.m.0_0.r.google-1` Street View on, `0.m.0_0.r.google-0*kartaview-1*panoramax-0` KartaView on and `0.m.0_0.r.google-0*kartaview-0*panoramax-1` Panoramax on, as the app writes them (`0.m.0_0.r.kartaview-1` and `0.m.0_0.r.panoramax-1` work too; a link that leaves out `m` keeps Mapillary, the default, lit), `0.p.p` panoramas only, `0.s.365` the last year). To add a provider, implement the contract in `src/layers/streetLevel/registry.js` and register it in `src/app/layers/streetLevel.js`.
## 🎖️ Field Missions
diff --cc SECURITY.md
index f74f08ad8,e53883548..8db2f5446
--- a/SECURITY.md
+++ b/SECURITY.md
@@@ -27,9 -27,9 +27,9 @@@ The golden rule: **secret-bearing API k
These are designed to be used directly in the browser (like a Mapbox public token). They are injected into the client bundle via Vite's `define`, so they **will** be visible in browser devtools. Scope and restrict them rather than trying to hide them:
- 1. **Google Maps API key** — loads Photorealistic 3D Tiles directly and powers GEV place search. **Restrict it** (HTTP referrer + API restriction to the required Google APIs) in the Google Cloud Console. An unrestricted key in a public deployment can be abused and billed to you.
+ 1. **Google Maps API key** — loads Photorealistic 3D Tiles directly and powers Street View (Maps JavaScript API; add it to the key's API restrictions). **Restrict it** (HTTP referrer + API restriction to the required Google APIs) in the Google Cloud Console. An unrestricted key in a public deployment can be abused and billed to you. Restrict it to the **Map Tiles API and Maps JavaScript API only**: a referrer restriction applies to the Maps JavaScript API and the client SDKs, not to the web services, so a key carrying Geocoding under one is refused with `API keys with referer restrictions cannot be used with this API`. Search does not need it — geocoding goes through the server proxies above (#363).
2. **Cesium ion token** (`CESIUM_ION_TOKEN`, optional — for ion-hosted Google Photorealistic 3D Tiles, Bing world imagery, and world terrain) — used as `Cesium.Ion.defaultAccessToken` client-side. Use a public **`assets:read`** token with **URL restrictions** for any hosted deployment. The Community plan has eligibility and usage limits; a public token is not a secret, but it can still consume the account's quota.
-3. **Mapillary client token** (`MAPILLARY_CLIENT_TOKEN`, optional, Street Level) — used by the MapillaryJS viewer and Graph API lookups in the browser, and by the server's coverage-tile proxy. Mapillary client tokens are meant for browser use.
+3. **Mapillary client token** (`MAPILLARY_CLIENT_TOKEN`, optional, Street Level) — used by the MapillaryJS viewer and Graph API lookups in the browser, and by the server's coverage-tile proxy, which sends it only to `tiles.mapillary.com` over HTTPS (an upstream redirect is refused and answered 502, never followed) and caches tiles in memory only. Mapillary client tokens are meant for browser use.
> The explicit browser `define` block in `build/vite.js` controls exactly what reaches the client: only these three keys. Everything else stays server-side.
diff --cc docs/CURRENT-STATE.md
index 9dfad2848,9562dc9f5..314c9b668
--- a/docs/CURRENT-STATE.md
+++ b/docs/CURRENT-STATE.md
@@@ -3067,60 -3404,331 +3404,321 @@@ its criteria cannot be silently ignored
| Dams ▰ | OpenInfraMap/OSM extract (bundled) | `src/data/localLayers.js` | — | static |
| Submarine Cables ◠ | TeleGeography public map (bundled) | `src/data/telegeographySubmarineCables.js` | — | static |
| FIRMS Active Fires ▲ | NASA FIRMS live (VIIRS ×3 NRT + MODIS NRT, trailing 24h) | `src/data/firmsHeatmap.js` | `/api/firms` (`FIRMS_MAP_KEY`) | 10 min (proxy TTL 30 min) |
-| Street Level 📷 | Street-level imagery; Mapillary is the first provider (vector tiles, Graph API, MapillaryJS) | `src/layers/streetLevel/` via `src/app/layers/streetLevel.js` | `/api/mapillary/status`, `/api/mapillary/tiles/coverage/{z}/{x}/{y}` (`MAPILLARY_CLIENT_TOKEN`) | camera-driven (320 ms debounce, ≤9 tiles, cached 24 h) |
+| Street Level 📷 | Mapillary street-level imagery (vector tiles, Graph API, MapillaryJS) | `src/layers/streetLevel/` via `src/app/layers/streetLevel.js` | `/api/mapillary/status`, `/api/mapillary/tiles/coverage/{z}/{x}/{y}` (`MAPILLARY_CLIENT_TOKEN`) | camera-driven (320 ms debounce, ≤9 tiles, server memory cache 24 h) |
| Wind 🌬 | NOAA GFS 10 m wind (keyless, 0.25°→1° grid; animated particles) | `src/data/wind.js` | `/api/wind` | 1 h (forecast cycle) |
+ | GNSS Integrity 📡 (`gnss-integrity`) | adsb.lol point snapshot, low navigation accuracy binned per 0.5° cell (GEV NIC/NACp threshold + gpsjam.org formula and bands, keyless, ODbL) | `src/layers/gnss/` via `src/app/layers/gnss.js` | `/api/gnss-integrity` | camera-driven (600 ms debounce, minimum 2.5 s between reads) + 60s poll (server cache 60 s; 30 min rolling window) |
| Fire Perimeters 🔥 | NIFC WFIGS current interagency perimeters (keyless, paged past the 2000-record cap); InciWeb catalog + incident page origin and update time checks for verified incident-page links | `src/layers/perimeters/` via `src/app/layers/perimeters.js` | `/api/fire-perimeters` + `/api/fire-perimeters/inciweb/*` | 5 min (server caches: catalog 1 h; publication 30 min) |
+ GNSS Integrity samples a 250 nm circle around the Earth point under the screen
+ centre. Camera reads debounce for 600 ms with a monotonic 2.5 s minimum gap;
+ nearby views share whole-degree cache keys, and a minute poll refreshes data.
+ Counts and bands cover visited views over 30 minutes, including regions now off
+ screen. Non-pickable ground primitives preserve Street Level and perimeter
+ selection. The legend describes a low-accuracy score, not the raw aircraft share;
+ `getStats().levels` exposes nominal, medium and high counts separately.
+
+ Transient source failures keep activation enabled and show unavailable/degraded
+ health with the next automatic retry. Upstream 429 deadlines are capped at one
+ hour, with the longest concurrent deadline retained; 5xx, timeout and malformed
+ responses impose a 15 s server cooldown. Cache hits and shared reads do not spend
+ upstream admission. Cache age and cooldown use a monotonic clock; observation
+ age comes from the upstream snapshot and is preserved in the row and voice stats.
+ Snapshots older than 30 minutes or without a source timestamp are refused.
+ Disable/destroy cancels pending requests, timers, subscriptions and primitives.
+
+ The GEV classifier remains unvalidated; anomalies do not confirm interference.
+ See [method, provenance and limits](../DATA_SOURCES.md#gnss-integrity), including
+ MLAT-positioned GPS loss, derived-field exclusions and the NIC 0 exception.
+ `scripts/qa-gnss.mjs` covers live freshness, bands, built primitives, camera/globe
+ anchors, recovery, keyboard and mobile states; emergency repainting is covered
+ by `scripts/qa-emergency-squawk.mjs`. Both accept `--timeout-ms` for slow boot.
+
+
Fire Perimeters uses capped, timed server reads with stale-on-error caching and a per-client limit. Unchanged snapshots retain geometry; link checks cancel on disable or selection change, and the row legend shows reported containment.
-Street Level is a collapsible right-rail panel (`#street-level-panel`, layer
-token `0`, option owner `street-level`, panel `ui` token `t`) that starts
+Street Level is a docked, collapsible right-rail panel (`#street-level-panel`,
+layer token `0`, option owner `street-level`, panel `ui` token `t`) that starts
collapsed. It opens itself only when the user, voice or a tool switches the
layer on or a photo opens, never on a restore, and those opens are not stored.
- It has a chip per imagery provider (the contract is in
- `src/layers/streetLevel/registry.js`; Mapillary, `mapillaryProvider.js`, is the
- default and so far the only one), 360°/flat and captured-since filters
- (relative days, so a link keeps its meaning), one embedded viewer and an
- on-globe credit per active provider. Share options: `m` (Mapillary on/off), `r`
- (custom provider switches by id), `p` (`a`/`p`/`f` panoramas), `s` (since,
- days). The header pill switches the layer; a chip switches its provider, and
- darkening the last lit chip switches the layer off.
+ Like the iD editor's photo overlay, it has one chip per registered provider,
+ shared 360°/flat and captured-since filters (relative days, so a link keeps its
+ meaning), one viewer host and one on-globe credit per active provider. Each
+ provider draws in one colour (`PROVIDER_COLORS` in
+ `src/layers/streetLevel/policy.js`); 360° cones are rings and the selected
+ sequence is GEV cyan. Share options: `m` (Mapillary), `r` (the other providers' switches by id,
+ e.g. `google-1` for Street View), `p` (`a`/`p`/`f` panoramas), `s` (since, days). Mapillary, Google
+ Street View, KartaView and Panoramax are registered. Without
+ `MAPILLARY_CLIENT_TOKEN` the panel reads KEY REQUIRED and the controls are
-disabled. With it, coverage draws as z0–5 overview points from orbit and z11–14
-sequence lines below 60 km; the proxy strips the unused `image` layer from z14
++disabled. With it, coverage draws as z11–14 sequence lines below 60 km; the proxy strips the unused `image` layer from z14
+ tiles (12 MB → ~80 KB) and shares one upstream fetch between concurrent
+ requests for a tile.
-Mapillary coverage ranks unique tile addresses before applying the 16-tile
-overview budget. Overlapping dateline halves in a polar view therefore do not
-waste overview slots on the same tile; loading already skips duplicate keys.
-
-On Google 3D (`photoreal`) at street zoom (in below 1,400 m above ground, out
-above 1,800 m) the surface mode switches from `draped` to `terrain`: draped
-lines land on roofs and tree tops, so `groundCast.js` instead places lines,
-cones and the marker 2 m above the bare earth from `/api/terrain/heights`, and
-the mesh hides what is behind buildings and trees. A tile is drawn draped until
-its heights arrive; a geoid fallback leaves it draped. Within 900 m of the
-camera, `meshSampler.js` samples the rendered surface (`scene.sampleHeight`,
-~11 m cells, nearest first, 6 ms idle budget) so lines also follow trenches,
-steep streets and roads under trees. It uses the mesh floor's rules (the
-visible tileset has finished streaming, a real bare-earth prior, the shared
-mesh window) and probes a cell again once the camera is half as far from it,
-down to 40 m, so coarse early samples are replaced as finer tiles load. A
-failed probe keeps the last good sample and distance and is retried after the
-miss cooldown. Roads on elevated decks are still drawn at
-ground level. Framing a photo ignores mesh samples far below the bare earth
-(unloaded tiles).
+Coverage is z11–14 sequence lines below 60 km; above that nothing is drawn and
+the panel says to zoom in. Tiles come from the visible ground within range of
- the camera, nearest first, at most 9. Lines are draped
++the camera, nearest first, at most 9 (the halves of a view across
++the date line count a shared tile once). Lines are draped
+`GroundPolylinePrimitive`s (`ClassificationType.BOTH`), so they follow terrain
+and Google 3D tiles alike; cones and the photo marker are ground-clamped
+billboards with a horizon cull. Without `MAPILLARY_CLIENT_TOKEN` the panel
+reads KEY REQUIRED, says which key to add and disables the filters; a rejected
+key reads KEY REJECTED and stops tile requests until the layer goes off; a 429
+pauses them for its Retry-After.
+
+The server proxy (`server/providers/mapillary.js`) adds the token to
+coverage-tile requests (the browser holds it too, for MapillaryJS and the Graph
+API), serves only z11–14 coverage, refuses upstream redirects, strips the
+unused `image` layer, shares one fetch per tile, runs at most six at once
+(cancelling those every client has left) and keeps tiles in memory for 24 h
+(a body too big to be a trimmed tile is served but not kept). While Mapillary
+rate-limits, the proxy answers 429 itself until the Retry-After (seconds or an
+HTTP date, at most 10 minutes) is over, so the rest of a view does not go on
+asking.
+ The header pill is the layer switch. Lighting a chip swaps the source;
+ clicking the lit chip turns the layer off. A chip without a usable key
+ explains the key instead of switching, and the other chips keep switching.
+ Lit off its map stack, a provider leaves the panel saying which map it
+ needs. When the switched-on providers lack
+ their keys but a switched-off one would draw with a key already set (no
+ Mapillary token, Street View on Google 3D with a Google key), the layer
+ reports it (`keyAlternatives`), and the panel's KEY REQUIRED, its coverage
+ line and the layer row's tooltip say to light it. The
-viewer sits under the header with EXPAND, FIT/FILL, FOLLOW and close above the
-image. FOLLOW needs the Google 3D map stack (`attachMapStackController`) and
-stops when the stack changes. Camera moves go through the application's
-navigation (`attachNavigation`), which releases aircraft and satellite tracking
-and is refused in the cockpit: turning FOLLOW on claims the camera at once, and
-FOLLOW stops when another feature takes it; a photo takes a deferred ticket
-when it starts opening and frames only if nothing newer took the camera while
-it loaded. SINCE is a stepped slider whose readout names the
-cut-off date. The panel is portable (`street-level-panel` spec, minimum
-320 × 280, `dockOnCollapse`): a floating window gives spare height to the
-viewer, and collapsing it, double-clicking the header or SHRINK after EXPAND
-docks it. At phone width (≤720 px) the viewer height is derived from the rail
-band so the whole photo fits.
++viewer sits under the header with EXPAND, FIT/FILL and close above the
++image. SINCE is a stepped slider whose readout names the cut-off date.
++
+MapillaryJS loads on the first photo. Opening one frames it with a single
+camera flight through the application's deferred navigation (`begin` /
+`reassert`): it releases tracking, is refused in the cockpit, and is skipped
+if newer navigation took the camera while the photo loaded; closing the photo
+cancels it. EXPAND is the browser's Fullscreen API on the viewer element; on
+iPhone, which has no element fullscreen, the viewer opens as a top-layer
+popover instead (hidden where neither API exists). Clean View, recording and
+the cockpit take an expanded photo out of full screen. At phone width the
+viewer height comes from the rail band so the whole photo fits.
- Browser gates: `npm run qa:street-level -- --url <server>` runs against real
- Mapillary; `npm run qa:street-level:fixtures` answers every Mapillary request
- from fixtures (`src/layers/streetLevel/coverageFixture.mjs`,
- `scripts/fixtures/street-level/`), but its server (default `:4173`) still needs
- some `MAPILLARY_CLIENT_TOKEN`. CI runs it `--strict` against `vite preview`.
+ Providers implement the contract in `src/layers/streetLevel/registry.js`. The
+ core routes clicks by pick prefix, swaps viewer adapters in the one host,
+ manages each provider's credit and fans the filter out to every provider. To
+ add a provider: implement the definition, register it in
+ `src/app/layers/streetLevel.js` and add its modules to
+ `scripts/package-boundaries.json`; its share switch travels in `r` by id.
+ A provider with line coverage builds it on `lineCoverage.js` (camera-driven
-XYZ tiles, draped or cast to bare earth, selection recolouring) and its cones
++XYZ tiles near the ground, draped, the selected sequence drawn again over
++them) and its cones
+ on `sequenceCones.js`, passing its tile fetch, zoom ladder, colours and pick
-prefixes; Mapillary's `coverage.js` and `sequences.js` are such wrappers. With providers on different keys the
++prefixes; Mapillary, KartaView and Panoramax all do. With providers on different keys the
+ layer's `requiresKeyId` is null and each chip reports its own key.
+
+ Google Street View (`providers/google/`) runs on the Maps JavaScript API with
+ the browser `GOOGLE_MAPS_API_KEY`, which needs that API enabled; it is loaded
+ on first use (`mapsLoader.js`, CSP `script-src https://maps.googleapis.com`).
+ Its chip starts off (`defaultOn: false`; a link without its switch keeps it off) because every
+ panorama load is billed to the key. Google's terms forbid Street View beside
+ non-Google maps, so the provider declares `requiresMapStack: 'photoreal'`:
-off Google 3D it does not appear at all (no chip, legend swatch, globe
++off Google 3D it does not appear at all (no chip, globe
+ credit, layer source or button, and Google's script is not loaded), lookups
+ and opens skip it, and leaving Google 3D closes its panorama; the share
+ option keeps the user's choice for when Google 3D returns. Google offers no coverage layer
+ for other maps, so it draws none: with it on, a click on the map itself
+ (`scenePick.isSurfacePick`: nothing picked or Google 3D tile content, so a
+ Mapillary line under the pointer wins; no tool holding the pointer; camera
+ below 3 km) opens its nearest Google-collected outdoor panorama within 50 m
+ and leaves the camera where it is (`groundClick.js`). Higher up the hint
+ says to zoom in. **OPEN STREET VIEW** beside that hint (`#sl-nearest-btn`)
+ does the same at the view centre, so Street View needs no pointer; it is
+ disabled until the camera is at street zoom (and aimed at the sky, it opens
+ nothing and says to aim at a street). One provider is lit at a time:
+ `setProviderEnabled(id, true)` darkens the others, a chip click sends every
+ switch in one update so the share link records the swap, and params that
+ light several keep the one already on, else the first in chip order
+ (`litByParams`; reapplying them never flips). Mapillary, free, is lit by
+ default. The chip reads GOOGLE STREET VIEW, and an open panorama's globe
+ marker is a Google-blue view cone (`marker: {kind: 'view-cone'}`) in place
+ of GEV's amber pin. Its
+ panoramas are all 360° and it draws no coverage, so it declares `filters: []`
+ (a provider's `filters` default to both `pano` and `since`): lookups ignore
-the IMAGERY and SINCE filters, the panel hides each filter row no lit provider
-honours (`filterControls`), and the legend lists only providers that draw
-lines, with "Selected" only beside one of them. The viewer is Google's `StreetViewPanorama` in its own
++the IMAGERY and SINCE filters, and the panel hides each filter row no lit provider
++honours (`filterControls`). The viewer is Google's `StreetViewPanorama` in its own
+ element in the viewer host, without Google's fullscreen, close and address
+ controls (the address goes in the caption); a pose goes out at once and
+ again when the panorama's month, photographer and address arrive (one
+ successful lookup per panorama per session, seeded by the nearest lookup;
+ a details lookup that fails or takes over ten seconds waits five seconds
+ before a view event can retry, and an unmount drops lookups in flight). Opening
+ another panorama settles the previous open before registering its wait; closing
+ then releases the current wait immediately. A details lookup released while its
+ service loads makes no panorama request after that service becomes available. A key
+ Google refuses (`gm_authFailure`: the API not enabled, a referrer it does
+ not allow, billing off) reads KEY REJECTED and fails a pending open at
+ once; a lookup or open Google never answers fails after 10 or 20 s. In CI
+ (no Google key, no Google 3D) the gate checks that nothing of Street View
+ shows off Google 3D, even switched on by a share link; the click and button
+ step skips as `no Google key`.
+
+ KartaView (`providers/kartaview/`) is keyless and browser-side: CORS is open
+ on `api.kartaview.org` (the documented `api.openstreetcam.org` answers but
+ serves empty tiles), `cdn.kartaview.org` and `storage*.openstreetcam.org`.
+ Its chip starts off. Coverage comes from z14 JSON tiles below 2.5 km above
+ ground and z13 up to 6 km (lower zooms take seconds per tile; z10 does not
+ answer), so higher up the hint says to zoom in, and an empty view says there
+ are no KartaView photos in it. A tile's lines are OSM way segments with
+ photos and carry no sequence, date or projection, so `decode.js` chains
+ segments that meet end to start (about four times fewer lines; linear time,
+ at most 20,000 segments a tile and 5,000 points a line), they are
-drawn as `kv:line:<z/x/y/n>`, up to 1,600 per tile, and never highlighted
-(`highlightsSequence: false`, so the legend has no "Selected"), and the
++drawn as `kv:line:<z/x/y/n>`, up to 1,600 per tile, and never highlighted, and the
+ provider declares `filters: ['pano', 'since']` and `coverageLabel` ("N
+ streets in view · click a line for its nearest photo"). KartaView filters
+ coverage only in its PNG tiles (`/sequence/tiles/{x}/{y}/{z}.png?fieldOfView=360|plane&startDate=YYYY-MM-DD`;
+ its JSON, GeoJSON and jsoncanvas tiles come back empty once a filter is
+ asked for), so a filtered tile is drawn from the cached JSON segments that
+ lie on the filtered PNG's drawn pixels (`maskedSegments`: at least half the
+ points sampled every 2 px have a drawn pixel within one; on Jakarta's 360°
+ filter, 332 of 1,041 segments lie on it, 676 miss it, 33 fall between).
-A filter change reloads the lines (`lineCoverage.reload`: the drawn ones show
-until the new ones are in), keeps the JSON segments, and caches masks per
++A filter change reloads the lines (`lineCoverage.reload`), keeps the JSON segments, and caches masks per
+ filter and tile. A dense filtered PNG can take KartaView over a minute the
+ first time (it answers 504 at 60 s and keeps drawing), so a timeout or 5xx is
+ asked again 4 s later, four tries in all; then the panel says it did not
+ filter the area in time. KartaView's `startDate` is the upload date (its
+ server filters by nothing else), so SINCE goes by upload date throughout,
+ the cut-off taken as its UTC day (`passesKartaViewFilter`): the nearest
+ lookup asks the photo API for the projection (`SPHERE`/`PLANE`; it ignores
+ `fieldOfView`) and upload date and checks each answer the same way (when
+ photos are near but none passes, the panel says so), and the cones pass on
+ each photo's projection and upload date. The provider declares
+ `sinceBasis: 'upload'`, so while it is lit the panel shows "KartaView: by
+ upload date" under the SINCE slider (`sinceNote` in the UI state). Tiles come uncompressed and
+ uncacheable, so the last 24 decoded tiles are kept for 10 minutes while
+ KartaView is lit (`createTileCache`, dropped when it is switched off); one
+ that does not answer in 20 s is asked once more, and one that is not a line
+ list is not cached. A click on a line reaches
+ `handlePick(id, {groundPoint})`, and the provider asks the core
+ (`actions.openNearest`) for its nearest showable photo within 50 m, without
+ framing: many photos are archived (their file answers 409, while a HEAD says
+ 200) or have no file, so the six nearest are probed at once with a GET cut
+ off at the headers, and where all are gone the panel says KartaView's photos
+ there are archived. Only a definite answer (403/404/409/410, or 200) is
+ remembered; a storage timeout or 5xx is asked again. The open photo's
+ sequence draws as cones from the 250-photo page holding it
+ (`/2.0/sequence/{id}/photos`); the panel counts the drive's own photos
+ (`countActivePhotos`, asked once per sequence). The camera direction (the
-marker, cones, FOLLOW, and a panorama's centre) is the direction of travel
++marker, cones and a panorama's centre) is the direction of travel
+ to the next photo a few metres on (`assignCourses`): KartaView is dashcam
+ imagery, while its `heading` is the device compass, which reads 0 for whole
+ drives without one and can sit a steady 110° off inside a car. Until the
+ drive's page arrives the compass stands in (0 counts as unknown), and the
+ pose is sent again once the course is known. The open photo's marker is a
+ purple view cone (`marker: {kind: 'view-cone'}`), as Street View's is blue. Pages follow photo ids, which only roughly
+ follow the index, so the page is found by search (both ways, halving past the
+ end when many photos were deleted), a neighbour page joins within 12 photos
+ of an edge, and the cones re-centre whenever a photo of the selected sequence
+ opens on another page. ‹ › (and ← →) open through the core without framing,
+ step on from the photo already on its way, skip archived photos, and disable
+ up front at the ends. `api.kartaview.org` speaks HTTP/1.1, so of the
+ browser's six connections to it tiles take three, lookups two and pages one
+ (newest first), and a lookup never waits behind tiles; the photo API answers
+ 429 to more than about three requests at once, so a 429 is retried with
+ backoff (at most 10 s), and a lookup gets 8 s, then 15 s once more (KartaView
+ sometimes sits on a lookup for 11 s and answers the same one in 3 s); a
+ request that could not be made at all (no network, CORS) says so and is not
+ repeated. Answers
+ are read with a running byte count and cut off past 16 MB (KartaView sends
+ them chunked, without a length). Photo URLs are built from
+ `storage` and `filepath*`: the API's `fileurl*` always name storage1, where
+ photos stored elsewhere 404, and a `fileurl*` fallback must itself be an
+ https storage host. The viewer (`viewer.js`) shows a flat photo at 1,280 px,
+ then 2,560 px, from the image proxy (`pr:sharp/rs:fit:W:H/<base64url>`),
+ with KartaView's own 1,280 px file as the fallback, and a 360° photo's
+ equirectangular `wrapped_proc` image (13,000 px wide upstream) resized to
+ 1,024 px, then 2,048 (docked) or 4,096 px (expanded, or once the viewer
+ grows), decoded off the main thread into an ImageBitmap and uploaded as RGBA
+ (about 90 ms → 15 ms for 4,096 px on a phone-class CPU), on `panorama.js`, a
+ single-triangle WebGL renderer (image centre = the camera heading; drag,
+ pinch, wheel, Shift+← →, ↑ ↓, + −; the canvas re-measures every frame; a
+ closed viewer keeps a 1×1 texture). Without WebGL, or if the proxy fails
+ within 15 s, a 360° photo shows its front view. A lost context draws the
+ photo again on a new canvas (a lost canvas only gives back its lost
+ context), through the core and facing where the user was looking; a newer
+ photo that was opening is drawn on the new canvas instead. FIT / FILL hide
+ for panoramas (`supportsRenderModes`). The
+ caption has no place name (KartaView's is where the drive began) and links to
+ the full-size photo through the image proxy, since kartaview.org's photo
+ pages fail for signed-out visitors. The viewer itself is `photoViewer.js`,
+ shared with Panoramax: each provider hands it a `PhotoSources` table (first
+ and sharper flat and panorama URLs, and the caption fields).
+
+ Panoramax (`providers/panoramax/`) is keyless and browser-side: the
+ meta-catalogue `api.panoramax.xyz` (CORS open) federates every instance, and
+ each picture is served by the instance holding it (OpenStreetMap France,
+ IGN, MapComplete…; IGN's redirect to its OVH object storage). Its chip
+ (orange, `#ff6f00`, Panoramax's own) starts off. Coverage comes from its
+ vector tiles (`/api/map/{z}/{x}/{y}.mvt`, an hour's HTTP cache): sequence
+ lines from z14 below 1.8 km above ground, z13 to 5 km, z12 to 12 km, z11
+ to 30 km and z10 to 60 km, as Mapillary's (a dense z10 tile over Paris is
+ ~2.1 MB and 8,600 sequences, 750,000 points). `decode.js` simplifies each
+ line (Douglas–Peucker to the segment, 4 units of a 4,096 tile: about a
+ pixel where it is drawn, 6–10% of a GPS track's points), and the tiles in
+ view draw their longest lines within 90,000 points (`maxPoints`,
-`keepOrder`), shared out once loading settles so a sparse tile keeps all
-it has and a dense one (a city centre) takes the rest; the selected
-sequence is always drawn. Every point becomes ~8 ground-line vertices:
++`keepOrder`), split evenly between the tiles in view (10,000 points
++each). Every point becomes ~8 ground-line vertices:
+ unsimplified, the lines hung the tab. Decoded tiles are kept while the
-provider is on (16, ten minutes, `tileCache.js`, shared with KartaView),
-and above
-60 km the `grid` layer's 0.1°
-density cells, binned to at most 96×96 points a tile (a z0 tile holds
-~70,000 cells) and not counted as sequences: the panel says to zoom in.
++provider is on (16, ten minutes, `tileCache.js`, shared with KartaView).
++Above 60 km nothing is drawn and the panel says to zoom in.
+ A tile decodes in slices of about 8 ms, the page getting a turn between
+ them (a 2 MB z10 tile is ~200 ms of work). A busy API (429/503) holds the
+ tiles back for its Retry-After, which the browser cannot read here (the API
+ exposes no headers), so the wait doubles from 5 s to 5 minutes until it
+ answers; an answer may take as long as it keeps arriving (silent for 15 s
+ is given up), so a slow link still gets its megabyte tiles. Both
-filters apply: lines carry their day and camera type, and a cell stays while
-it holds pictures of the kind asked for (cells are undated). A click on a
++filters apply: lines carry their day and camera type. A click on a
+ line asks the core (`actions.openNearest`) for that sequence's picture
+ nearest the click, within the camera height / 100 (50–400 m: from high up
+ a click lands well off a line), without framing, then any sequence's within
+ 50 m. Each lookup is two searches side by side, ranked by distance in the
+ browser: `place_position` (nearest first, but even at
+ `place_fov_tolerance=180` it leaves out pictures looking away from the
+ point) and a bounding box (those too, roughly nearest first, so 20 are
+ asked for: ~60 kB, against ~600 kB for 100); the filters go to both (`filter=field_of_view=360`, `datetime=<since>/..`). A line is dated
+ by its sequence's first day, so a sequence still growing can hide under
+ SINCE; a line with no camera type or day stays drawn. Lines keep the
+ decoded longest-first order under the per-tile cap (`keepOrder`). Once the picture is on screen
+ its sequence is highlighted and drawn as cones from the z15 tiles around it
+ (their `pictures` layer, ~110 bytes a picture, against ~7.5 kB for a STAC
+ item), plus the neighbours within 150 m of an edge, on their own connection
+ (coverage tiles take three, searches two); each tile's list for the sequence
+ is kept. The open picture's own tile draws at once and the neighbours join
+ as they arrive; one that fails is not counted, so a picture opening in it
+ re-centres the cones there. The cones re-centre when a picture opens outside the tiles
+ they were drawn from, judged from the moment their load starts, and centre
+ only on a picture actually shown (never on a lookup that came back after
+ the user moved on); a lookup nobody waits for any more is stopped. ‹ › follow the picture's own `prev`/`next`
+ links, so stepping costs one small search per picture. The viewer shows the
+ 2,048 px SD derivative (equirectangular for a 360° picture, decoded at
+ 2,048 × 1,024) and swaps in the HD original only when the viewer is wider
+ than SD (flat) or, for a panorama, expanded; once, shrunk while it decodes.
+ When SD fails a flat picture falls back to the thumbnail, and to the
+ original only in the expanded viewer. Every download of a photo, first or
+ sharper, stops when another opens or the viewer closes. Originals wider than
+ 8,192 px are never fetched; a file's header (JPEG, PNG, WebP, GIF) is read
+ before it decodes, and one declaring more than 64 MP or 16,384 px a side
+ is refused undecoded, as is an `<img>` that decodes larger and any file
+ over 48 MB. The caption names every
+ producer (an uploading app and its photographer; never an account named by
+ an email address), or else the instance holding the picture ("via
+ panoramax.ign.fr"), and the picture's licence (CC BY-SA 4.0, Licence
+ Ouverte 2.0…; StreetPose `license`), and links to the picture in the
+ Panoramax viewer. Esc anywhere in the docked viewer clears the selected
+ sequence before the panel can take it (KartaView too). After a GPU reset
+ the viewer draws the same picture again itself (`onReopen`), leaving the
+ core's lookups alone. The MCP globe panel allows the meta-catalogue and the
+ three biggest instances; a picture on another instance shows only in the
+ app.
+
+ Street Level has two browser gates. `npm run qa:street-level -- --url <server>`
+ runs against real Mapillary and needs `MAPILLARY_CLIENT_TOKEN`. `npm run
+ qa:street-level:fixtures -- --url <server>` answers every Mapillary request
+ from fixtures (`providers/mapillary/coverageFixture.mjs`,
+ `scripts/fixtures/street-level/`), and KartaView's and Panoramax's too, so it
-needs no network and covers the whole photo flow. CI runs the fixture gate and `qa:panel-resize`
-against a production build served by `vite preview` with a dummy token.
++needs no network and covers the whole photo flow. CI runs the fixture gate against a production build served by `vite preview` with a dummy token.
Directions is a keyless front end to the routing the voice agent already
uses. Its row chips are the whole interface: DRIVE / WALK / BIKE pick the
diff --cc scripts/format-scope.json
index 07fe1ac25,5ec1adb0c..410f013f3
--- a/scripts/format-scope.json
+++ b/scripts/format-scope.json
@@@ -866,57 -906,110 +902,102 @@@
"src/ui/streetLevelPresentation.test.mjs",
"src/app/layers/streetLevel.js",
"src/tooling/mapillaryProvider.test.mjs",
+ "src/app/layers/streetLevel.test.mjs",
+ "src/data/idSwitches.js",
+ "src/layers/streetLevel/credits.js",
- "src/layers/streetLevel/mapillaryProvider.js",
- "src/layers/streetLevel/mapillaryProvider.test.mjs",
++ "src/layers/streetLevel/providers/mapillary/index.js",
++ "src/layers/streetLevel/providers/mapillary/provider.test.mjs",
+ "src/layers/streetLevel/params.js",
+ "src/layers/streetLevel/params.test.mjs",
+ "src/layers/streetLevel/pickRouter.js",
+ "src/layers/streetLevel/pickRouter.test.mjs",
+ "src/layers/streetLevel/providerSwitches.test.mjs",
+ "src/layers/streetLevel/registry.js",
+ "src/layers/streetLevel/registry.test.mjs",
+ "src/layers/streetLevel/uiState.js",
+ "src/layers/streetLevel/uiState.test.mjs",
- "src/layers/streetLevel/source.test.mjs",
+ "src/layers/streetLevel/providers/mapillary/source.test.mjs",
"src/streetLevelMarkup.test.mjs",
"src/layers/streetLevel/index.js",
"src/layers/streetLevel/policy.js",
"src/layers/streetLevel/filter.js",
- "src/layers/streetLevel/registry.js",
- "src/layers/streetLevel/params.js",
- "src/layers/streetLevel/pickRouter.js",
- "src/layers/streetLevel/uiState.js",
- "src/layers/streetLevel/groundCast.js",
- "src/layers/streetLevel/meshSampler.js",
"src/layers/streetLevel/view.js",
"src/layers/streetLevel/marker.js",
- "src/layers/streetLevel/cameraFollow.js",
- "src/layers/streetLevel/credits.js",
+ "src/layers/streetLevel/cameraFraming.js",
"src/layers/streetLevel/viewerHost.js",
- "src/layers/streetLevel/providers/mapillary/index.js",
"src/layers/streetLevel/state.js",
- "src/layers/streetLevel/coverage.js",
- "src/layers/streetLevel/sequences.js",
- "src/layers/streetLevel/providers/mapillary/policy.js",
- "src/layers/streetLevel/providers/mapillary/coverage.js",
- "src/layers/streetLevel/providers/mapillary/sequences.js",
++ "src/layers/streetLevel/lineCoverage.js",
++ "src/layers/streetLevel/sequenceCones.js",
"src/layers/streetLevel/glyphs.js",
- "src/layers/streetLevel/decode.js",
+ "src/layers/streetLevel/providers/mapillary/decode.js",
"src/layers/streetLevel/tileMath.js",
"src/layers/streetLevel/selection.js",
- "src/layers/streetLevel/viewer.js",
- "src/layers/streetLevel/source.js",
+ "src/layers/streetLevel/providers/mapillary/viewer.js",
+ "src/layers/streetLevel/providers/mapillary/source.js",
+ "src/layers/streetLevel/groundClick.js",
+ "src/layers/streetLevel/providers/google/index.js",
+ "src/layers/streetLevel/providers/google/policy.js",
+ "src/layers/streetLevel/providers/google/viewer.js",
+ "src/layers/streetLevel/providers/google/mapsLoader.js",
+ "src/layers/streetLevel/groundClick.test.mjs",
- "src/app/layers/streetLevel.test.mjs",
+ "src/layers/streetLevel/providers/google/provider.test.mjs",
+ "src/layers/streetLevel/providers/google/viewer.test.mjs",
+ "src/layers/streetLevel/providers/google/mapsLoader.test.mjs",
+ "src/layers/streetLevel/providers/kartaview/index.js",
+ "src/layers/streetLevel/providers/kartaview/policy.js",
+ "src/layers/streetLevel/providers/kartaview/source.js",
+ "src/layers/streetLevel/providers/kartaview/decode.js",
+ "src/layers/streetLevel/providers/kartaview/viewer.js",
+ "src/layers/streetLevel/panorama.js",
- "src/layers/streetLevel/lineCoverage.js",
- "src/layers/streetLevel/sequenceCones.js",
+ "src/layers/streetLevel/providers/kartaview/policy.test.mjs",
+ "src/layers/streetLevel/providers/kartaview/decode.test.mjs",
+ "src/layers/streetLevel/providers/kartaview/source.test.mjs",
+ "src/layers/streetLevel/panorama.test.mjs",
+ "src/layers/streetLevel/providers/kartaview/viewer.test.mjs",
+ "src/layers/streetLevel/providers/kartaview/provider.test.mjs",
+ "src/layers/streetLevel/providers/panoramax/index.js",
+ "src/layers/streetLevel/providers/panoramax/policy.js",
+ "src/layers/streetLevel/providers/panoramax/source.js",
+ "src/layers/streetLevel/providers/panoramax/decode.js",
+ "src/layers/streetLevel/providers/panoramax/viewer.js",
+ "src/layers/streetLevel/photoViewer.js",
+ "src/layers/streetLevel/limiter.js",
+ "src/layers/streetLevel/imageSize.js",
+ "src/layers/streetLevel/tileCache.js",
+ "src/layers/streetLevel/providers/panoramax/policy.test.mjs",
+ "src/layers/streetLevel/providers/panoramax/decode.test.mjs",
+ "src/layers/streetLevel/providers/panoramax/source.test.mjs",
+ "src/layers/streetLevel/providers/panoramax/viewer.test.mjs",
+ "src/layers/streetLevel/providers/panoramax/provider.test.mjs",
+ "src/testSupport/panoramaxFixtures.mjs",
+ "src/layers/streetLevel/photoViewer.test.mjs",
+ "src/layers/streetLevel/limiter.test.mjs",
+ "src/layers/streetLevel/imageSize.test.mjs",
+ "src/layers/streetLevel/lineCoverage.test.mjs",
+ "src/testSupport/kartaViewFakes.mjs",
+ "src/testSupport/googleStreetViewFakes.mjs",
"server/providers/mapillary.js",
- "server/providers/mapillary/routes.js",
- "server/providers/mapillary/constants.js",
"server/providers/mapillary/tiles.js",
"server/providers/mapillary/trim.js",
"src/layers/streetLevel/tileMath.test.mjs",
"scripts/qa-street-level.mjs",
"src/tooling/streetLevelQa.test.mjs",
"scripts/qa-browserEvidence.mjs",
+ "scripts/qa-chrome.mjs",
+ "src/qaChrome.test.mjs",
"scripts/fixtures/street-level/mapillaryGraph.mjs",
+ "scripts/fixtures/street-level/kartaView.mjs",
+ "scripts/fixtures/street-level/panoramax.mjs",
"src/layers/streetLevel/filter.test.mjs",
- "src/layers/streetLevel/registry.test.mjs",
- "src/layers/streetLevel/params.test.mjs",
- "src/layers/streetLevel/pickRouter.test.mjs",
- "src/layers/streetLevel/uiState.test.mjs",
- "src/layers/streetLevel/groundCast.test.mjs",
- "src/layers/streetLevel/meshSampler.test.mjs",
"src/layers/streetLevel/view.test.mjs",
- "src/layers/streetLevel/mapillary.test.mjs",
- "src/layers/streetLevel/decode.test.mjs",
- "src/layers/streetLevel/coverage.test.mjs",
- "src/layers/streetLevel/coverageFixture.mjs",
- "src/layers/streetLevel/providers/mapillary/provider.test.mjs",
++ "src/layers/streetLevel/providers/mapillary/mapillary.test.mjs",
+ "src/layers/streetLevel/providers/mapillary/decode.test.mjs",
- "src/layers/streetLevel/providers/mapillary/coverage.test.mjs",
+ "src/layers/streetLevel/providers/mapillary/coverageFixture.mjs",
- "src/layers/streetLevel/cameraFollow.test.mjs",
+ "src/layers/streetLevel/cameraFraming.test.mjs",
"src/ui/streetLevelControls.test.mjs",
- "src/ui/panelDock.test.mjs",
"src/layers/streetLevel/marker.test.mjs",
"src/layers/streetLevel/viewerHost.test.mjs",
- "src/layers/streetLevel/sequences.test.mjs",
- "src/layers/streetLevel/providers/mapillary/sequences.test.mjs",
++ "src/layers/streetLevel/sequenceCones.test.mjs",
"src/layers/streetLevel/selection.test.mjs",
"src/layers/streetLevel/index.test.mjs",
"scripts/qa-overpass-offload.mjs",
diff --cc scripts/package-boundaries.json
index 5861fab0d,43bc3d4de..a6ee26c43
--- a/scripts/package-boundaries.json
+++ b/scripts/package-boundaries.json
@@@ -1196,10 -1378,10 +1376,10 @@@
],
"modules": [
"src/layers/streetLevel/index.js",
+ "src/layers/streetLevel/credits.js",
- "src/layers/streetLevel/mapillaryProvider.js",
+ "src/layers/streetLevel/providers/mapillary/index.js",
"src/layers/streetLevel/viewerHost.js",
- "src/layers/streetLevel/credits.js",
- "src/layers/streetLevel/cameraFollow.js",
+ "src/layers/streetLevel/cameraFraming.js",
"src/layers/streetLevel/marker.js",
"src/layers/streetLevel/view.js",
"src/layers/streetLevel/uiState.js",
@@@ -1210,16 -1394,43 +1390,41 @@@
"src/layers/streetLevel/filter.js",
"src/layers/streetLevel/policy.js",
"src/layers/streetLevel/state.js",
- "src/layers/streetLevel/coverage.js",
- "src/layers/streetLevel/sequences.js",
- "src/layers/streetLevel/providers/mapillary/policy.js",
- "src/layers/streetLevel/providers/mapillary/coverage.js",
- "src/layers/streetLevel/providers/mapillary/sequences.js",
++ "src/layers/streetLevel/lineCoverage.js",
++ "src/layers/streetLevel/sequenceCones.js",
"src/layers/streetLevel/glyphs.js",
- "src/layers/streetLevel/decode.js",
- "src/layers/streetLevel/coverageFixture.mjs",
+ "src/layers/streetLevel/providers/mapillary/decode.js",
+ "src/layers/streetLevel/providers/mapillary/coverageFixture.mjs",
"src/layers/streetLevel/tileMath.js",
"src/layers/streetLevel/selection.js",
- "src/layers/streetLevel/viewer.js",
- "src/layers/streetLevel/source.js",
- "scripts/qa-street-level.mjs"
+ "src/layers/streetLevel/providers/mapillary/viewer.js",
+ "src/layers/streetLevel/groundClick.js",
+ "src/layers/streetLevel/providers/google/index.js",
+ "src/layers/streetLevel/providers/google/policy.js",
+ "src/layers/streetLevel/providers/google/viewer.js",
+ "src/layers/streetLevel/providers/google/mapsLoader.js",
+ "src/layers/streetLevel/providers/kartaview/index.js",
+ "src/layers/streetLevel/providers/kartaview/policy.js",
+ "src/layers/streetLevel/providers/kartaview/source.js",
+ "src/layers/streetLevel/providers/kartaview/decode.js",
+ "src/layers/streetLevel/providers/kartaview/viewer.js",
+ "src/layers/streetLevel/providers/panoramax/index.js",
+ "src/layers/streetLevel/providers/panoramax/policy.js",
+ "src/layers/streetLevel/providers/panoramax/source.js",
+ "src/layers/streetLevel/providers/panoramax/decode.js",
+ "src/layers/streetLevel/providers/panoramax/viewer.js",
+ "src/layers/streetLevel/photoViewer.js",
+ "src/layers/streetLevel/limiter.js",
+ "src/layers/streetLevel/imageSize.js",
+ "src/layers/streetLevel/tileCache.js",
+ "src/layers/streetLevel/panorama.js",
- "src/layers/streetLevel/lineCoverage.js",
- "src/layers/streetLevel/sequenceCones.js",
+ "src/layers/streetLevel/providers/mapillary/source.js",
+ "scripts/qa-street-level.mjs",
+ "src/i18n/index.js",
+ "src/i18n/locale.js",
+ "src/i18n/locales/es.json",
- "src/i18n/locales/ru.json"
++ "src/i18n/locales/ru.json",
++ "src/layers/streetLevel/providers/mapillary/policy.js"
],
"external": ["cesium", "pbf", "@mapbox/vector-tile", "mapillary-js"]
},
@@@ -2152,25 -2418,43 +2405,45 @@@
"src/layers/streetLevel/pickRouter.js",
"src/layers/streetLevel/params.js",
"src/layers/streetLevel/registry.js",
+ "scripts/qa-street-level.mjs",
+ "src/layers/streetLevel/credits.js",
- "src/layers/streetLevel/mapillaryProvider.js",
++ "src/layers/streetLevel/providers/mapillary/index.js",
+ "src/layers/streetLevel/viewerHost.js",
+ "src/layers/streetLevel/cameraFraming.js",
+ "src/layers/streetLevel/marker.js",
+ "src/layers/streetLevel/view.js",
"src/layers/streetLevel/filter.js",
"src/layers/streetLevel/policy.js",
"src/layers/streetLevel/state.js",
- "src/layers/streetLevel/coverage.js",
- "src/layers/streetLevel/sequences.js",
- "src/layers/streetLevel/providers/mapillary/policy.js",
- "src/layers/streetLevel/providers/mapillary/coverage.js",
- "src/layers/streetLevel/providers/mapillary/sequences.js",
++ "src/layers/streetLevel/lineCoverage.js",
++ "src/layers/streetLevel/sequenceCones.js",
"src/layers/streetLevel/glyphs.js",
- "src/layers/streetLevel/decode.js",
- "src/layers/streetLevel/coverageFixture.mjs",
+ "src/layers/streetLevel/providers/mapillary/decode.js",
+ "src/layers/streetLevel/providers/mapillary/coverageFixture.mjs",
"src/layers/streetLevel/tileMath.js",
"src/layers/streetLevel/selection.js",
- "src/layers/streetLevel/viewer.js",
- "src/layers/streetLevel/source.js",
+ "src/layers/streetLevel/providers/mapillary/viewer.js",
+ "src/layers/streetLevel/groundClick.js",
+ "src/layers/streetLevel/providers/google/index.js",
+ "src/layers/streetLevel/providers/google/policy.js",
+ "src/layers/streetLevel/providers/google/viewer.js",
+ "src/layers/streetLevel/providers/google/mapsLoader.js",
+ "src/layers/streetLevel/providers/kartaview/index.js",
+ "src/layers/streetLevel/providers/kartaview/policy.js",
+ "src/layers/streetLevel/providers/kartaview/source.js",
+ "src/layers/streetLevel/providers/kartaview/decode.js",
+ "src/layers/streetLevel/providers/kartaview/viewer.js",
+ "src/layers/streetLevel/providers/panoramax/index.js",
+ "src/layers/streetLevel/providers/panoramax/policy.js",
+ "src/layers/streetLevel/providers/panoramax/source.js",
+ "src/layers/streetLevel/providers/panoramax/decode.js",
+ "src/layers/streetLevel/providers/panoramax/viewer.js",
+ "src/layers/streetLevel/photoViewer.js",
+ "src/layers/streetLevel/limiter.js",
+ "src/layers/streetLevel/imageSize.js",
+ "src/layers/streetLevel/tileCache.js",
+ "src/layers/streetLevel/panorama.js",
- "src/layers/streetLevel/lineCoverage.js",
- "src/layers/streetLevel/sequenceCones.js",
+ "src/layers/streetLevel/providers/mapillary/source.js",
"src/app/layers/streetLevel.js",
"src/layers/alpr/tileRecords.js",
"src/sources/capability.js",
@@@ -2182,7 -2466,7 +2455,6 @@@
"src/data/cameraArrival.js",
"src/layers/alpr/floors.js",
"src/data/militaryNames.js",
-- "src/sources/requestDeadline.js",
"src/data/local_data/osm_military_names/names.json",
"src/layers/installations/namedMarkers.js",
"src/data/infrastructureOverlayEntry.js",
@@@ -2190,7 -2474,23 +2462,24 @@@
"src/tools/functions.js",
"src/voice/actionSchemas.js",
"src/view/index.js",
- "src/app/embed.js"
+ "src/app/embed.js",
+ "src/i18n/index.js",
+ "src/i18n/locale.js",
+ "src/i18n/locales/es.json",
+ "src/i18n/locales/ru.json",
+ "src/ui/unitLabels.js",
+ "src/layers/recentImagery/display.js",
+ "src/ui/keyGuidance.js",
+ "src/layers/installations/classLabel.js",
+ "src/data/cameraFraming.js",
+ "src/data/geoImportPins.js",
+ "src/data/geoImportImages.js",
+ "src/app/layers/airQuality.js",
+ "src/layers/airQuality/index.js",
+ "src/layers/airQuality/model.js",
+ "src/layers/airQuality/source.js",
- "src/ui/statusText.js"
++ "src/ui/statusText.js",
++ "src/layers/streetLevel/providers/mapillary/policy.js"
],
"external": [
"hls.js",
@@@ -2676,25 -2994,43 +2977,45 @@@
"src/layers/streetLevel/pickRouter.js",
"src/layers/streetLevel/params.js",
"src/layers/streetLevel/registry.js",
+ "scripts/qa-street-level.mjs",
+ "src/layers/streetLevel/credits.js",
- "src/layers/streetLevel/mapillaryProvider.js",
++ "src/layers/streetLevel/providers/mapillary/index.js",
+ "src/layers/streetLevel/viewerHost.js",
+ "src/layers/streetLevel/cameraFraming.js",
+ "src/layers/streetLevel/marker.js",
+ "src/layers/streetLevel/view.js",
"src/layers/streetLevel/filter.js",
"src/layers/streetLevel/policy.js",
"src/layers/streetLevel/state.js",
- "src/layers/streetLevel/coverage.js",
- "src/layers/streetLevel/sequences.js",
- "src/layers/streetLevel/providers/mapillary/policy.js",
- "src/layers/streetLevel/providers/mapillary/coverage.js",
- "src/layers/streetLevel/providers/mapillary/sequences.js",
++ "src/layers/streetLevel/lineCoverage.js",
++ "src/layers/streetLevel/sequenceCones.js",
"src/layers/streetLevel/glyphs.js",
- "src/layers/streetLevel/decode.js",
- "src/layers/streetLevel/coverageFixture.mjs",
+ "src/layers/streetLevel/providers/mapillary/decode.js",
+ "src/layers/streetLevel/providers/mapillary/coverageFixture.mjs",
"src/layers/streetLevel/tileMath.js",
"src/layers/streetLevel/selection.js",
- "src/layers/streetLevel/viewer.js",
- "src/layers/streetLevel/source.js",
+ "src/layers/streetLevel/providers/mapillary/viewer.js",
+ "src/layers/streetLevel/groundClick.js",
+ "src/layers/streetLevel/providers/google/index.js",
+ "src/layers/streetLevel/providers/google/policy.js",
+ "src/layers/streetLevel/providers/google/viewer.js",
+ "src/layers/streetLevel/providers/google/mapsLoader.js",
+ "src/layers/streetLevel/providers/kartaview/index.js",
+ "src/layers/streetLevel/providers/kartaview/policy.js",
+ "src/layers/streetLevel/providers/kartaview/source.js",
+ "src/layers/streetLevel/providers/kartaview/decode.js",
+ "src/layers/streetLevel/providers/kartaview/viewer.js",
+ "src/layers/streetLevel/providers/panoramax/index.js",
+ "src/layers/streetLevel/providers/panoramax/policy.js",
+ "src/layers/streetLevel/providers/panoramax/source.js",
+ "src/layers/streetLevel/providers/panoramax/decode.js",
+ "src/layers/streetLevel/providers/panoramax/viewer.js",
+ "src/layers/streetLevel/photoViewer.js",
+ "src/layers/streetLevel/limiter.js",
+ "src/layers/streetLevel/imageSize.js",
+ "src/layers/streetLevel/tileCache.js",
+ "src/layers/streetLevel/panorama.js",
- "src/layers/streetLevel/lineCoverage.js",
- "src/layers/streetLevel/sequenceCones.js",
+ "src/layers/streetLevel/providers/mapillary/source.js",
"src/app/layers/streetLevel.js",
"src/layers/alpr/tileRecords.js",
"src/sources/capability.js",
@@@ -2706,11 -3042,25 +3027,25 @@@
"src/data/cameraArrival.js",
"src/layers/alpr/floors.js",
"src/data/militaryNames.js",
-- "src/sources/requestDeadline.js",
"src/data/local_data/osm_military_names/names.json",
"src/layers/installations/namedMarkers.js",
"src/data/infrastructureOverlayEntry.js",
- "src/sources/infrastructureData.js"
+ "src/sources/infrastructureData.js",
+ "src/i18n/index.js",
+ "src/i18n/locale.js",
+ "src/i18n/locales/es.json",
+ "src/i18n/locales/ru.json",
+ "src/ui/unitLabels.js",
+ "src/layers/recentImagery/display.js",
+ "src/layers/installations/classLabel.js",
+ "src/data/cameraFraming.js",
+ "src/app/layers/airQuality.js",
+ "src/layers/airQuality/index.js",
+ "src/layers/airQuality/model.js",
+ "src/layers/airQuality/source.js",
+ "src/ui/statusText.js",
- "src/ui/layerNames.js"
++ "src/ui/layerNames.js",
++ "src/layers/streetLevel/providers/mapillary/policy.js"
],
"external": [
"hls.js",
diff --cc scripts/qa-street-level.mjs
index 6d8315dac,b629c6c3c..c44deeb39
--- a/scripts/qa-street-level.mjs
+++ b/scripts/qa-street-level.mjs
@@@ -1,18 -1,30 +1,19 @@@
#!/usr/bin/env node
/**
- * Browser QA for the Street Level layer against a running server. Run with
+ * Browser QA for the Street Level layer against a running server:
* `npm run qa:street-level -- --url http://localhost:4173`.
*
- * `--fixtures` (CI) answers every *.mapillary.com request and the coverage
- * tile route from fixtures, so nothing reaches Mapillary; the server still
- * needs a (dummy) token because the bundle carries it. `--strict` fails on any
- * `--fixtures` (the CI mode) answers every *.mapillary.com, KartaView and
- * Panoramax request from fixtures, so nothing reaches those providers. The
- * server still needs a token
- * because the bundle carries it; CI uses a dummy one. Fixture runs also stage
- * a rejected key and a keyless second server.
- *
- * `--strict` fails on any skip not in STRICT_ALLOWED_SKIPS. `--fail-on-retry`
- * (or QA_FAIL_ON_RETRY=1) fails a missed header press unless the panel moved.
- * A failed run saves evidence under qa-artifacts/street-level/.
++ * `--fixtures` (CI) answers every *.mapillary.com, KartaView and Panoramax
++ * request and the coverage tile route from fixtures, so nothing reaches those
++ * providers; the server still needs a (dummy) Mapillary token because the
++ * bundle carries it. `--strict` fails on any
+ * skip other than "fixtures only". A failed run saves evidence under
+ * qa-artifacts/street-level/.
*/
import assert from 'node:assert/strict';
import { pathToFileURL } from 'node:url';
-import { LAYER_STATE_REGISTRY } from '../src/data/layerState.js';
import { tileBounds } from '../src/layers/streetLevel/tileMath.js';
- import { encodeCoverageTile } from '../src/layers/streetLevel/coverageFixture.mjs';
+ import { encodeCoverageTile } from '../src/layers/streetLevel/providers/mapillary/coverageFixture.mjs';
-import { COVERAGE_MOVE_DEBOUNCE_MS } from '../src/layers/streetLevel/providers/mapillary/policy.js';
-import {
- describePress,
- dockPanelByDoubleClick,
- liftPanelByHeader,
- waitForStill,
-} from './qa-panelDrag.mjs';
import {
hookRenderErrors,
readRenderErrors,
@@@ -26,10 -38,99 +27,25 @@@ import
PHOTO_SEQUENCE_ID,
photoImages,
} from './fixtures/street-level/mapillaryGraph.mjs';
+ import {
+ answerKartaViewRequest,
+ describeKartaViewCall,
+ KV_LINE,
+ KV_SEQUENCE_ID,
- kartaViewLookups,
+ kartaViewPhotos,
+ resetKartaViewFixture,
+ } from './fixtures/street-level/kartaView.mjs';
+ import {
+ answerPanoramaxRequest,
+ describePanoramaxCall,
- PNX_CREATOR,
- PNX_LINE,
+ PNX_PARK,
- PNX_SEQUENCES,
- panoramaxHdDownloads,
+ panoramaxPictures,
+ resetPanoramaxFixture,
+ } from './fixtures/street-level/panoramax.mjs';
-const PANEL_ID = 'street-level-panel';
-
-/** Where a failed run leaves its screenshots and logs. */
-export const ARTIFACT_DIR = 'qa-artifacts/street-level';
-
-export const VIEWPORTS = Object.freeze([
- { width: 1440, height: 900 },
- { width: 1280, height: 800 },
-]);
-
-/** Provider chips the panel must show, in order. */
-export const EXPECTED_PROVIDERS = Object.freeze([
- 'mapillary',
- 'google',
- 'kartaview',
- 'panoramax',
-]);
-
-/**
- * Skips no setup can avoid: CI forks have no Google key (so neither Google 3D
- * nor Street View), and live runs cannot stage fixture-only cases. `no
- * Mapillary key` is not accepted: CI's dummy token runs the keyed flow, so a
- * keyless strict run means that wiring broke. Nor is `Google key refused`: a
- * key that is set must work.
- */
-export const STRICT_ALLOWED_SKIPS = Object.freeze([
- 'no Google 3D',
- 'no Google key',
- 'fixtures only',
-]);
-
-/** A Sacramento street with Google Street View (10th St, by the Capitol). */
-export const STREET_VIEW_STREET = Object.freeze({
- lon: -121.49372,
- lat: 38.57986,
-});
-
-export function strictViolations(skips) {
- return skips.filter((skip) => !STRICT_ALLOWED_SKIPS.includes(skip.reason));
-}
-
-const STREET_LEVEL_TOKEN = LAYER_STATE_REGISTRY.find(
- (entry) => entry.id === 'street-level',
-).token;
-
-/** The Street Level panel's token in the share link's `ui` panel state. */
-export const PANEL_UI_TOKEN = 't';
-
-/** Right-rail order once the layout controller has run. */
-export const RAIL_ORDER = Object.freeze([
- 'pp-toggles',
- 'cctv-panel',
- 'weather-panel',
- 'recent-imagery-panel',
- 'street-level-panel',
- 'global-context-panel',
-]);
-
-/** Over downtown Sacramento, looking north and down. */
-export const PARK = Object.freeze({
- lon: -121.4944,
- lat: 38.5816,
- height: 900,
- pitch: -1.3,
-});
-
-export function isCollapsed(classList) {
- return [...classList].includes('collapsed');
-}
-
-const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
-
+const VIEWPORT = { width: 1440, height: 900 };
+/** Over downtown Sacramento, above the fixture photo line, looking down. */
+const PARK = { lon: PHOTO_LINE.lon, lat: 38.5816, height: 900, pitch: -1.3 };
const DAY_MS = 86_400_000;
/**
@@@ -87,22 -199,79 +103,42 @@@ function fixtureTile(z, x, y, now = Dat
],
],
});
- return encodeCoverageTile(tile, { sequences });
+ return encodeCoverageTile({ x, y, z }, { sequences });
}
-/**
- * Ask the real status route from Node, outside the page's interception, so a
- * server that never registered it fails even in fixture runs. Node sends no
- * Origin, so the same-site gate admits it.
- * @returns {Promise<{configured: boolean}>}
- */
-export async function assertRealStatusRoute(url, fetchImpl = fetch) {
- const route = new URL('/api/mapillary/status', url).href;
- let response;
- try {
- response = await fetchImpl(route, {
- headers: { Accept: 'application/json' },
- });
- } catch (error) {
- throw new Error(`${route} is unreachable: ${error?.message || error}`, {
- cause: error,
- });
- }
- const type = response.headers.get('content-type') || '';
- const text = await response.text();
- assert.equal(
- response.status,
- 200,
- `${route} must be the server's Mapillary route (HTTP ${response.status}: ${text.slice(0, 120)})`,
- );
- assert.match(type, /application\/json/, `${route} answers JSON, not ${type}`);
- let body;
- try {
- body = JSON.parse(text);
- } catch {
- assert.fail(`${route} answered unparseable JSON: ${text.slice(0, 120)}`);
- }
- assert.equal(
- typeof body?.configured,
- 'boolean',
- `${route} reports a boolean \`configured\`: ${text.slice(0, 120)}`,
- );
- return body;
-}
++/** Fixture answers and call names per keyless provider host. */
++const KEYLESS_HOSTS = [
++ {
++ host: /(^|\.)(kartaview|openstreetcam)\.org$/,
++ describe: describeKartaViewCall,
++ answer: answerKartaViewRequest,
++ },
++ {
++ host: /^(api\.panoramax\.xyz|panoramax\.openstreetmap\.fr)$/,
++ describe: describePanoramaxCall,
++ answer: answerPanoramaxRequest,
++ },
++];
+
/**
-- * Answer the page's Mapillary requests from `fixture`, which steps may change
-- * mid-run. `configured: undefined` lets the server's real status route answer.
- * @param {{configured?: boolean, tiles: 'ok'|'rejected', tileRequests: number, images: Array<object>, calls: Set<string>, unknown: Array<string>}} fixture
++ * Answer the page's Mapillary, KartaView and Panoramax requests from
++ * `fixture`, which steps may change mid-run. `configured: undefined` lets the
++ * server's real status route answer.
*/
-export async function serveFixtures(page, fixture) {
- // CDP Fetch on just these URLs: Puppeteer's page-wide interception stalls
- // Cesium's worker scripts, leaving nothing to click.
+async function serveFixtures(page, fixture) {
+ // CDP Fetch on just these URLs: page-wide interception stalls Cesium workers.
const cdp = await page.createCDPSession();
await cdp.send('Fetch.enable', {
patterns: [
{ urlPattern: '*://*.mapillary.com/*' },
{ urlPattern: '*/api/mapillary/*' },
+ { urlPattern: '*://api.kartaview.org/*' },
+ { urlPattern: '*://cdn.kartaview.org/*' },
+ { urlPattern: '*://*.openstreetcam.org/*' },
+ { urlPattern: '*://api.panoramax.xyz/*' },
+ { urlPattern: '*://panoramax.openstreetmap.fr/*' },
],
});
- const fulfil = (requestId, { status, headers = {}, contentType, body }) =>
- cdp.send('Fetch.fulfillRequest', {
- requestId,
- responseCode: status,
- responseHeaders: Object.entries({
- ...headers,
- ...(contentType ? { 'Content-Type': contentType } : {}),
- }).map(([name, value]) => ({ name, value: String(value) })),
- body: Buffer.from(body ?? '').toString('base64'),
- });
const json = (status, payload) => ({
status,
contentType: 'application/json',
@@@ -118,42 -290,55 +154,52 @@@
});
fixture.calls.add(call);
if (!answer.known) fixture.unknown.push(call);
- } else if (/(^|\.)(kartaview|openstreetcam)\.org$/.test(address.hostname)) {
- const call = describeKartaViewCall(method, address);
- answer = answerKartaViewRequest({ method, url: request.url });
- fixture.calls.add(call);
- if (!answer.known) fixture.unknown.push(call);
- } else if (
- address.hostname === 'api.panoramax.xyz' ||
- address.hostname === 'panoramax.openstreetmap.fr'
- ) {
- const call = describePanoramaxCall(method, address);
- answer = answerPanoramaxRequest({ method, url: request.url });
+ return answer;
+ }
++ const keyless = KEYLESS_HOSTS.find(({ host }) =>
++ host.test(address.hostname),
++ );
++ if (keyless) {
++ const call = keyless.describe(method, address);
++ const answer = keyless.answer({ method, url: address.href });
+ fixture.calls.add(call);
+ if (!answer.known) fixture.unknown.push(call);
- } else if (
- address.pathname === '/api/mapillary/status' &&
- fixture.configured !== undefined
- ) {
- answer = json(200, { configured: fixture.configured });
- } else {
- const tile = address.pathname.match(
- /^\/api\/mapillary\/tiles\/coverage\/(\d+)\/(\d+)\/(\d+)$/,
- );
- if (tile) {
- fixture.tileRequests++;
- if (fixture.configured === false)
- answer = json(503, { error: 'no_key', keyRequired: true });
- else if (fixture.tiles === 'rejected')
- answer = json(403, {
- error: 'Mapillary rejected the access token',
- keyRejected: true,
- });
- else {
- const bytes = fixtureTile(
- Number(tile[1]),
- Number(tile[2]),
- Number(tile[3]),
- );
- answer = bytes.length
- ? {
- status: 200,
- contentType: 'application/x-protobuf',
- body: Buffer.from(bytes),
- }
- : { status: 204, body: '' };
- }
- }
++ return answer;
+ }
+ if (address.pathname === '/api/mapillary/status')
+ return fixture.configured === undefined
+ ? null
+ : json(200, { configured: fixture.configured });
+ const tile = address.pathname.match(
+ /^\/api\/mapillary\/tiles\/coverage\/(\d+)\/(\d+)\/(\d+)$/,
+ );
+ if (!tile) return null;
+ if (fixture.configured === false)
+ return json(503, { error: 'no_key', keyRequired: true });
+ if (fixture.rejected)
+ return json(403, {
+ error: 'Mapillary rejected the access token',
+ keyRejected: true,
+ });
+ const bytes = fixtureTile(...tile.slice(1).map(Number));
+ return bytes.length
+ ? { status: 200, contentType: 'application/x-protobuf', body: bytes }
+ : { status: 204, body: '' };
+ };
+ cdp.on('Fetch.requestPaused', ({ requestId, request }) => {
+ const answer = answerFor(request.method, new URL(request.url));
const done = answer
- ? fulfil(requestId, answer)
+ ? cdp.send('Fetch.fulfillRequest', {
+ requestId,
+ responseCode: answer.status,
+ responseHeaders: Object.entries({
+ ...answer.headers,
+ ...(answer.contentType
+ ? { 'Content-Type': answer.contentType }
+ : {}),
+ }).map(([name, value]) => ({ name, value: String(value) })),
+ body: Buffer.from(answer.body ?? '').toString('base64'),
+ })
: cdp.send('Fetch.continueRequest', { requestId });
// A page that navigated or closed meanwhile has no request to answer.
done.catch(() => {});
@@@ -189,60 -392,74 +235,65 @@@ async function boot(page, url)
});
}
-/**
- * Click a panel control once the panel holds still and the control is what
- * lies under its centre: the rail animates panel heights, so a point read
- * once can miss by the time the pointer goes down.
- */
-async function clickPanelControl(page, selector, { timeout = 5_000 } = {}) {
- await waitForStill(page, PANEL_ID);
- const deadline = Date.now() + timeout;
- for (;;) {
- const hit = await page.$eval(selector, (el) => {
- el.scrollIntoView({ block: 'nearest' });
- const r = el.getBoundingClientRect();
- const x = r.left + r.width / 2;
- const y = r.top + r.height / 2;
- const top = document.elementFromPoint(x, y);
- return {
- x,
- y,
- ok: Boolean(top && (top === el || el.contains(top))),
- target: top
- ? `${top.tagName.toLowerCase()}${top.id ? `#${top.id}` : ''}`
- : 'nothing',
- };
- });
- if (hit.ok) return page.mouse.click(hit.x, hit.y);
- if (Date.now() > deadline)
- throw new Error(`${selector} is covered by ${hit.target}`);
- await new Promise((resolve) => setTimeout(resolve, 200));
- }
-}
+/** Run `test(uiState, arg)` in the page until it is true. */
+const uiUntil = (page, test, arg = null, timeout = 30_000) =>
+ page.waitForFunction(
+ `(${test})(window.__godsEyeView.dataManager.layers.get('street-level').module.getUIState(), ${JSON.stringify(arg)})`,
+ { timeout, polling: 100 },
+ );
-/** Load the app and clear the first-run dialog. */
-export async function boot(page, url) {
- await page.goto(url, { waitUntil: 'domcontentloaded' });
- await clearFirstRun(page);
-}
++/** `id` is the one provider lit. */
++const litAlone = (u, id) =>
++ u.providers.find((p) => p.id === id)?.on === true &&
++ u.providers.filter((p) => p.on).length === 1;
+
-function readPanel(page) {
- return page.evaluate(() => {
- const el = document.getElementById('street-level-panel');
- const rail = document.getElementById('right-context-rail');
- const box = el.getBoundingClientRect();
- return {
- order: rail ? [...rail.children].map((child) => child.id) : [],
- classes: [...el.classList],
- width: Math.round(box.width),
- right: Math.round(box.right),
- status: document.getElementById('sl-status').textContent,
- controlsDisabled: document.getElementById('sl-controls').disabled,
- bodyDisplay: getComputedStyle(document.getElementById('sl-body')).display,
- };
- });
-}
+const getUI = (page) =>
+ page.evaluate(() =>
+ window.__godsEyeView.dataManager.layers
+ .get('street-level')
+ .module.getUIState(),
+ );
-/** Wait until Street Level is on, drawn, settled and not key-gated. */
-function waitForCoverage(page, { timeout = 90_000 } = {}) {
- return page.waitForFunction(
- () => {
- const dm = window.__godsEyeView.dataManager;
- const u = dm.layers.get('street-level').module.getUIState();
- return (
- dm.isEnabled('street-level') &&
- u.coverage.count > 0 &&
- !u.coverage.loading &&
- !u.keyRequired
- );
- },
- { timeout },
+const statusIs = (page, text) =>
+ page.waitForFunction(
+ (want) => document.getElementById('sl-status').textContent === want,
+ { timeout: 30_000 },
+ text,
+ );
+
+const waitForCoverage = (page) =>
+ uiUntil(
+ page,
+ (u) =>
+ u.enabled &&
+ u.coverage.count > 0 &&
+ !u.coverage.loading &&
+ !u.keyRequired,
+ null,
+ 90_000,
+ );
+
+/**
+ * Press a panel control through the DOM: the rail animates panel heights, so
+ * a pointer aimed from one frame's layout can miss in the next.
+ */
+const press = (page, selector) =>
+ page.$eval(selector, (control) => control.click());
+
+/** Expand the strip; a panel state stored by an earlier page may have done so. */
+async function expandPanel(page) {
+ const collapsed = await page.$eval('#street-level-panel', (node) =>
+ node.classList.contains('collapsed'),
+ );
+ if (collapsed)
+ await press(
+ page,
+ '.panel-collapse-btn[data-collapse-target="street-level-panel"]',
+ );
+ await page.waitForFunction(
+ () =>
+ getComputedStyle(document.getElementById('sl-body')).display === 'flex',
+ { timeout: 10_000 },
);
}
@@@ -264,56 -488,17 +315,61 @@@ async function assertKeyRequired(page)
}
/**
- * With no Mapillary key the panel points at KartaView, which needs none:
- * lit, it draws coverage and the layer is not key-gated.
+ * Client coordinates of the first thing drawn whose pick id starts with
+ * `prefix`, scanning `box` ({x, y, w, h} in canvas pixels; default: a row
+ * across the middle) every `step` px; null when nothing matches.
*/
-async function assertKeylessKartaView(page) {
- assert.match(
- await page.$eval('#sl-coverage-meta', (node) => node.textContent),
- /light KARTAVIEW/,
- 'KEY REQUIRED points at KartaView',
+const findPick = (page, prefix, { box = null, step = 3 } = {}) =>
+ page.evaluate(
+ (want, area, stride) => {
+ const { scene } = window.__godsEyeView.viewer;
+ const rect = scene.canvas.getBoundingClientRect();
+ const { x, y, w, h } = area || {
+ x: 0,
+ y: Math.round(rect.height / 2),
+ w: rect.width,
+ h: 1,
+ };
+ for (let py = y; py < y + h; py += stride)
+ for (let px = x; px < x + w; px += stride) {
+ const id = scene.pick({ x: px, y: py })?.id;
+ if (typeof id === 'string' && id.startsWith(want))
+ return {
+ x: rect.left + px,
+ y: rect.top + py,
+ local: { x: px, y: py },
++ id,
+ };
+ }
+ return null;
+ },
+ prefix,
+ box,
+ step,
);
- for (let attempt = 0; attempt < 4; attempt++) {
- await page.evaluate((at) => {
+
+/**
+ * `findPick`, retried until a hit or `timeout`: draped lines build in a
+ * worker after their tile decoded, so a scan right after LOADING clears can
+ * come too early on a slow machine.
+ */
- async function findPickUntil(page, prefix, { timeout = 30_000 } = {}) {
++async function findPickUntil(
++ page,
++ prefix,
++ { timeout = 30_000, box = null } = {},
++) {
+ const deadline = Date.now() + timeout;
+ for (;;) {
- const hit = await findPick(page, prefix);
++ const hit = await findPick(page, prefix, { box });
+ if (hit || Date.now() >= deadline) return hit;
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ }
+}
+
- /** Park the camera over the photo line; a late startup flight can move it. */
- async function park(page) {
++/** Park the camera at `at`; a late startup flight can move it. */
++async function park(page, at = PARK) {
+ for (let attempt = 0; attempt < 5; attempt++) {
+ const stayed = await page.evaluate(async (at) => {
const v = window.__godsEyeView.viewer;
v.camera.cancelFlight?.();
const C = v.camera.positionCartographic.constructor;
@@@ -323,16 -508,141 +379,16 @@@
),
orientation: { heading: 0, pitch: at.pitch, roll: 0 },
});
- }, PARK);
- await sleep(1000);
- }
- await clickPanelControl(
- page,
- '#sl-provider-chips [data-chip-id="kartaview"]',
- );
- await waitForCoverage(page);
- const state = await page.evaluate(() => ({
- status: document.getElementById('sl-status').textContent,
- keyRequired: window.__godsEyeView.dataManager.layers
- .get('street-level')
- .module.getUIState().keyRequired,
- }));
- assert.equal(state.keyRequired, false);
- assert.doesNotMatch(state.status, /KEY/);
-}
-
-/**
- * Runs in the page. Find a point where a real click picks `prefix` + `id` (any
- * id when null), searched around `points` ([lon, lat]), the aimed billboards,
- * or else a grid mid-screen. Only points where the canvas is topmost count.
- * Each call picks for at most `budgetMs`; the next call resumes the search.
- * @returns {{x: number, y: number, id: string}|null} client coordinates
- */
-export function findPickPoint({
- prefix,
- id,
- points,
- billboardIds,
- billboardPrefix = null,
- budgetMs = 4000,
-}) {
- const viewer = window.__godsEyeView.viewer;
- const scene = viewer.scene;
- const canvas = scene.canvas;
- const rect = canvas.getBoundingClientRect();
- const Cartographic = viewer.camera.positionCartographic.constructor;
- let Cartesian2 = null;
- const windowPoint = (x, y) => (Cartesian2 ? new Cartesian2(x, y) : { x, y });
- const wanted = (picked) => {
- const pid =
- typeof picked?.id === 'string' ? picked.id : (picked?.id?.id ?? null);
- if (typeof pid !== 'string' || !pid.startsWith(prefix)) return null;
- const rest = pid.slice(prefix.length).split('~')[0];
- return id === null || rest === id ? rest : null;
- };
- const tryAt = (x, y) => {
- if (x < 2 || y < 2 || x > rect.width - 2 || y > rect.height - 2)
- return null;
- const top = document.elementFromPoint(rect.left + x, rect.top + y);
- if (top !== canvas) return null;
- const hit = wanted(scene.pick(windowPoint(x, y)));
- return hit ? { x: rect.left + x, y: rect.top + y, id: hit } : null;
- };
- const centres = [];
- const aimed = (billboardId) =>
- typeof billboardId === 'string' &&
- ((billboardIds || []).includes(billboardId) ||
- (billboardPrefix !== null && billboardId.startsWith(billboardPrefix)));
- if ((billboardIds && billboardIds.length) || billboardPrefix !== null) {
- for (let i = 0; i < scene.primitives.length; i++) {
- const collection = scene.primitives.get(i);
- if (typeof collection?.get !== 'function' || !collection.length) continue;
- for (let j = 0; j < collection.length; j++) {
- const billboard = collection.get(j);
- if (!aimed(billboard?.id) || !billboard.show) continue;
- const at = billboard.computeScreenSpacePosition?.(scene);
- if (at) {
- Cartesian2 ??= at.constructor;
- centres.push([at.x, at.y]);
- }
- }
- }
- }
- for (const [lon, lat] of points || []) {
- const at = scene.cartesianToCanvasCoordinates(
- scene.globe.ellipsoid.cartographicToCartesian(
- Cartographic.fromDegrees(lon, lat, 0),
- ),
- );
- if (at) {
- Cartesian2 ??= at.constructor;
- centres.push([at.x, at.y]);
- }
- }
- // A pick is a render of the scene (0.5–2 s each under SwiftShader): try
- // the centres the canvas is on top of first, nearest the screen centre,
- // so the first pick usually hits.
- const uncovered = ([x, y]) =>
- document.elementFromPoint(rect.left + x, rect.top + y) === canvas;
- const fromMiddle = ([x, y]) =>
- (x - rect.width / 2) ** 2 + (y - rect.height / 2) ** 2;
- centres.sort(
- (a, b) =>
- Number(uncovered(b)) - Number(uncovered(a)) ||
- fromMiddle(a) - fromMiddle(b),
- );
- const candidates = [];
- for (const [cx, cy] of centres) {
- candidates.push([cx, cy]);
- for (let r = 2; r <= 16; r += 2)
- for (const [dx, dy] of [
- [r, 0],
- [-r, 0],
- [0, r],
- [0, -r],
- ])
- candidates.push([cx + dx, cy + dy]);
- }
- // Aimed at known places: never fall back to a scan of the whole screen.
- if (!points && !billboardIds && billboardPrefix === null)
- for (let y = rect.height * 0.25; y < rect.height * 0.8; y += 18)
- for (let x = rect.width * 0.25; x < rect.width * 0.7; x += 6)
- candidates.push([x, y]);
- // One evaluation stays well inside the caller's wait: past the budget it
- // returns null, and the next poll carries on from where this one stopped.
- const key = JSON.stringify([prefix, id, billboardPrefix]);
- const cursors = (window.__qaPickCursors ??= {});
- const deadline = performance.now() + budgetMs;
- let at = cursors[key] ?? 0;
- if (at >= candidates.length) at = 0;
- for (; at < candidates.length; at++) {
- const hit = tryAt(...candidates[at]);
- if (hit) {
- delete cursors[key];
- return hit;
- }
- if (performance.now() > deadline) {
- cursors[key] = at + 1;
- return null;
- }
+ await new Promise((resolve) => setTimeout(resolve, 1500));
+ const c = v.camera.positionCartographic;
+ return (
+ Math.abs((c.longitude * 180) / Math.PI - at.lon) < 0.001 &&
+ Math.abs((c.latitude * 180) / Math.PI - at.lat) < 0.001
+ );
- }, PARK);
++ }, at);
+ if (stayed) return;
}
- throw new Error('the camera would not stay parked over the photo line');
- delete cursors[key];
- return null;
++ throw new Error(`the camera would not stay parked at ${JSON.stringify(at)}`);
}
async function main() {
@@@ -353,21 -664,27 +409,24 @@@
});
let count = 0;
const skips = [];
- const step = async (label, fn) => {
- await fn();
- console.log(`ok ${++count} ${label}`);
- };
- /** `fn` gets `skip(reason)`: the step runs what it can but reports a skip. */
+ const skip = (reason, label) => {
+ skips.push(reason);
+ console.log(`skip (${reason}) ${++count} ${label}`);
+ };
++ // `fn` may call `skipped(reason)` when a live run has nothing to test.
+ const step = async (label, fn) => {
- let skipped = null;
- const result = await fn({
- skip: (reason) => {
- skipped = reason;
- },
- });
- count++;
- if (skipped) {
- skips.push({ reason: skipped, label });
- console.log(`skip (${skipped}) ${count} ${label}`);
- } else console.log(`ok ${count} ${label}`);
- return result;
++ let reason = null;
++ await fn({ skipped: (why) => (reason = why) });
++ if (reason) skip(reason, label);
++ else console.log(`ok ${++count} ${label}`);
+ };
- /** A step this mode cannot run at all. */
- const skipStep = (reason, label) => step(label, ({ skip }) => skip(reason));
+ const fixtureStep = (label, fn) =>
+ fixtures ? step(label, fn) : skip('fixtures only', label);
const errors = [];
const monitors = [];
- /** The layer only warns on listener exceptions, so count those as errors. */
- const watch = async (page, name) => {
+ // The layer only warns on listener exceptions, so count those as errors.
+ const open = async (name, fixture) => {
+ const page = await browser.newPage();
monitors.push(
watchPage(page, {
name,
@@@ -376,51 -693,249 +435,120 @@@
}),
);
await hookRenderErrors(page);
- };
- const renderErrorsSeen = [];
- try {
- await step(
- 'the server registers the real Mapillary status route',
- async () => {
- const real = await assertRealStatusRoute(url);
- console.log(` (server status: configured=${real.configured})`);
- if (fixtures)
- assert.equal(
- real.configured,
- true,
- 'fixture runs need a server started with MAPILLARY_CLIENT_TOKEN (CI uses a dummy, non-secret one): the browser bundle carries the token, and without it no photo can open',
- );
- },
- );
- const page = await browser.newPage();
- const fixture = newFixture();
- await watch(page, 'main');
- if (fixtures) await serveFixtures(page, fixture);
+ if (fixture) await serveFixtures(page, fixture);
await boot(page, url);
- const panel = () => readPanel(page);
- const status = await page.evaluate(() =>
- fetch('/api/mapillary/status').then((res) => res.json()),
+ return page;
+ };
+ const collectRenderErrors = async (page, name) =>
+ errors.push(
+ ...(await readRenderErrors(page)).map(
+ (text) => `[${name}] scene.renderError: ${text}`,
+ ),
);
- for (const viewport of VIEWPORTS) {
- await page.setViewport(viewport);
- await step(
- `panel is a collapsed right-rail strip at ${viewport.width}×${viewport.height}`,
- async () => {
- await settle(
- page,
- (width) => {
- const box = document
- .getElementById('street-level-panel')
- .getBoundingClientRect();
- return box.width <= 200 && box.right <= width;
- },
- viewport.width,
- );
- const info = await panel();
- assert.deepEqual(info.order, RAIL_ORDER);
- assert.ok(isCollapsed(info.classes));
- assert.equal(info.bodyDisplay, 'none');
- assert.ok(info.width <= 200 && info.right <= viewport.width);
- },
- );
- }
- await page.setViewport(VIEWPORTS[0]);
- const expandStrip = async (target = page) => {
- await clickPanelControl(
- target,
- '.panel-collapse-btn[data-collapse-target="street-level-panel"]',
- );
- assert.ok(
- await settle(
- target,
- () =>
- !document
- .getElementById('street-level-panel')
- .classList.contains('collapsed') &&
- getComputedStyle(document.getElementById('sl-body')).display ===
- 'flex',
- ),
- 'Street Level panel did not expand before the timeout',
- );
- };
- await expandStrip();
- await step(
- 'expanding the strip shows the body, one chip per provider and the legend',
- async () => {
- const info = await panel();
- assert.ok(!isCollapsed(info.classes));
- assert.equal(info.bodyDisplay, 'flex');
- const chips = await page.evaluate(() =>
- [
- ...document.querySelectorAll(
- '#sl-provider-chips .data-toggle-chip',
- ),
- ].map((chip) => chip.dataset.chipId),
+
++ /**
++ * A keyless provider: lighting its chip darkens the others and draws its
++ * coverage with its credit; a click on a line opens a photo from it; ×
++ * closes it. Leaves that provider lit.
++ */
++ const keylessProviderStep = ({
++ id,
++ name,
++ at,
++ linePrefix,
++ box,
++ reset,
++ check,
++ }) =>
++ step(
++ `${name}: its chip draws keyless coverage and its credit, a line opens its photo, × closes it`,
++ async ({ skipped }) => {
++ reset();
++ await park(page, at);
++ await press(page, `#sl-provider-chips [data-chip-id="${id}"]`);
++ await uiUntil(page, litAlone, id);
++ await waitForCoverage(page);
++ await page.waitForFunction(
++ (credit) => document.body.innerHTML.includes(credit),
++ { timeout: 15_000 },
++ `${name}</a> contributors`,
++ );
++ const area =
++ box === 'column'
++ ? await page.evaluate(() => {
++ const { height, width } =
++ window.__godsEyeView.viewer.scene.canvas.getBoundingClientRect();
++ return { x: Math.round(width * 0.3), y: 0, w: 1, h: height };
++ })
++ : null;
++ const line = await findPickUntil(page, linePrefix, { box: area });
++ if (!line && !fixtures) return skipped(`no ${name} line in view`);
++ assert.ok(line, `a ${name} line in view`);
++ await page.mouse.click(line.x, line.y);
++ await uiUntil(
++ page,
++ (u) => (u.street.imageId && !u.street.loading) || u.street.error,
++ null,
++ 90_000,
+ );
- // Every registered provider usable on this map, in order (Street View
- // only on Google 3D).
- const listed = await page.evaluate(() =>
- window.__godsEyeView.dataManager.layers
- .get('street-level')
- .module.getUIState()
- .providers.map((provider) => provider.id),
++ const { street } = await getUI(page);
++ if (!fixtures && /No street-level imagery/.test(street.error || ''))
++ return skipped(`no ${name} photo near the line`);
++ assert.equal(street.error, null, `viewer error: ${street.error}`);
++ assert.equal(street.providerId, id);
++ assert.equal(
++ await page.$eval('#sl-viewer-wrap', (node) => node.hidden),
++ false,
+ );
- assert.deepEqual(chips, listed);
- assert.deepEqual(
- EXPECTED_PROVIDERS.filter((id) => listed.includes(id)),
- listed,
++ if (fixtures)
++ check(street, line.id.slice(linePrefix.length).split('~')[0]);
++ await press(page, '#sl-viewer-close');
++ await uiUntil(
++ page,
++ (u) => !u.street.open && u.sequence.selectedId === null,
+ );
- assert.ok(listed.includes('mapillary'));
- // One swatch per switched-on source plus "Selected" (Street View
- // starts off); each chip wears its colour.
- const legend = await page.evaluate(() => ({
- swatches: document.querySelectorAll('#sl-legend li').length,
- on: window.__godsEyeView.dataManager.layers
- .get('street-level')
- .module.getUIState()
- .providers.filter((provider) => provider.on).length,
- }));
- assert.equal(legend.swatches, legend.on + 1);
+ assert.equal(
- await page.$eval('[data-chip-id="mapillary"]', (chip) =>
- chip.style.getPropertyValue('--chip-color'),
- ),
- '#05cb63',
++ await page.$eval('#sl-viewer-wrap', (node) => node.hidden),
++ true,
+ );
+ },
+ );
- if (!status.configured) {
- await step(
- 'keyless install gates the controls and reports KEY REQUIRED',
- () => assertKeylessGate(page),
- );
- await skipStep(
- 'no Mapillary key',
- 'the keyed steps (coverage, filters, photos, panel window)',
- );
- console.log(
- 'keyless run complete (no MAPILLARY_CLIENT_TOKEN on the server)',
- );
- } else {
- await keyedSteps();
- }
- await step('no page errors and no Cesium render-loop errors', async () => {
- renderErrorsSeen.push(
- ...(await readRenderErrors(page)).map(
- (text) => `[main] scene.renderError: ${text}`,
- ),
- );
- assert.deepEqual([...errors, ...renderErrorsSeen], []);
- });
- if (strict)
- await step('strict: no skips beyond the documented ones', () => {
- assert.deepEqual(
- strictViolations(skips),
- [],
- `--strict accepts only skips for: ${STRICT_ALLOWED_SKIPS.join(', ')}`,
- );
- });
- console.log(
- `${count} steps: ${count - skips.length} ok, ${skips.length} skipped`,
++ let page = null;
++
+ try {
+ const fixture = newFixture();
- const page = await open('main', fixtures && fixture);
++ page = await open('main', fixtures && fixture);
+ const { configured } = await page.evaluate(() =>
+ fetch('/api/mapillary/status').then((res) => res.json()),
);
+ if (fixtures)
+ assert.equal(
+ configured,
+ true,
+ 'fixture runs need a server started with MAPILLARY_CLIENT_TOKEN (CI uses a dummy one)',
+ );
- /**
- * KartaView: keyless coverage from its JSON tiles, a line click opening
- * the nearest photo, cones along the drive, › and a 360° photo. Runs on a
- * draped map so a line is where it is drawn; leaves Mapillary lit.
- */
- async function kartaViewSteps() {
- // The first lookup from here on is the rate-limited one.
- resetKartaViewFixture();
- const ui = () =>
- page.evaluate(() =>
- window.__godsEyeView.dataManager.layers
- .get('street-level')
- .module.getUIState(),
- );
- const uiUntil = (test, arg = null, options) =>
- settle(
- page,
- `(${test})(window.__godsEyeView.dataManager.layers.get('street-level').module.getUIState(), ${JSON.stringify(arg)})`,
- undefined,
- options,
- );
- const lit = (id) =>
- uiUntil(
- (u, want) =>
- u.providers.find((p) => p.id === want)?.on === true &&
- u.providers.filter((p) => p.on).length === 1,
- id,
- );
- const stack = () =>
- page.evaluate(() =>
- window.__godsEyeView.mapStackController.getActiveId(),
- );
- const setStack = async (id) => {
- await page.evaluate(
- (stackId) =>
- window.__godsEyeView.mapStackController.setStack(stackId),
- id,
- );
- await settle(
- page,
- (stackId) =>
- window.__godsEyeView.mapStackController.getActiveId() === stackId,
- id,
- );
- };
- const kvChip = '#sl-provider-chips [data-chip-id="kartaview"]';
- const original = await stack();
- const photos = kartaViewPhotos();
- await page.evaluate(() =>
- window.__godsEyeView.dataManager.layers
- .get('street-level')
- .module.closeViewer(),
+ await expandPanel(page);
+ if (!configured) {
+ await step('keyless server: KEY REQUIRED gates the controls', () =>
+ assertKeyRequired(page),
);
- await setStack('esri-imagery');
- // Over the fixture drive, looking down: its line is mid-screen.
- for (let attempt = 0; attempt < 4; attempt++) {
- await page.evaluate((at) => {
- const v = window.__godsEyeView.viewer;
- v.camera.cancelFlight?.();
- const C = v.camera.positionCartographic.constructor;
- v.camera.setView({
- destination: v.scene.globe.ellipsoid.cartographicToCartesian(
- C.fromDegrees(at.lon, at.lat, at.height),
- ),
- orientation: { heading: 0, pitch: at.pitch, roll: 0 },
- });
- }, PARK);
- await sleep(1000);
- }
+ skip('no Mapillary key', 'the keyed steps');
+ } else {
+ await park(page);
await step(
- 'KartaView: its chip draws keyless coverage, credits KartaView and offers Mapillary’s filters, SINCE noted as its upload date',
+ 'enabling draws coverage and the Mapillary credit',
async () => {
- await clickPanelControl(page, kvChip);
- assert.ok(await lit('kartaview'), 'KartaView alone is lit');
- await waitForCoverage(page);
- const u = await ui();
- assert.equal(u.keyRequired, false);
- assert.deepEqual(u.filterControls, { pano: true, since: true });
- // KartaView's SINCE is its upload date: the panel says so.
- assert.equal(u.sinceNote, 'KartaView: by upload date');
- assert.equal(
- await page.$eval('#sl-since-note', (node) =>
- node.hidden ? null : node.textContent,
- ),
- 'KartaView: by upload date',
+ await page.evaluate(() =>
+ window.__godsEyeView.dataManager.setEnabled('street-level', true, {
+ origin: 'user',
+ }),
);
+ await waitForCoverage(page);
+ await statusIs(page, 'ON');
assert.equal(
- await page.$eval(kvChip, (chip) =>
- chip.style.getPropertyValue('--chip-color'),
- ),
- '#635bff',
- );
- assert.match(
- await page.$eval('#sl-coverage-meta', (node) => node.textContent),
- /streets in view · click a line for its nearest photo/,
+ await page.$eval('#sl-controls', (node) => node.disabled),
+ false,
);
await page.waitForFunction(
() =>
@@@ -505,84 -2075,949 +633,121 @@@
() =>
document.getElementById('sl-image-when').textContent.trim()
.length > 0,
- null,
{ timeout: 30_000 },
);
- if (!filled) {
- const dump = await page.evaluate(() => {
- const u = window.__godsEyeView.dataManager.layers
- .get('street-level')
- .module.getUIState();
- return {
- street: u.street,
- captionNodes:
- document.querySelectorAll('#sl-image-when').length,
- captionNow:
- document.getElementById('sl-image-when').textContent,
- wrapHidden: document.getElementById('sl-viewer-wrap').hidden,
- collapsed: document
- .getElementById('street-level-panel')
- .classList.contains('collapsed'),
- };
- });
- throw new Error(`caption never filled: ${JSON.stringify(dump)}`);
- }
const view = await page.evaluate(() => ({
hidden: document.getElementById('sl-viewer-wrap').hidden,
- when: document.getElementById('sl-image-when').textContent.trim(),
- link: document.getElementById('sl-image-link').textContent.trim(),
- href: document.getElementById('sl-image-link').href,
- width: Math.round(
- document.getElementById('sl-viewer').getBoundingClientRect()
- .width,
- ),
+ width: document.getElementById('sl-viewer').getBoundingClientRect()
+ .width,
+ link: document.getElementById('sl-image-link').href,
}));
assert.equal(view.hidden, false);
- assert.ok(view.width > 200);
- assert.ok(view.when.length > 0, 'caption shows the capture date');
- assert.equal(street.providerId, 'mapillary');
- firstImageId = street.imageId;
- assert.equal(view.link, 'MAPILLARY ↗');
+ assert.ok(view.width > 200, `viewer width ${view.width}`);
+ assert.match(view.link, /mapillary\.com\/app\/\?pKey=/);
if (fixtures) {
- const known = fixtureIds.get(street.imageId);
- assert.ok(known, `a fixture photo opened (${street.imageId})`);
- assert.equal(street.isPano, known.isPano, 'pano flag from the ent');
- assert.equal(street.sequenceId, PHOTO_SEQUENCE_ID);
- }
- const fit = await page.evaluate(() => {
- const inner = document.querySelector('.street-level-panel-inner');
- const box = inner.getBoundingClientRect();
- const wrap = document
- .getElementById('sl-viewer-wrap')
- .getBoundingClientRect();
- return {
- scrollTop: inner.scrollTop,
- top: wrap.top - box.top,
- overflowBottom: wrap.bottom - box.bottom,
- };
- });
- assert.equal(fit.scrollTop, 0, 'panel not scrolled');
- assert.ok(
- fit.top >= 0 && fit.top < 80,
- `viewer right under the header (${fit.top}px)`,
- );
- assert.ok(
- fit.overflowBottom <= 1,
- `whole viewer visible (${fit.overflowBottom}px cut)`,
- );
- assert.match(view.href, /mapillary\.com\/app\/\?pKey=/);
- // The open selects the photo's sequence: its cones are drawn.
- assert.ok(
- await uiUntil(
- (u) => u.sequence.selectedId === u.street.sequenceId,
- null,
- { timeout: 30_000 },
- ),
- 'the open photo’s sequence is selected',
- );
- },
- );
- if (fixtures)
- await step(
- 'a click on a neighbouring cone steps the viewer to that photo (360° and flat)',
- async () => {
- // Let the framing flight land, so the cone does not move under the click.
- await settle(
- page,
- () => !window.__godsEyeView.viewer.camera._currentFlight,
- null,
- { timeout: 10_000 },
- );
- await uiUntil((u) => u.sequence.images > 0 && !u.sequence.loading);
- const current = fixtureIds.get(firstImageId);
- const neighbour = [1, -1, 2, -2, 4, -4]
- .map((offset) => fixture.images[current.index + offset])
- .find((image) => image && image.isPano !== current.isPano);
- assert.ok(neighbour, 'a neighbour of the other camera type');
- const handle = await page.waitForFunction(
- findPickPoint,
- // A pick is a render; under SwiftShader on a busy machine one
- // evaluation can take seconds.
- { timeout: 30_000, polling: 250 },
- {
- prefix: 'mly:img:',
- id: neighbour.id,
- points: null,
- billboardIds: [`mly:img:${neighbour.id}`],
- },
- );
- const at = await handle.jsonValue();
- await page.mouse.click(at.x, at.y);
- await waitForImage(neighbour.id);
- const street = (await ui()).street;
- assert.equal(street.error, null);
- assert.equal(street.imageId, neighbour.id, 'stepped to the cone');
- assert.equal(street.isPano, neighbour.isPano);
- assert.notEqual(street.isPano, current.isPano, 'both kinds shown');
- await openById(firstImageId);
- },
- );
- else
- await skipStep(
- 'fixtures only',
- 'a click on a neighbouring cone steps the viewer to that photo',
- );
- await step(
- 'FOLLOW is offered only on the Google 3D map',
- async ({ skip }) => {
- const follow = () =>
- page.$eval('#sl-follow-btn', (node) => ({
- disabled: node.disabled,
- pressed: node.getAttribute('aria-pressed'),
- title: node.title,
- }));
- const followIs = (disabled, pressed = null) =>
- settle(
- page,
- ([d, p]) => {
- const node = document.getElementById('sl-follow-btn');
- return (
- node.disabled === d &&
- (p === null || node.getAttribute('aria-pressed') === p)
- );
- },
- [disabled, pressed],
- );
- const original = await stacks.active();
- await stacks.set('esri-imagery');
- await followIs(true);
- let state = await follow();
- assert.equal(state.disabled, true, 'disabled on Esri');
- assert.match(state.title, /needs the Google 3D map/);
- if (await stacks.photoreal()) {
- await stacks.set('photoreal');
- await followIs(false);
- state = await follow();
- assert.equal(state.disabled, false, 'enabled on Google 3D');
- await clickPanelControl(page, '#sl-follow-btn');
- await followIs(false, 'true');
- assert.equal((await follow()).pressed, 'true');
- await stacks.set('esri-imagery');
- await followIs(true, 'false');
- state = await follow();
- assert.equal(
- state.pressed,
- 'false',
- 'leaving Google 3D stops following',
- );
- assert.equal(state.disabled, true);
- } else {
- console.log(
- ' (Google 3D unavailable here: only the disabled path ran)',
- );
- skip('no Google 3D');
- }
- await stacks.set(original);
- },
- );
- await park();
- await step(
- 'closing a photo stops the framing flight toward it',
- async () => {
- // Opening frames the photo with a 1.6 s camera flight; closing right
- // away must cancel it, leaving the camera where it was.
- const result = await page.evaluate(async (id) => {
- const v = window.__godsEyeView.viewer;
- const module =
- window.__godsEyeView.dataManager.layers.get(
- 'street-level',
- ).module;
- const opened = await module.openImage('mapillary', id);
- const flying = Boolean(v.camera._currentFlight);
- const from = v.camera.positionCartographic.clone();
- module.closeViewer();
- const stillFlying = Boolean(v.camera._currentFlight);
- const frames = (n) =>
- new Promise((resolve) => {
- const tick = () =>
- --n <= 0 ? resolve() : requestAnimationFrame(tick);
- requestAnimationFrame(tick);
- });
- await frames(20);
- const to = v.camera.positionCartographic;
- return {
- opened,
- flying,
- stillFlying,
- moved: Math.hypot(
- (to.longitude - from.longitude) * 6_371_000,
- (to.latitude - from.latitude) * 6_371_000,
- to.height - from.height,
- ),
- height: to.height,
- };
- }, firstImageId);
- assert.equal(result.opened, true, 'the photo opened');
- assert.equal(result.flying, true, 'opening started a framing flight');
- assert.equal(result.stillFlying, false, 'closing cancelled it');
- assert.ok(
- result.moved < 0.5,
- `the camera stopped where it was (moved ${result.moved.toFixed(2)} m)`,
- );
- assert.ok(
- result.height > PARK.height / 2,
- `the camera never reached the photo (${Math.round(result.height)} m up)`,
- );
- assert.equal((await ui()).street.open, false);
- },
- );
- await step(
- 'coverage sits on the bare earth on Google 3D and drapes elsewhere',
- async ({ skip }) => {
- const surface = () =>
- page.evaluate(() => {
- const u = window.__godsEyeView.dataManager.layers
- .get('street-level')
- .module.getUIState();
- return { surface: u.surface, count: u.coverage.count };
- });
- const original = await stacks.active();
- await stacks.set('esri-imagery');
- await page.waitForFunction(
- () =>
- window.__godsEyeView.dataManager.layers
- .get('street-level')
- .module.getUIState().surface === 'draped',
- { timeout: 10_000 },
- );
- const coverageLoaded = () =>
- waitForCoverage(page, { timeout: 60_000 });
- await coverageLoaded();
- assert.equal((await surface()).surface, 'draped', 'draped on Esri');
- if (await stacks.photoreal()) {
- await stacks.set('photoreal');
- await page.waitForFunction(
- () =>
- window.__godsEyeView.dataManager.layers
- .get('street-level')
- .module.getUIState().surface === 'terrain',
- { timeout: 15_000 },
- );
- await coverageLoaded();
- assert.equal((await surface()).surface, 'terrain');
- } else {
- console.log(
- ' (Google 3D unavailable here: only the draped path ran)',
+ assert.ok(
+ fixture.images.some((image) => image.id === street.imageId),
+ `fixture photo ${street.imageId}`,
);
- skip('no Google 3D');
+ assert.equal(street.sequenceId, PHOTO_SEQUENCE_ID);
}
- await stacks.set(original);
- },
- );
- const expanded = () =>
- page.evaluate(() =>
- document
- .getElementById('sl-viewer-wrap')
- .classList.contains('sl-viewer-wrap-expanded'),
- );
- await step(
- 'EXPAND opens a modal dialog (the rest of <body> inert) and Esc returns focus to the button',
- async () => {
- await openById(firstImageId);
- const inertBefore = await page.evaluate(
- () =>
- [...document.body.children].filter((node) => node.inert).length,
- );
- await clickPanelControl(page, '#sl-viewer-expand');
- await settle(page, () =>
- document
- .getElementById('sl-viewer-wrap')
- .classList.contains('sl-viewer-wrap-expanded'),
- );
- const dialog = await page.evaluate(() => {
- const wrap = document.getElementById('sl-viewer-wrap');
- const others = [...document.body.children].filter(
- (node) => node !== wrap,
- );
- return {
- role: wrap.getAttribute('role'),
- modal: wrap.getAttribute('aria-modal'),
- inside: wrap.contains(document.activeElement),
- width: Math.round(wrap.getBoundingClientRect().width),
- onBody: wrap.parentElement === document.body,
- notInert: others
- .filter((node) => !node.inert)
- .map((node) => node.id || node.tagName.toLowerCase()),
- wrapInert: wrap.inert,
- };
- });
- assert.equal(dialog.role, 'dialog');
- assert.equal(dialog.modal, 'true');
- assert.equal(dialog.inside, true);
- assert.ok(dialog.width > 900);
- assert.equal(dialog.onBody, true);
- assert.deepEqual(
- dialog.notInert,
- [],
- 'every other body child is inert',
- );
- assert.equal(dialog.wrapInert, false);
- await page.keyboard.press('Escape');
- await settle(
- page,
- () =>
- !document
- .getElementById('sl-viewer-wrap')
- .classList.contains('sl-viewer-wrap-expanded'),
- );
- const after = await page.evaluate(() => ({
- expanded: document
- .getElementById('sl-viewer-wrap')
- .classList.contains('sl-viewer-wrap-expanded'),
- focus: document.activeElement?.id,
- inert: [...document.body.children].filter((node) => node.inert)
- .length,
- }));
- assert.equal(
- `${after.expanded}:${after.focus}`,
- 'false:sl-viewer-expand',
- );
- assert.equal(
- after.inert,
- inertBefore,
- 'the application is live again',
- );
- },
- );
- await step(
- '× closes the image and deselects it on the globe',
- async () => {
- await clickPanelControl(page, '#sl-viewer-close');
+ // Opening selects the photo's sequence, so its cones are drawn.
await uiUntil(
- (u) => !u.street.open && u.sequence.selectedId === null,
+ page,
+ (u) => u.sequence.selectedId === u.street.sequenceId,
);
- const after = await ui();
- assert.equal(after.street.open, false);
- assert.equal(after.sequence.selectedId, null);
},
);
- const floating = () =>
- page.$eval('#street-level-panel', (node) =>
- node.classList.contains('panel-floating'),
+
+ await step('× closes the photo and deselects its sequence', async () => {
+ await press(page, '#sl-viewer-close');
+ await uiUntil(
+ page,
+ (u) => !u.street.open && u.sequence.selectedId === null,
);
- const center = (selector) =>
- page.$eval(selector, (node) => {
- const r = node.getBoundingClientRect();
- return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
- });
- // Right after a dock the rail is still animating, so the shared helpers
- // re-resolve the header and retry only a press that provably missed it.
- const floatPanel = async () => {
- const attempt = await liftPanelByHeader(page, PANEL_ID, {
- dx: -400,
- dy: 80,
- });
assert.equal(
- attempt.done,
+ await page.$eval('#sl-viewer-wrap', (node) => node.hidden),
true,
- `a header drag lifts the panel out of the rail (${describePress(attempt)})`,
);
- assert.equal(await floating(), true);
- };
- await step(
- 'the panel floats on a header drag, resizes, and the viewer takes the room',
- async () => {
- await openById(firstImageId);
- await floatPanel();
- const viewerHeight = () =>
- page.$eval('#sl-viewer', (node) =>
- Math.round(node.getBoundingClientRect().height),
- );
- const before = await viewerHeight();
- const grip = await center('#street-level-panel .panel-resize-grip');
- await page.mouse.move(grip.x, grip.y);
- await page.mouse.down();
- await page.mouse.move(grip.x + 120, grip.y + 160, { steps: 10 });
- await page.mouse.up();
- await settle(
- page,
- (height) =>
- document.getElementById('sl-viewer').getBoundingClientRect()
- .height >
- height + 60,
- before,
- );
- const after = await viewerHeight();
+ });
+
++ await keylessProviderStep({
++ id: 'kartaview',
++ name: 'KartaView',
++ at: PARK,
++ linePrefix: 'kv:line:',
++ // A row across the middle crosses the drive, west of the old street.
++ box: null,
++ reset: resetKartaViewFixture,
++ check: (street) => {
++ assert.equal(street.sequenceId, KV_SEQUENCE_ID);
+ assert.ok(
- after > before + 60,
- `viewer grew with the window (${before} → ${after}px)`,
- );
- assert.equal(
- await page.$eval(
- '.sl-settings',
- (node) => getComputedStyle(node).overflowY,
- ),
- 'auto',
- 'only the settings block scrolls',
- );
- },
- );
- await step(
- 'SHRINK after EXPAND docks the window back in the rail at its default size, viewer inside the panel',
- async () => {
- await clickPanelControl(page, '#sl-viewer-expand');
- await settle(page, () =>
- document
- .getElementById('sl-viewer-wrap')
- .classList.contains('sl-viewer-wrap-expanded'),
- );
- assert.equal(await expanded(), true, 'expanded');
- await clickPanelControl(page, '#sl-viewer-expand');
- await settle(
- page,
- () =>
- !document
- .getElementById('street-level-panel')
- .classList.contains('panel-floating') &&
- !document
- .getElementById('sl-viewer-wrap')
- .classList.contains('sl-viewer-wrap-expanded'),
- );
- assert.equal(await floating(), false, 'docked again');
- const style = await page.$eval('#street-level-panel', (node) => ({
- width: node.style.width,
- height: node.style.height,
- parent: node.parentElement.id,
- }));
- assert.deepEqual(style, {
- width: '',
- height: '',
- parent: 'right-context-rail',
- });
- const home = await page.evaluate(() => {
- const wrap = document.getElementById('sl-viewer-wrap');
- return {
- inPanel: Boolean(wrap.closest('#street-level-panel')),
- onBody: wrap.parentElement === document.body,
- };
- });
- assert.deepEqual(
- home,
- { inPanel: true, onBody: false },
- 'the viewer returned into the panel',
++ kartaViewPhotos().some((photo) => photo.id === street.imageId),
++ `fixture photo ${street.imageId}`,
+ );
+ },
- );
- await step('a header double-click docks a floating window', async () => {
- await floatPanel();
- const attempt = await dockPanelByDoubleClick(page, PANEL_ID);
- assert.equal(
- attempt.done,
- true,
- `docked again (${describePress(attempt)})`,
- );
+ });
- await step(
- 'collapsing a floating window docks it as the rail strip',
- async () => {
- // The double-click just docked a panel showing a photo: let the photo
- // and its sequence finish loading before pressing the header again.
- await uiUntil((u) => !u.street.loading && !u.sequence.loading);
- await floatPanel();
- await clickPanelControl(
- page,
- '.panel-collapse-btn[data-collapse-target="street-level-panel"]',
- );
- await settle(page, () => {
- const node = document.getElementById('street-level-panel');
- return (
- node.classList.contains('collapsed') &&
- !node.classList.contains('panel-floating')
- );
- });
- const state = await page.$eval('#street-level-panel', (node) => ({
- floating: node.classList.contains('panel-floating'),
- collapsed: node.classList.contains('collapsed'),
- height: node.style.height,
- }));
- assert.deepEqual(state, {
- floating: false,
- collapsed: true,
- height: '',
- });
- },
- );
- await step(
- 'on a phone the whole photo fits in the docked panel',
- async () => {
- // Width alone drives the phone layout; toggling isMobile would reload.
- await page.setViewport({ width: 390, height: 844 });
- await settle(page, () => innerWidth === 390);
- if (
- await page.$eval('#street-level-panel', (node) =>
- node.classList.contains('collapsed'),
- )
- )
- await expandStrip();
- await openById(firstImageId);
- const measure = () =>
- page.evaluate(() => {
- const inner = document
- .querySelector('.street-level-panel-inner')
- .getBoundingClientRect();
- const meta = document
- .getElementById('sl-image-meta')
- .getBoundingClientRect();
- const viewer = document
- .getElementById('sl-viewer')
- .getBoundingClientRect();
- return {
- cut: Math.round(meta.bottom - inner.bottom),
- top: Math.round(viewer.top - inner.top),
- height: Math.round(viewer.height),
- overflowX: document.documentElement.scrollWidth > innerWidth,
- };
- });
- // The panel settles its phone layout over a frame or two.
- await settle(page, () => {
- const inner = document
- .querySelector('.street-level-panel-inner')
- .getBoundingClientRect();
- const meta = document
- .getElementById('sl-image-meta')
- .getBoundingClientRect();
- return (
- meta.bottom - inner.bottom <= 1 &&
- document.getElementById('sl-viewer').getBoundingClientRect()
- .height >= 100
- );
- });
- const fit = await measure();
- assert.ok(fit.cut <= 1, `photo and caption fit (${fit.cut}px cut)`);
- assert.ok(fit.height >= 100, `viewer stays usable (${fit.height}px)`);
- assert.equal(fit.overflowX, false, 'no sideways scroll');
- await page.setViewport(VIEWPORTS[0]);
- await settle(
- page,
- (width) => innerWidth === width,
- VIEWPORTS[0].width,
- );
- },
- );
- const googleChip = '#sl-provider-chips [data-chip-id="google"]';
- const googleKey = await page.evaluate(() =>
- Boolean(window.__GOOGLE_MAPS_API_KEY__),
- );
- await step(
- 'Street View starts off, appears only on the Google 3D map, and travels in the share link',
- async () => {
- const module = () =>
- window.__godsEyeView.dataManager.layers.get('street-level').module;
- assert.equal(
- await page.evaluate(`(${module})().getParams().google`),
- false,
- 'off until lit: panoramas are billed',
- );
- const setStreetView = (on) =>
- page.evaluate(
- (value) =>
- window.__godsEyeView.dataManager.setLayerParams(
- 'street-level',
- { google: value },
- { origin: 'user' },
- ),
- on,
- );
- const shown = () =>
- page.evaluate(() => ({
- chip: Boolean(
- document.querySelector(
- '#sl-provider-chips [data-chip-id="google"]',
- ),
- ),
- legend: [...document.querySelectorAll('#sl-legend li')].some(
- (item) => /Street View/.test(item.textContent),
- ),
- credit: document.body.innerHTML.includes('Street View imagery'),
- button: !document.getElementById('sl-nearest-btn').hidden,
- }));
- const original = await stacks.active();
- // Off Google 3D (CI's only map) nothing of Street View shows, even
- // switched on: Google's terms keep it off other maps.
- if (original === 'photoreal') await stacks.set('esri-imagery');
- await setStreetView(true);
- await uiUntil((u) => u.providers.every((p) => p.id !== 'google'));
- assert.ok(
- await settle(
- page,
- () => !document.body.innerHTML.includes('Street View imagery'),
- ),
- 'no Google credit on another map',
- );
- assert.deepEqual(await shown(), {
- chip: false,
- legend: false,
- credit: false,
- button: false,
- });
- // Street View rides the shared provider-switch field (r), beside
- // the other providers' switches a chip click recorded.
- const option = `${STREET_LEVEL_TOKEN}.r.google-1`;
++ await keylessProviderStep({
++ id: 'panoramax',
++ name: 'Panoramax',
++ at: PNX_PARK,
++ linePrefix: 'pnx:seq:',
++ // The street runs east-west: scan a column left of the middle.
++ box: 'column',
++ reset: resetPanoramaxFixture,
++ check: (street, lineId) => {
++ assert.equal(street.sequenceId, lineId, 'the line clicked');
+ assert.ok(
- await settle(
- page,
- (prefix) =>
- (new URLSearchParams(location.hash.slice(1)).get('lo') || '')
- .split('_')
- .some(
- (entry) =>
- entry.startsWith(prefix) &&
- entry
- .slice(prefix.length)
- .split('*')
- .includes('google-1'),
- ),
- `${STREET_LEVEL_TOKEN}.r.`,
- // The link is written once the view rests for 500 ms; under a
- // software renderer with a photo open that can take a while.
- { timeout: 30_000 },
- ),
- `the share link keeps the choice: ${option}`,
- );
- if (await stacks.photoreal()) {
- await stacks.set('photoreal');
- await uiUntil((u) => u.providers.some((p) => p.id === 'google'));
- const chipNow = await page.$eval(googleChip, (node) => ({
- className: node.className,
- title: node.title,
- color: node.style.getPropertyValue('--chip-color'),
- }));
- assert.equal(chipNow.color, '#4285f4');
- if (googleKey) assert.match(chipNow.className, /chip-active/);
- else {
- assert.match(chipNow.className, /chip-error/);
- assert.match(chipNow.title, /GOOGLE_MAPS_API_KEY/);
- }
- assert.ok(
- await settle(page, () =>
- document.body.innerHTML.includes('Street View imagery'),
- ),
- 'the Google credit shows on Google 3D',
- );
- }
- // Back to Mapillary (one source at a time), as the next steps expect.
- await page.evaluate(() =>
- window.__godsEyeView.dataManager.setLayerParams(
- 'street-level',
- { mapillary: true, google: false },
- { origin: 'user' },
- ),
- );
- await stacks.set(original);
- await uiUntil(
- (u) => u.providers.find((p) => p.id === 'google')?.on !== true,
++ panoramaxPictures().some((photo) => photo.id === street.imageId),
++ `fixture picture ${street.imageId}`,
+ );
+ },
- );
- await step(
- 'on Google 3D a click on a street opens Google Street View where it is, captioned and linked, and its view drives the pose',
- async ({ skip }) => {
- if (!googleKey) return skip('no Google key');
- // Google's terms: Street View only beside Google's own map.
- if (!(await stacks.photoreal())) return skip('no Google 3D');
- const original = await stacks.active();
- const closePhoto = () =>
- page.evaluate(() =>
- window.__godsEyeView.dataManager.layers
- .get('street-level')
- .module.closeViewer(),
- );
- const setOn = async (selector, id, on) => {
- const now = (await ui()).providers.find((p) => p.id === id)?.on;
- if (now === on) return;
- await clickPanelControl(page, selector);
- assert.ok(
- await uiUntil(
- (u, want) =>
- u.providers.find((p) => p.id === want.id)?.on === want.on,
- { id, on },
- ),
- `the ${id} chip switched ${on ? 'on' : 'off'}`,
- );
- };
- await closePhoto();
- await stacks.set('photoreal');
- // A Mapillary line under the pointer wins the click: aim at bare
- // ground with only Street View on (lit first: the last lit chip
- // would switch the layer off).
- await setOn(googleChip, 'google', true);
- await setOn(chip, 'mapillary', false);
- try {
- const street = STREET_VIEW_STREET;
- await page.evaluate((at) => {
- const v = window.__godsEyeView.viewer;
- v.camera.cancelFlight?.();
- const C = v.camera.positionCartographic.constructor;
- v.camera.setView({
- destination: v.scene.globe.ellipsoid.cartographicToCartesian(
- C.fromDegrees(at.lon, at.lat, 300),
- ),
- orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
- });
- }, street);
- // At street zoom the hint invites the click.
- assert.ok(
- await uiUntil(
- (u) =>
- u.providers.find((p) => p.id === 'google')?.hint ===
- 'click a street to open Street View',
- ),
- 'the click hint shows at street zoom',
- );
- const camera = () =>
- page.evaluate(() => {
- const c = window.__godsEyeView.viewer.camera.positionWC;
- return [c.x, c.y, c.z];
- });
- const at = await page.evaluate((point) => {
- const v = window.__godsEyeView.viewer;
- const C = v.camera.positionCartographic.constructor;
- const ground = v.scene.globe.ellipsoid.cartographicToCartesian(
- C.fromDegrees(point.lon, point.lat, 0),
- );
- const canvas = v.scene.cartesianToCanvasCoordinates(ground);
- const box = v.scene.canvas.getBoundingClientRect();
- return (
- canvas && { x: box.left + canvas.x, y: box.top + canvas.y }
- );
- }, street);
- assert.ok(at, 'the street is on screen');
- const before = await camera();
- await page.mouse.click(at.x, at.y);
- await uiUntil(
- (u) =>
- Boolean(u.street.error) ||
- (u.street.providerId === 'google' &&
- Boolean(u.street.imageId) &&
- !u.street.loading),
- null,
- { timeout: 30_000 },
- );
- const opened = (await ui()).street;
- if (/refused GOOGLE_MAPS_API_KEY/.test(opened.error || ''))
- return skip('Google key refused');
- if (/did not answer/.test(opened.error || ''))
- return skip('Google did not answer');
- assert.equal(opened.error, null);
- assert.equal(opened.providerId, 'google');
- const after = await camera();
- assert.ok(
- Math.hypot(...after.map((v, i) => v - before[i])) < 1,
- 'the camera stays where the user clicked',
- );
- const shown = await page.evaluate(() => ({
- by: document.getElementById('sl-image-by').textContent,
- when: document.getElementById('sl-image-when').textContent,
- label: document.getElementById('sl-image-link').textContent,
- href: document.getElementById('sl-image-link').href,
- fitFillHidden:
- document.querySelector('[data-sl-render]').parentElement.hidden,
- panorama: Boolean(
- document.querySelector('#sl-viewer .sl-google-panorama'),
- ),
- mapillaryLeft: Boolean(
- document.querySelector('#sl-viewer .mapillary-dom'),
- ),
- }));
- assert.match(shown.by, /Image by /);
- assert.match(shown.when, /\d{4}-\d{2}$/, 'dated by month');
- assert.equal(shown.label, 'GOOGLE STREET VIEW ↗');
- assert.match(shown.href, /map_action=pano&pano=/);
- assert.equal(shown.fitFillHidden, true, 'no FIT/FILL for Google');
- assert.equal(shown.panorama, true);
- assert.equal(shown.mapillaryLeft, false, 'no viewer left under it');
- // A real drag turns Google's view, and the pose follows it.
- const box = await page.$eval(
- '#sl-viewer .sl-google-panorama',
- (node) => {
- const r = node.getBoundingClientRect();
- return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
- },
- );
- await page.mouse.move(box.x, box.y);
- await page.mouse.down();
- await page.mouse.move(box.x - 120, box.y, { steps: 12 });
- await page.mouse.up();
- assert.ok(
- await uiUntil(
- (u, start) =>
- Number.isFinite(u.street.bearing) &&
- Math.abs(u.street.bearing - start) > 5,
- opened.bearing ?? 0,
- { timeout: 10_000 },
- ),
- 'the pose bearing follows the drag',
- );
- // The keyboard path: OPEN STREET VIEW at the view centre.
- await closePhoto();
- await uiUntil((u) => u.street.open === false);
- await clickPanelControl(page, '#sl-nearest-btn');
- assert.ok(
- await uiUntil(
- (u) =>
- u.street.providerId === 'google' &&
- Boolean(u.street.imageId) &&
- !u.street.loading,
- null,
- { timeout: 30_000 },
- ),
- 'OPEN STREET VIEW opens the panorama at the view centre',
- );
- // Leaving Google 3D closes the panorama (Google's terms).
- await stacks.set('esri-imagery');
- assert.ok(
- await uiUntil((u) => u.street.open === false),
- 'the panorama closes off Google 3D',
- );
- } finally {
- await closePhoto();
- // Off Google 3D the Street View chip is hidden: return to it
- // before switching the chip, or the cleanup throws and hides
- // the step's own result.
- await stacks.set('photoreal');
- await setOn(chip, 'mapillary', true);
- await setOn(googleChip, 'google', false);
- await stacks.set(original);
- }
++ });
++ // Back to Mapillary, where the next page and a reload expect it.
++ await press(page, '#sl-provider-chips [data-chip-id="mapillary"]');
++ await uiUntil(page, litAlone, 'mapillary');
++ await park(page);
++
+ await fixtureStep(
+ 'keyless server (second page): KEY REQUIRED gates the controls',
+ async () => {
+ const keyless = await open(
+ 'keyless',
+ newFixture({ configured: false }),
+ );
+ await expandPanel(keyless);
+ await assertKeyRequired(keyless);
+ await collectRenderErrors(keyless, 'keyless');
+ await keyless.close();
},
);
- await kartaViewSteps();
- await panoramaxSteps();
- await step(
- 'a reload with the layer on keeps a collapsed panel collapsed, and the share link carries its ui token',
- async () => {
- await page.evaluate(() =>
- window.__godsEyeView.dataManager.layers
- .get('street-level')
- .module.closeViewer(),
- );
- // Press through the DOM: a toast over the button must not make this
- // step about pointer aim.
- await page.$eval(
- '.panel-collapse-btn[data-collapse-target="street-level-panel"]',
- (button) => {
- const panel = document.getElementById('street-level-panel');
- if (!panel.classList.contains('collapsed')) button.click();
- },
- );
- assert.ok(
- await settle(page, () =>
- document
- .getElementById('street-level-panel')
- .classList.contains('collapsed'),
- ),
- 'the panel collapsed',
- );
- const shared = (collapsed) =>
- settle(
- page,
- (assignment) =>
- (new URLSearchParams(location.hash.slice(1)).get('ui') || '')
- .split('_')
- .includes(assignment),
- `${PANEL_UI_TOKEN}.c.${collapsed ? '1' : '0'}`,
- );
- assert.ok(
- await shared(true),
- `the share link records the collapsed panel as ui ${PANEL_UI_TOKEN}.c.1: ${await page.evaluate(() => location.hash)}`,
- );
- await page.reload({ waitUntil: 'domcontentloaded' });
- await clearFirstRun(page);
- await waitForCoverage(page);
- // The panel would open on the enable transition, before coverage.
- const after = await page.evaluate(() => ({
- enabled: window.__godsEyeView.dataManager.isEnabled('street-level'),
- collapsed: document
- .getElementById('street-level-panel')
- .classList.contains('collapsed'),
- }));
- assert.deepEqual(
- after,
- { enabled: true, collapsed: true },
- 'the restored layer did not reopen the panel',
- );
- assert.ok(await shared(true), 'still shared as collapsed');
+
+ await fixtureStep(
- 'every Mapillary request was answered from a fixture',
++ 'every Mapillary, KartaView and Panoramax request was answered from a fixture',
+ () => {
+ console.log(` (answered: ${[...fixture.calls].sort().join(' | ')})`);
+ assert.deepEqual(fixture.unknown, []);
},
);
- if (fixtures)
- await step(
- 'keyless install (a second page, no key on the server) gates the controls and reports KEY REQUIRED, and KartaView draws there',
- async () => {
- const keyless = await browser.newPage();
- await keyless.setViewport(VIEWPORTS[0]);
- await watch(keyless, 'keyless');
- await serveFixtures(keyless, newFixture({ configured: false }));
- await boot(keyless, url);
- await expandStrip(keyless);
- await assertKeylessGate(keyless);
- await assertKeylessKartaView(keyless);
- renderErrorsSeen.push(
- ...(await readRenderErrors(keyless)).map(
- (text) => `[keyless] scene.renderError: ${text}`,
- ),
- );
- await keyless.close();
- },
- );
- else
- await skipStep(
- 'fixtures only',
- 'keyless install (a second page) reports KEY REQUIRED',
- );
- if (fixtures)
- await step(
- 'every Mapillary, KartaView and Panoramax request was answered from a fixture',
- () => {
- console.log(
- ` (answered: ${[...fixture.calls].sort().join(' | ')})`,
- );
- assert.deepEqual(fixture.unknown, [], 'no unanswered call');
- },
- );
}
+
+ await step('no page errors and no Cesium render-loop errors', async () => {
+ await collectRenderErrors(page, 'main');
+ assert.deepEqual(errors, []);
+ });
+ if (strict)
+ await step('strict: no skips other than "fixtures only"', () =>
+ assert.deepEqual(
+ skips.filter((reason) => reason !== 'fixtures only'),
+ [],
+ ),
+ );
+ console.log(
+ `${count} steps: ${count - skips.length} ok, ${skips.length} skipped`,
+ );
} catch (error) {
const dir = await saveFailureArtifacts({
- dir: ARTIFACT_DIR,
+ dir: 'qa-artifacts/street-level',
browser,
monitors,
error,
diff --cc src/app/layers/streetLevel.js
index 44b4bfa52,b441d12d7..268216eaa
--- a/src/app/layers/streetLevel.js
+++ b/src/app/layers/streetLevel.js
@@@ -3,21 -6,47 +6,37 @@@ import { createPanoramaxProvider } fro
import * as sprites from '../../data/spriteOrder.js';
import * as picking from '../../data/pickRegistry.js';
import * as input from '../../data/inputOwnership.js';
+ import * as scenePick from '../../data/scenePick.js';
import * as render from '../../renderGovernor.js';
+ /** The browser Maps key the scene was started with (src/app/scene.js). */
+ const googleApiKey = () => globalThis.window?.__GOOGLE_MAPS_API_KEY__ || null;
+
+ /**
+ * Mapillary, Google Street View, KartaView and Panoramax, once the Mapillary
+ * source is supplied; else none.
+ */
+ function defaultProviders(sources) {
+ if (sources.mapillary == null) return [];
+ return [
+ createMapillaryProvider({ source: sources.mapillary }),
+ createGoogleProvider({ getApiKey: googleApiKey }),
+ createKartaViewProvider(),
+ createPanoramaxProvider(),
+ ];
+ }
+
/**
- * Inject providers, or use Mapillary only when its source is supplied.
- * An explicit provider list replaces the default; an unused sources.mapillary
- * is neither constructed nor validated, including when the list is empty.
+ * Inject providers, or use the defaults. An explicit provider list replaces
+ * them; an unused sources.mapillary is neither constructed nor validated,
+ * including when the list is empty.
*/
export function createApplicationStreetLevel({
- surface,
sources = {},
- providers = sources.mapillary == null
- ? []
- : [createMapillaryProvider({ source: sources.mapillary })],
+ providers = defaultProviders(sources),
}) {
return createStreetLevelLayer({
providers,
- services: { sprites, picking, input, render },
- services: {
- sprites,
- picking,
- input,
- scenePick,
- render,
- ground: surface?.groundFloor ?? null,
- meshFloor: surface?.meshFloor ?? null,
- terrain: surface?.terrain ?? null,
- },
++ services: { sprites, picking, input, scenePick, render },
});
}
diff --cc src/i18n/locales/es.json
index 000000000,b5b0a3abb..0e77a0e8e
mode 000000,100644..100644
--- a/src/i18n/locales/es.json
+++ b/src/i18n/locales/es.json
@@@ -1,0 -1,2893 +1,2889 @@@
+ {
+ "NO PLACE LEFT BEHIND": "NINGÚN RINCÓN SIN VIGILAR",
+ "Initializing photorealistic world...": "Inicializando el mundo fotorrealista...",
+ "Configuring viewer...": "Configurando el visor...",
+ "Google 3D Tiles unavailable ({detail}). Loading the keyless globe...": "Google 3D Tiles no disponibles ({detail}). Cargando el globo sin clave...",
+ "Flying to Austin, TX...": "Volando a Austin, TX...",
+ "Restoring shared view...": "Restaurando la vista compartida...",
+ "LOADING LIVE DATA": "CARGANDO DATOS EN VIVO",
+ "LOAD COMPLETE": "CARGA COMPLETA",
+ "LOAD FAILED": "CARGA FALLIDA",
+ "LOAD CANCELLED": "CARGA CANCELADA",
+ "syncing road network": "sincronizando la red vial",
+ "retrying in {seconds}s": "reintento en {seconds} s",
+ "retry pending": "reintento pendiente",
+ "Clear selected data layers": "Limpiar las capas de datos seleccionadas",
+ "Turn off all selected data layers": "Desactivar todas las capas de datos seleccionadas",
+ "Copy share link": "Copiar enlace para compartir",
+ "Reset to full globe view": "Restablecer la vista del globo completo",
+ "DATA LAYERS": "CAPAS DE DATOS",
+ "Collapse panel": "Contraer panel",
+ "Navigation, voice, and visual preset controls": "Controles de navegación, voz y preajustes visuales",
+ "Globe actions": "Acciones del globo",
+ "Reset camera and return to full globe view": "Restablecer la cámara y volver a la vista del globo completo",
+ "loading frames": "cargando fotogramas",
+ "Language: {language}": "Idioma: {language}",
+ "Change the interface language": "Cambiar el idioma de la interfaz",
+ "Interface language": "Idioma de la interfaz",
+ "Search languages": "Buscar idioma",
+ "No matching languages": "No hay idiomas que coincidan",
+ "Loading Google 3D Tiles...": "Cargando Google 3D Tiles...",
+ "Loading the keyless globe...": "Cargando el globo sin clave...",
+ "Initializing systems...": "Inicializando sistemas...",
+ "LIVE DATA OFF": "DATOS EN VIVO DESACTIVADOS",
+ "MAPPED SITES LOADED": "SITIOS MAPEADOS CARGADOS",
+ "RETRYING MAPPED SITES": "REINTENTANDO SITIOS MAPEADOS",
+ "FETCHING MAPPED SITES": "OBTENIENDO SITIOS MAPEADOS",
+ "TURNING OFF LIVE DATA": "DESACTIVANDO DATOS EN VIVO",
+ "REFRESHING LIVE DATA": "ACTUALIZANDO DATOS",
+ "Close data attribution": "Cerrar la atribución de datos",
+ "Aircraft cockpit view": "Vista de cabina de la aeronave",
+ "EXIT COCKPIT": "SALIR DE CABINA",
+ "GROUND SPEED": "VEL. SUELO",
+ "ALTITUDE": "ALTITUD",
+ "CONTACT": "CONTACTO",
+ "CONTACTS · 250 KM": "CONTACTOS · 250 KM",
+ "LIVE SIGNALS": "SEÑALES EN VIVO",
+ "OBSERVED / MAPPED PINGS": "PINGS OBSERVADOS / MAPEADOS",
+ "CURRENT": "ACTUAL",
+ "READY": "LISTA",
+ "ACTIVE STYLE": "ESTILO ACTUAL",
+ "Return UI controls": "Volver a mostrar los controles de la interfaz",
+ "EXIT CLEAN VIEW": "SALIR DE VISTA LIMPIA",
+ "Expand Visual Presets": "Expandir Preajustes visuales",
+ "VISUAL PRESETS": "PREAJUSTES",
+ "Pin visual presets": "Fijar Preajustes visuales",
+ "Keep visual presets open": "Mantener abiertos los Preajustes visuales",
+ "Show the globe without a visual filter.": "Muestra el globo sin filtro visual.",
+ "Normal": "Normal",
+ "Emulate a green phosphor CRT with scanlines and screen curvature.": "Emula un CRT de fósforo verde con líneas de barrido y curvatura de pantalla.",
+ "CRT": "CRT",
+ "Simulate night-vision goggles with green intensification and a tube vignette.": "Simula unas gafas de visión nocturna con intensificación verde y viñeta de tubo.",
+ "NVG": "NVG",
+ "Simulate FLIR-style thermal contrast. Turn up Ironbow for color.": "Simula un contraste térmico estilo FLIR. Sube Ironbow para tener color.",
+ "FLIR": "FLIR",
+ "Apply bright cel-shaded color and illustrated outlines.": "Aplica un color brillante de cel-shading y contornos ilustrados.",
+ "Anime": "Anime",
+ "Apply high-contrast monochrome film-noir grading.": "Aplica una gradación monocroma de alto contraste estilo film noir.",
+ "Noir": "Noir",
+ "Add a cold, snowy whiteout treatment to the scene.": "Añade a la escena un tratamiento frío de ventisca blanca.",
+ "Snow": "Nieve",
+ "MAP SOURCE": "FUENTE DEL MAPA",
+ "Map source": "Fuente del mapa",
+ "Style": "Estilo",
+ "DISPLAY": "VISUALIZACIÓN",
+ "Intelligence HUD (H)": "HUD de inteligencia (H)",
+ "Layout": "Disposición",
+ "HUD layout": "Disposición del HUD",
+ "Tactical": "Táctica",
+ "Operator": "De operador",
+ "Minimal": "Mínima",
+ "Detection Overlay (D)": "Superposición de detección (D)",
+ "Detection overlay": "Superposición de detección",
+ "DETECT": "DETECTAR",
+ "Density": "Densidad",
+ "Detection label density": "Densidad de etiquetas de detección",
+ "Allocation": "Asignación",
+ "Detection label allocation": "Asignación de etiquetas de detección",
+ "Elastic": "Elástica",
+ "Weighted": "Ponderada",
+ "Fade": "Desvanecimiento",
+ "Detection fade distance": "Distancia de desvanecimiento de detección",
+ "World-overlay fade distance outside the keyhole as a percentage of its radius": "Distancia de desvanecimiento de la superposición del mundo fuera del ojo de cerradura, como porcentaje de su radio",
+ "Outside": "Exterior",
+ "Detection opacity outside the keyhole": "Opacidad de detección fuera del ojo de cerradura",
+ "World-overlay label and card opacity beyond the fade distance": "Opacidad de etiquetas y tarjetas de la superposición del mundo más allá de la distancia de desvanecimiento",
+ "PARAMETERS": "PARÁMETROS",
+ "3D aircraft — flat icons zoomed out, 3D models up close": "Aeronaves 3D — iconos planos de lejos, modelos 3D de cerca",
+ "Models": "Modelos",
+ "3D model coverage": "Cobertura de modelos 3D",
+ "Proximity": "Proximidad",
+ "All": "Todos",
+ "Scope — the circular viewport mask": "Mirilla — la máscara circular del visor",
+ "Scope": "Mirilla",
+ "Feather": "Difuminado",
+ "Scope edge feather as a percentage of the keyhole radius": "Difuminado del borde de la mirilla como porcentaje del radio del ojo de cerradura",
+ "Celestial ring — reveal the full globe": "Anillo celestial — muestra el globo completo",
+ "Celestial": "Cielo",
+ "Hide UI chrome": "Ocultar los elementos de la interfaz",
+ "Clean UI": "Interfaz limpia",
+ "Bloom / Glow": "Resplandor",
+ "Bloom": "Resplandor",
+ "Sharpening": "Nitidez",
+ "Sharpen": "Nitidez",
+ "LOCATION": "UBICACIÓN",
+ "Pin location tray": "Fijar bandeja de ubicación",
+ "Keep location tray open": "Mantener abierta la bandeja de ubicación",
+ "📍 Location: --": "📍 Ubicación: --",
+ "Landmark: --": "Punto de interés: --",
+ "Search any location": "Buscar un lugar",
+ "Search any location...": "Buscar un lugar…",
+ "LEVEL": "NIVEL",
+ "Estimated destination direction": "Dirección estimada del destino",
+ "DEST ---°": "DEST ---°",
+ "OPTICAL PLANE · 01": "PLANO ÓPTICO · 01",
+ "VISOR LOCK · ACTIVE": "BLOQUEO DE VISERA · ACTIVO",
+ "FIRST PERSON": "PRIMERA PERSONA",
+ "LIVE TRACK · COURSE ALIGNED": "RASTREO EN VIVO · RUMBO ALINEADO",
+ "Cockpit vision style": "Estilo de visión de la cabina",
+ "Current aircraft heading": "Rumbo actual de la aeronave",
+ "GROUND SPEED · KTS": "VEL. SUELO · KN",
+ "ALTITUDE · FT": "ALTITUD · FT",
+ "PREV": "ANT.",
+ "Previous cockpit vision style": "Estilo de visión de cabina anterior",
+ "Previous vision style": "Estilo de visión anterior",
+ "Current cockpit vision style: NORMAL. Activate for next style.": "Estilo de visión de cabina actual: NORMAL. Actívalo para pasar al siguiente estilo.",
+ "Current style: NORMAL — click for next": "Estilo actual: NORMAL — haz clic para el siguiente",
+ "NEXT": "SIG.",
+ "Next cockpit vision style": "Siguiente estilo de visión de cabina",
+ "Next vision style": "Siguiente estilo de visión",
+ "View switcher": "Selector de vistas",
+ "Reset cockpit to full globe view": "Restablecer la cabina a la vista de globo completo",
+ "Exit cockpit and return to full globe view": "Salir de la cabina y volver a la vista de globo completo",
+ "RESET": "RESTABLECER",
+ "Exit cockpit view": "Salir de la vista de cabina",
+ "Estimated flight plan": "Plan de vuelo estimado",
+ "ESTIMATED FLIGHT PLAN": "PLAN DE VUELO ESTIMADO",
+ "ROUTE DATA UNAVAILABLE": "DATOS DE RUTA NO DISPONIBLES",
+ "FROM": "DESDE",
+ "TO": "HACIA",
+ "UNKNOWN": "DESCONOCIDO",
+ "Cockpit briefing carousel": "Carrusel de información de la cabina",
+ "Cockpit briefing controls": "Controles de información de la cabina",
+ "Previous briefing page": "Página de información anterior",
+ "Next briefing page": "Página de información siguiente",
+ "Cycle briefing pages automatically every 9 seconds (Signals → News → Local). Pauses while you hover or focus the panel. Live signal data refreshes continuously either way.": "Cambia las páginas de información automáticamente cada 9 segundos (Señales → Noticias → Local). Se pausa mientras pasas el cursor por el panel o lo enfocas. Los datos de señales en vivo se actualizan continuamente de todos modos.",
+ "Collapse cockpit briefing panel": "Contraer el panel de información de la cabina",
+ "Collapse briefing panel": "Contraer el panel de información",
+ "Live signals": "Señales en vivo",
+ "Latest regional news": "Últimas noticias regionales",
+ "Location-based information": "Información basada en la ubicación",
+ "ACQUIRING REGIONAL NEWS": "OBTENIENDO NOTICIAS DE ZONA",
+ "RESOLVING REGION": "DETERMINANDO REGIÓN",
+ "TEMP": "TEMP.",
+ "WIND": "VIENTO",
+ "SKY": "CIELO",
+ "PRECIP": "PRECIP.",
+ "SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS": "EVENTOS CON FUENTE · SIN NOTICIAS SINTÉTICAS",
+ "Show Live Signals": "Mostrar Señales en vivo",
+ "Show Regional News": "Mostrar noticias de zona",
+ "Show Local Info": "Mostrar Información local",
+ "Contact cockpit summary": "Resumen de contacto de la cabina",
+ "Contact navigation": "Navegación de contactos",
+ "Previous — prior visited contact in the 250 km window": "Anterior — contacto ya visitado en la ventana de 250 km",
+ "Next — nearest unvisited contact in the 250 km window": "Siguiente — contacto sin visitar más cercano en la ventana de 250 km",
+ "Collapse Contact panel": "Contraer el panel de contacto",
+ "Collapse contact panel": "Contraer el panel de contacto",
+ "CONTEXT ONLY": "SOLO CONTEXTO",
+ "Nearby cohort counts": "Recuento de grupos cercanos",
+ "NEAREST OBSERVED / MAPPED": "MÁS CERCANO OBSERVADO / MAPEADO",
+ "NO AVAILABLE EXAMPLE": "SIN EJEMPLO DISPONIBLE",
+ "AVAILABLE INPUTS ONLY · NOT AN ALL-CLEAR": "SOLO DATOS DISPONIBLES · NO IMPLICA TODO DESPEJADO",
+ "Enable cockpit weather effects": "Activar los efectos climáticos de la cabina",
+ "CONTEXT": "CONTEXTO",
+ "Expand panel": "Expandir panel",
+ "Context mode": "Modo de contexto",
+ "CONTACTS": "CONTACTOS",
+ "Cycles the nearest contacts of whatever type you select — planes, vessels, installations. Satellites track independently.": "Recorre los contactos más cercanos del tipo que elijas — aeronaves, buques, instalaciones. Los satélites se rastrean por separado.",
+ "SPACE MISSIONS": "MISIONES ESPACIALES",
+ "SELECT CONTEXT": "SELECCIONAR CONTEXTO",
+ "Contact Context actions": "Acciones de contexto de contacto",
+ "COCKPIT": "CABINA",
+ "SEARCH NEARBY SITES": "BUSCAR SITIOS CERCANOS",
+ "Reclassify tracked contact as TR-3B": "Reclasificar el contacto rastreado como TR-3B",
+ "Reclassify as TR-3B": "Reclasificar como TR-3B",
+ "CONTACTS CONTEXT OFF": "CONTEXTO DE CONTACTOS DESACTIVADO",
+ "SELECT CONTACTS TO LOAD OBSERVED / MAPPED PROXIMITY": "SELECCIONA CONTACTOS PARA CARGAR LA PROXIMIDAD OBSERVADA / MAPEADA",
+ "Available Space Missions": "Misiones espaciales disponibles",
+ "AVAILABLE MISSIONS": "MISIONES DISPONIBLES",
+ "SELECT A MISSION TO INSPECT": "SELECCIONA UNA MISIÓN PARA INSPECCIONAR",
+ "LOADING 30-DAY MISSION INDEX": "CARGANDO ÍNDICE DE MISIONES DE 30 DÍAS",
+ "Open compact Radio controls": "Abrir los controles compactos de Radio",
+ "Compact Radio controls": "Controles compactos de Radio",
+ "RADIO": "RADIO",
+ "RADIO READY": "RADIO LISTA",
+ "Open detailed Radio controls": "Abrir los controles detallados de Radio",
+ "Close compact Radio controls": "Cerrar los controles compactos de Radio",
+ "ENABLE": "ACTIVAR",
+ "Previous filtered radio station": "Emisora de radio filtrada anterior",
+ "Previous station": "Emisora anterior",
+ "Play selected radio station": "Reproducir la emisora de radio seleccionada",
+ "Play": "Reproducir",
+ "Next filtered radio station": "Siguiente emisora de radio filtrada",
+ "Next station": "Siguiente emisora",
+ "VOLUME": "VOLUMEN",
+ "Compact Radio volume": "Volumen de la Radio compacta",
+ "Cockpit display and Radio controls": "Controles de visualización y Radio de la cabina",
+ "Expand Cockpit display options": "Expandir las opciones de visualización de la cabina",
+ "Cockpit display options": "Opciones de visualización de la cabina",
+ "Expand Cockpit Radio controls": "Expandir los controles de Radio de la cabina",
+ "Cockpit compact Radio controls": "Controles compactos de Radio de la cabina",
+ "Cockpit Radio volume": "Volumen de la Radio de la cabina",
+ "Expand {name}": "Expandir {name}",
+ "Collapse {name}": "Contraer {name}",
+ "panel": "panel",
+ "Collapse Radio": "Contraer Radio",
+ "Collapse Radio section": "Contraer la sección de Radio",
+ "Searched location": "Ubicación buscada",
+ "Disable cockpit weather effects": "Desactivar los efectos climáticos de la cabina",
+ "ON": "ACTIVO",
+ "OFF": "INACTIVO",
+ "Restore real aircraft": "Restaurar la aeronave real",
+ "Night vision": "Visión nocturna",
+ "Thermal": "Térmica",
+ "Current cockpit vision style: {style}. Activate for next style.": "Estilo de visión de cabina actual: {style}. Actívalo para pasar al siguiente estilo.",
+ "Current style: {style} — click for next": "Estilo actual: {style} — haz clic para el siguiente",
+ "TRACK ACQUIRED": "RASTREO ADQUIRIDO",
+ "{label} · COURSE {heading}°": "{label} · RUMBO {heading}°",
+ "Select flight {title}": "Seleccionar el vuelo {title}",
+ "CONTEXT STANDBY": "CONTEXTO EN ESPERA",
+ "ENABLE GLOBAL CONTEXT FOR PROXIMITY PINGS": "ACTIVAR CONTEXTO GLOBAL PARA PINGS DE PROXIMIDAD",
+ "CONTACT LOST · {subject}": "CONTACTO PERDIDO · {subject}",
+ "SUBJECT LEFT ITS FEED · READOUT HOLDING LAST KNOWN": "EL OBJETIVO SALIÓ DE SU FUENTE · LA LECTURA CONSERVA EL ÚLTIMO DATO CONOCIDO",
+ "MILITARY FLIGHT": "VUELO MILITAR",
+ "COMMERCIAL FLIGHT": "VUELO COMERCIAL",
+ "{aircraftClass} · CURRENT": "{aircraftClass} · ACTUAL",
+ "{aircraftClass} · {distance}": "{aircraftClass} · {distance}",
+ "DISTANCE UNKNOWN": "DISTANCIA DESCONOCIDA",
+ "{count} INPUTS UNKNOWN": {
+ "one": "{count} DATO DESCONOCIDO",
+ "many": "{count} DE DATOS DESCONOCIDOS",
+ "other": "{count} DATOS DESCONOCIDOS"
+ },
+ "SOURCE STATUS UNAVAILABLE": "ESTADO DE FUENTE NO DISPONIBLE",
+ "AIRCRAFT": "AERONAVE",
+ "MILITARY": "MILITAR",
+ "COMMERCIAL": "COMERCIAL",
+ "ACQUIRING SURFACE": "OBTENIENDO SUPERFICIE",
+ "SURFACE FALLBACK": "RESPALDO DE SUPERFICIE",
+ "STALE FEED": "FUENTE DESACTUALIZADA",
+ "LIVE TRACK": "RASTREO EN VIVO",
+ "{aircraftClass} · {feedState} · COURSE ALIGNED": "{aircraftClass} · {feedState} · RUMBO ALINEADO",
+ "ARROW · ESTIMATED DIRECTION": "FLECHA · DIRECCIÓN ESTIMADA",
+ "DEST {bearing}": "DEST {bearing}",
+ "CONTACT LOST · LAST KNOWN READOUT · NOT AN ALL-CLEAR": "CONTACTO PERDIDO · ÚLTIMA LECTURA CONOCIDA · NO IMPLICA TODO DESPEJADO",
+ "{count} INPUTS UNKNOWN · NOT AN ALL-CLEAR": {
+ "one": "{count} DATO DESCONOCIDO · NO IMPLICA TODO DESPEJADO",
+ "many": "{count} DE DATOS DESCONOCIDOS · NO IMPLICA TODO DESPEJADO",
+ "other": "{count} DATOS DESCONOCIDOS · NO IMPLICA TODO DESPEJADO"
+ },
+ "AVAILABLE INPUTS CURRENT · NOT AN ALL-CLEAR": "DATOS DISPONIBLES ACTUALIZADOS · NO IMPLICA TODO DESPEJADO",
+ "{cohort} · {contact}": "{cohort} · {contact}",
+ "{cohort}, Unavailable": "{cohort}, no disponible",
+ "BRG —": "BRG —",
+ "AHEAD": "AL FRENTE",
+ "{side} {angle}": "{side} {angle}",
+ "L": "I",
+ "R": "D",
+ "Expand Contact panel": "Expandir el panel de contacto",
+ "Expand contact panel": "Expandir el panel de contacto",
+ "Expand cockpit briefing panel": "Expandir el panel de información de la cabina",
+ "Expand briefing panel": "Expandir el panel de información",
+ "CYCLE ON": "CICLO: SÍ",
+ "CYCLE OFF": "CICLO: NO",
+ "Stop automatic page cycling. Previous, Next, and the SIG/NEWS/LOCAL tabs stay available.": "Detén el cambio automático de páginas. Anterior, Siguiente y las pestañas SIG/NOTICIAS/LOCAL siguen disponibles.",
+ "REGIONAL NEWS": "NOTICIAS DE ZONA",
+ "LOCAL INFO": "INFORMACIÓN LOCAL",
+ "LATEST LOCATION-MATCHED REPORTING": "ÚLTIMOS INFORMES SEGÚN UBICACIÓN",
+ "PLACE / CONDITIONS / POSITION": "LUGAR / CLIMA / POSICIÓN",
+ "POSITION UNAVAILABLE": "POSICIÓN NO DISPONIBLE",
+ "REGIONAL NEWS UNAVAILABLE": "NOTICIAS DE ZONA NO DISPONIBLES",
+ "REGION UNAVAILABLE": "REGIÓN NO DISPONIBLE",
+ "NO RECENT LOCATION MATCHES": "SIN COINCIDENCIAS RECIENTES DE UBICACIÓN",
+ "SOURCE": "FUENTE",
+ "{domain} · {age}": "{domain} · {age}",
+ "{source} · LOCATION QUERY": "{source} · CONSULTA POR UBICACIÓN",
+ "TIME UNKNOWN": "HORA DESCONOCIDA",
+ "{count}M AGO": "HACE {count} MIN",
+ "{count}H AGO": "HACE {count} H",
+ "{count}D AGO": "HACE {count} D",
+ "DIR UNKNOWN": "DIR DESCONOCIDA",
+ "CLOUD {pct}%": "NUBES {pct}%",
+ "CLOUD UNKNOWN": "NUBES DESCONOCIDAS",
+ "Panel layout updated — positions reset to new defaults": "Disposición de paneles actualizada — posiciones restablecidas a los nuevos valores predeterminados",
+ "Link copied!": "¡Enlace copiado!",
+ "Copy failed": "No se pudo copiar",
+ "Location not found": "Ubicación no encontrada",
+ "Search failed": "No se pudo completar la búsqueda",
+ "Fly to a POI first": "Ve primero a un punto de interés",
+ "Clearing selected data layers": "Limpiando las capas de datos seleccionadas",
+ "Selected data layers could not be cleared": "No se pudieron limpiar las capas de datos seleccionadas",
+ "ACQUIRING": "OBTENIENDO",
+ "entity": "entidad",
+ "SHARED {subject}": "{subject} COMPARTIDO",
+ "Shared {subject} follow expired": "El seguimiento de {subject} compartido ha caducado",
+ "Shared {subject} could not be restored — feed unavailable": "No se pudo restaurar {subject} compartido — fuente no disponible",
+ "Shared {subject} is unavailable": "{subject} compartido no está disponible",
+ "Context": "Contexto",
+ "Space Missions": "Misiones espaciales",
+ "{mode} could not start because another layer did not stop cleanly": "{mode} no pudo iniciarse porque otra capa no se detuvo correctamente",
+ "Contacts could not complete the requested transition; try again": "Contactos no pudo completar la transición solicitada; inténtalo de nuevo",
+ "Space Missions could not complete the requested transition; try again": "Misiones espaciales no pudo completar la transición solicitada; inténtalo de nuevo",
+ "Nearby installations could not be refreshed; try again": "No se pudieron actualizar las instalaciones cercanas; inténtalo de nuevo",
+ "Context could not restore every layer; try again": "Contexto no pudo restaurar todas las capas; inténtalo de nuevo",
+ "Zoom in to search mapped installations": "Acércate para buscar instalaciones mapeadas",
+ "Nearby installations refreshed": "Instalaciones cercanas actualizadas",
+ "That layer is unavailable in the current Context mode": "Esa capa no está disponible en el modo de contexto actual",
+ "start": "iniciarse",
+ "stop": "detenerse",
+ "{layerId} could not {action} cleanly": "{layerId} no pudo {action} correctamente",
+ "Radio could not {action} cleanly": "Radio no pudo {action} correctamente",
+ "camera grid ready": "cuadrícula de cámaras lista",
+ "CCTV calibration saved": "Calibración de CCTV guardada",
+ "CCTV calibration reset": "Calibración de CCTV restablecida",
+ "CCTV layer unavailable": "Capa de CCTV no disponible",
+ "MAP": "MAPA",
+ "CONTACTS — nearest planes · vessels · sites": "CONTACTOS — aeronaves · buques · sitios más cercanos",
+ "SPACE MISSIONS — launches & orbital assets": "MISIONES ESPACIALES — lanzamientos y activos orbitales",
+ "Space Missions cancellation could not restore the previous layer state": "La cancelación de Misiones espaciales no pudo restaurar el estado previo de las capas",
+ "Collapse Cockpit display options": "Contraer las opciones de visualización de la cabina",
+ "Collapse Cockpit Radio controls": "Contraer los controles de Radio de la cabina",
+ "SYNC": "SINCR.",
+ "{category} BAND": "BANDA {category}",
+ "NO STATIONS": "SIN EMISORAS",
+ "{name}, station {index} of {total}": "{name}, emisora {index} de {total}",
+ "No station available": "Sin emisoras disponibles",
+ "OFF AIR": "FUERA DEL AIRE",
+ "STATION UNAVAILABLE": "EMISORA NO DISPONIBLE",
+ "Pause": "Pausar",
+ "Resume": "Reanudar",
+ "selected": "seleccionada",
+ "nearest": "más cercana",
+ "{action} {target} radio station": "{action} la emisora de radio {target}",
+ "RADIO STATE UNCERTAIN": "ESTADO DE RADIO SIN CONFIRMAR",
+ "SYNCING DIRECTORY": "SINCRONIZANDO DIRECTORIO",
+ "SYNCING": "SINCRONIZANDO",
+ "station": "emisora",
+ "Ready": "Listo",
+ "VIEWSHED ON": "ÁREA VISIBLE ACTIVADA",
+ "FRAME · LOADING": "FOTOGRAMA · CARGANDO",
+ "FRAME · UNAVAILABLE": "FOTOGRAMA · NO DISPONIBLE",
+ "CAL · EDITED (UNSAVED)": "CAL · EDITADA (SIN GUARDAR)",
+ "CAL · {badge}": "CAL · {badge}",
+ "CALIBRATED": "CALIBRADA",
+ "CURATED": "CURADA",
+ "RAW PRIOR": "ESTIMACIÓN INICIAL",
+ "MONITOR": "MONITOR",
+ "{city} · HDG {heading} · FOV {fov} · RANGE {range}m · {projection}{calBadge} · {provider}{status}": "{city} · HDG {heading} · FOV {fov} · RANGE {range} m · {projection}{calBadge} · {provider}{status}",
+ "{count} cameras loaded · click a camera to activate": {
+ "one": "{count} cámara cargada · haz clic en una cámara para activarla",
+ "many": "{count} de cámaras cargadas · haz clic en una cámara para activarla",
+ "other": "{count} cámaras cargadas · haz clic en una cámara para activarla"
+ },
+ "{count} cameras loaded · enable CCTV to activate": {
+ "one": "{count} cámara cargada · activa CCTV para activarla",
+ "many": "{count} de cámaras cargadas · activa CCTV para activarlas",
+ "other": "{count} cámaras cargadas · activa CCTV para activarlas"
+ },
+ "No summary available.": "No hay resumen disponible.",
+ "Celestial ring — available in Normal style": "Anillo celestial — disponible en el estilo Normal",
+ "Detection overlay: {mode}": "Superposición de detección: {mode}",
+ "Detection overlay: off": "Superposición de detección: desactivada",
+ "SPARSE": "DISPERSA",
+ "BALANCED": "EQUILIBRADA",
+ "DENSE": "DENSO",
+ "Resetting to full globe view": "Restableciendo la vista de globo completo",
+ "Resetting cockpit to full globe view": "Restableciendo la cabina a la vista de globo completo",
+ "ORBIT": "ÓRBITA",
+ "SUMMARY": "RESUMEN",
+ "Awaiting telemetry...": "Esperando telemetría...",
+ "REC": "REC",
+ "Scope edge feather": "Difuminado del borde de la mirilla",
+ "Bloom intensity": "Intensidad del resplandor",
+ "Sharpen intensity": "Intensidad de la nitidez",
+ "Search location by name or coordinates": "Buscar ubicación por nombre o coordenadas",
+ "Expand LOCATION": "Expandir UBICACIÓN",
+ "UNAVAILABLE": "NO DISPONIBLE",
+ "Live Flights": "Vuelos en vivo",
+ "Earthquakes (24h)": "Terremotos (24 h)",
+ "No selected data layers": "No hay capas de datos seleccionadas",
+ "Cleared {count} data layers": {
+ "one": "Se limpió {count} capa de datos",
+ "many": "Se limpiaron {count} de capas de datos",
+ "other": "Se limpiaron {count} capas de datos"
+ },
+ "{count} data layers could not be cleared": {
+ "one": "No se pudo limpiar {count} capa de datos",
+ "many": "No se pudieron limpiar {count} de capas de datos",
+ "other": "No se pudieron limpiar {count} capas de datos"
+ },
+ "Visible map targets": "Objetivos visibles en el mapa",
+ "CCTV": "CCTV",
+ "SOURCE · UNKNOWN": "FUENTE · DESCONOCIDA",
+ "Enable CCTV to load camera intersections": "Activa CCTV para cargar intersecciones con cámaras",
+ "CCTV OFF": "CCTV DESACTIVADO",
+ "NEAREST": "MÁS CERCANA",
+ "CCTV camera": "Cámara CCTV",
+ "FOCUS": "ENFOCAR",
+ "COVERAGE OFF": "COBERTURA DESACTIVADA",
+ "AUTO HOP OFF": "SALTO AUTO: NO",
+ "PROJECTION ON": "PROYECCIÓN ACTIVADA",
+ "CALIBRATION": "CALIBRACIÓN",
+ "ADJUST": "AJUSTAR",
+ "Drag the camera in the world: rings rotate, arrows move, handles set range/FOV": "Arrastra la cámara en el mundo: los anillos la giran, las flechas la mueven, los tiradores ajustan alcance/FOV",
+ "Camera pose — click a value to type": "Pose de la cámara — clic en un valor para escribirlo",
+ "Heading (compass °) — click to type": "Rumbo (° brújula) — clic para escribir",
+ "Pitch (° up/down) — click to type": "Inclinación (° arriba/abajo) — clic para escribir",
+ "Horizontal FOV (°) — click to type": "FOV horizontal (°) — clic para escribir",
+ "Range / monitor-plane distance (m) — click to type": "Alcance / distancia al plano del monitor (m) — clic para escribir",
+ "Mount height above ground (m) — click to type": "Altura de montaje sobre el suelo (m) — clic para escribir",
+ "North offset from catalog position (m) — click to type": "Desplazamiento al norte desde la posición del catálogo (m) — clic para escribir",
+ "East offset from catalog position (m) — click to type": "Desplazamiento al este desde la posición del catálogo (m) — clic para escribir",
+ "SAVE CAL": "GUARDAR CAL",
+ "RESET CAL": "RESTABLECER CAL",
+ "SCENE SUMMARY": "RESUMEN DE ESCENA",
+ "Enable CCTV to start camera-linked intelligence summaries.": "Activa CCTV para iniciar resúmenes de inteligencia vinculados a cámaras.",
+ "Internet radio and local SDR": "Radio por Internet y SDR local",
+ "Expand Radio": "Expandir Radio",
+ "Expand Radio section": "Expandir la sección de Radio",
+ "STATION TAG": "ETIQUETA DE EMISORA",
+ "Filter stations by station tag": "Filtrar emisoras por etiqueta de emisora",
+ "NO STATION SELECTED": "NINGUNA EMISORA SELECCIONADA",
+ "Enable Radio, then choose a globe marker or use next.": "Activa Radio y elige un marcador del globo o pulsa SIG.",
+ "DIRECTORY BAND": "BANDA DEL DIRECTORIO",
+ "DRAG TO TUNE": "ARRASTRA PARA SINTONIZAR",
+ "ALL · DRAG THE NEEDLE": "TODAS · ARRASTRA LA AGUJA",
+ "SNAPS TO AVAILABLE STATIONS": "SE AJUSTA A EMISORAS DISPONIBLES",
+ "Radio playback": "Reproducción de Radio",
+ "Previous filtered station": "Emisora filtrada anterior",
+ "PLAY": "ESCUCHAR",
+ "Play selected station": "Reproducir la emisora seleccionada",
+ "Next filtered station": "Siguiente emisora filtrada",
+ "STOP": "DETENER",
+ "Stop radio playback": "Detener la reproducción de Radio",
+ "Radio volume": "Volumen de Radio",
+ "Radio off": "Radio desactivada",
+ "STATION SITE": "SITIO DE LA EMISORA",
+ "Audio connects directly to the broadcaster after you press play. Your IP is visible to that broadcaster.": "El audio se conecta directamente con la emisora después de pulsar ESCUCHAR. Tu IP es visible para esa emisora.",
+ "LOADING": "CARGANDO",
+ "DEGRADED": "DEGRADADO",
+ "STALE": "DESACTUALIZADO",
+ "FALLBACK": "RESPALDO",
+ "PARTIAL": "PARCIAL",
+ "UNCERTAIN": "INCIERTO",
+ "ENABLING": "ACTIVANDO",
+ "DISABLING": "APAGANDO",
+ "Military Flights": "Vuelos militares",
+ "Satellites": "Satélites",
+ "Space Missions (30d)": "Misiones espaciales (30 d)",
+ "Street Traffic": "Tráfico urbano",
+ "Radio": "Radio",
+ "Bikeshare": "Bicicletas compartidas",
+ "Live AIS Vessels": "Buques AIS en vivo",
+ "Mapped Installations": "Instalaciones mapeadas",
+ "Global Context": "Contexto global",
+ "Datacenters": "Centros de datos",
+ "Dams": "Presas",
+ "Submarine Cables": "Cables submarinos",
+ "FIRMS Active Fires": "Incendios activos FIRMS",
+ "just now": "hace un momento",
+ "{count}s ago": "hace {count} s",
+ "{count}m ago": "hace {count} min",
+ "{count}h ago": "hace {count} h",
+ "never": "sin actualizar",
+ "loading...": "cargando...",
+ "UNCERTAIN · {source} · lifecycle state requires reconciliation": "INCIERTO · {source} · el estado del ciclo de vida requiere reconciliación",
+ "{state} · {source}": "{state} · {source}",
+ "{state} · {source} · {detail} · retry {seconds}s": "{state} · {source} · {detail} · reintento en {seconds}s",
+ "{state} · {source} · {detail}": "{state} · {source} · {detail}",
+ "{state} · {source} · {ago}": "{state} · {source} · {ago}",
+ "{state} · {source} · {ago} · retrying in {seconds}s": "{state} · {source} · {ago} · reintentando en {seconds}s",
+ "{source} · {loadingLabel}": "{source} · {loadingLabel}",
+ "{source} · {ago}": "{source} · {ago}",
+ "{accepted} of {raw} records accepted": "{accepted} de {raw} registros aceptados",
+ "incomplete snapshot": "instantánea incompleta",
+ "{state} · {source} · {detail} · {ago}": "{state} · {source} · {detail} · {ago}",
+ "{name}: {state}": "{name}: {state}",
+ "Type unknown": "Tipo desconocido",
+ "Reg unknown": "Matrícula desconocida",
+ "Operator unknown": "Operador desconocido",
+ "Alt unknown": "Altitud desconocida",
+ "FISHING": "PESCA",
+ "TOWING": "REMOLQUE",
+ "DREDGER": "DRAGA",
+ "DIVE OPS": "BUCEO",
+ "SAILING": "VELERO",
+ "PLEASURE": "RECREO",
+ "PILOT": "PRÁCTICO",
+ "SAR": "SAR",
+ "TUG": "REMOLCADOR",
+ "PORT TENDER": "AUXILIAR DE PUERTO",
+ "ANTI-POLLUTION": "ANTICONTAMINACIÓN",
+ "LAW ENFORCE": "POLICÍA",
+ "MEDICAL": "MÉDICO",
+ "HIGH-SPEED": "ALTA VELOCIDAD",
+ "PASSENGER": "PASAJEROS",
+ "CARGO": "CARGA",
+ "TANKER": "PETROLERO",
+ "OTHER": "OTRO",
+ "VESSEL": "BUQUE",
+ "POS: LIVE": "POS: EN VIVO",
+ "POS: {time}Z": "POS: {time}Z",
+ "AIS: --": "AIS: --",
+ "AIS: {name}": "AIS: {name}",
+ "{type} SPD: {speed} HDG: {heading}": "{type} SPD: {speed} HDG: {heading}",
+ "awaiting first AIS position…": "esperando la primera posición AIS…",
+ "CCTV ON": "CCTV ACTIVADO",
+ "COVERAGE ON": "COBERTURA ACTIVADA",
+ "AUTO HOP ON": "SALTO AUTO: SÍ",
+ "PROJECTION OFF": "PROYECCIÓN DESACTIVADA",
+ "ADJUST ON": "AJUSTE ACTIVADO",
+ "{count} CAMERAS STANDING BY · NO CAMERA SELECTED · CLICK A CAMERA TO ACTIVATE": "{count} CÁMARAS EN ESPERA · NINGUNA CÁMARA SELECCIONADA · CLIC EN UNA CÁMARA PARA ACTIVARLA",
+ "No cameras available in catalog.": "No hay cámaras disponibles en el catálogo.",
+ "{city} CCTV": "CCTV de {city}",
+ "HDG {value}°": "HDG {value}°",
+ "HDG {value}° (ESTIMATED)": "HDG {value}° (ESTIMADO)",
+ "FOV {value}°": "FOV {value}°",
+ "COVERAGE {value}km²": "COBERTURA {value} KM²",
+ "OVERLAP {count} cams": "SOLAPE {count} cám.",
+ "ISOLATED VIEW": "VISTA AISLADA",
+ "PROJ MONITOR": "PROY MONITOR",
+ "PROJ OFF": "PROY DESACT",
+ "VIEWSHED": "ÁREA VISIBLE",
+ "CAL {value}": "CAL {value}",
+ "SRC {value}": "SRC {value}",
+ "{value} CONTEXT": "CONTEXTO {value}",
+ "News": "Noticias",
+ "Talk": "Radio hablada",
+ "Weather / Emergency": "Clima / Emergencias",
+ "Public Safety": "Seguridad pública",
+ "Aviation / Marine": "Aviación / Marina",
+ "Traffic / Transit": "Tráfico / Transporte",
+ "Music": "Música",
+ "Other": "Otros",
+ "NO STATION AVAILABLE": "NINGUNA EMISORA DISPONIBLE",
+ "DISABLE": "DESACTIVAR",
+ "RECONCILE": "RECONCILIAR",
+ "Enable Radio": "Activar Radio",
+ "Disable Radio": "Desactivar Radio",
+ "Reconcile Radio — lifecycle uncertain": "Reconciliar Radio — ciclo de vida incierto",
+ "Loading station directory…": "Cargando el directorio de emisoras…",
+ "Directory metadata only": "Solo metadatos del directorio",
+ "Choose a globe marker or use next.": "Elige un marcador del globo o pulsa SIG.",
+ "TAGS · {tags}": "ETIQUETAS · {tags}",
+ "Ready — playback starts only from your action": "Preparada: la reproducción empieza cuando pulses ESCUCHAR",
+ "Connecting directly to broadcaster…": "Conectando directamente con la emisora…",
+ "Buffering broadcaster stream…": "Almacenando en búfer el flujo de la emisora…",
+ "Playing {station}": "Reproduciendo {station}",
+ "Paused {station}": "{station} en pausa",
+ "Broadcaster stream unavailable": "Flujo de la emisora no disponible",
+ " · degraded directory": " · directorio degradado",
+ " · stale directory": " · directorio desactualizado",
+ " · stale/degraded directory": " · directorio desactualizado/degradado",
+ " · outside current filter": " · fuera del filtro actual",
+ " · muted during voice interaction": " · silenciado durante la interacción de voz",
+ " · restoring volume after voice": " · restaurando el volumen tras la voz",
+ " · static indicates no broadcaster audio": " · la estática indica que no hay audio de la emisora",
+ " · tuning static until broadcaster starts": " · estática de sintonía hasta que la emisora comience",
+ "Station unavailable after directory refresh — choose another channel": "Emisora no disponible tras actualizar el directorio — elige otro canal",
+ "Radio is enabling…": "Activando Radio…",
+ "Radio is disabling…": "Desactivando Radio…",
+ "Radio lifecycle is uncertain — use Enable or Disable to reconcile": "El ciclo de vida de Radio es incierto — usa Activar o Desactivar para reconciliar",
+ "LAUNCH SITE": "LUGAR DE LANZAMIENTO",
+ "LAUNCH SITE · {site}": "LUGAR DE LANZAMIENTO · {site}",
+ "SELECTED SPACE MISSION": "MISIÓN ESPACIAL SELECCIONADA",
+ "Show all missions": "Mostrar todas las misiones",
+ "Deselect mission": "Deseleccionar misión",
+ "MISSION": "MISIÓN",
+ "STATUS · ": "ESTADO · ",
+ "LAUNCH SITE · ": "LUGAR DE LANZAMIENTO · ",
+ "LAUNCH TIME · ": "HORA DE LANZAMIENTO · ",
+ "ORBIT · ": "ÓRBITA · ",
+ "ASCENT PATH · ": "TRAYECTORIA DE ASCENSO · ",
+ "CURRENT DISTANCE FROM EARTH · ": "DISTANCIA ACTUAL A LA TIERRA · ",
+ "SATELLITE SPEED · ": "VELOCIDAD DEL SATÉLITE · ",
+ "PAYLOAD": "CARGA ÚTIL",
+ "NAME": "NOMBRE",
+ "TYPE": "TIPO",
+ "DESTINATION": "DESTINO",
+ "STAGE / RE-ENTRY / RECOVERY": "ETAPA / REENTRADA / RECUPERACIÓN",
+ "STAGE": "ETAPA",
+ "STATUS": "ESTADO",
+ "FINAL POSITION": "POSICIÓN FINAL",
+ "Previous mission": "Misión anterior",
+ "Next mission": "Misión siguiente",
+ "SHOW ALL / DESELECT": "MOSTRAR TODAS / DESELECCIONAR",
+ "NO MISSIONS AVAILABLE IN THE CURRENT 30-DAY WINDOW": "SIN MISIONES DISPONIBLES EN LA VENTANA ACTUAL DE 30 DÍAS",
+ "{count} / 30D": "{count} / 30 D",
+ "DATE UNAVAILABLE": "FECHA NO DISPONIBLE",
+ "UNSPECIFIED OPERATOR": "OPERADOR NO ESPECIFICADO",
+ "Select {mission}": "Seleccionar {mission}",
+ "+{count} additional payload records": "+{count} registros de carga útil adicionales",
+ "PAYLOAD DATA UNAVAILABLE": "DATOS DE CARGA ÚTIL NO DISPONIBLES",
+ "NO STAGE RE-ENTRY / RECOVERY DATA": "SIN DATOS DE REENTRADA / RECUPERACIÓN DE ETAPA",
+ "UNSPECIFIED": "NO ESPECIFICADO",
+ "FLIGHT {count}": "VUELO {count}",
+ "REUSED": "REUTILIZADO",
+ "{value} KM DOWNRANGE": "{value} KM DE TRAYECTORIA",
+ "PLANNED · ": "PLANIFICADA · ",
+ "SUPPLIED TRAJECTORY POINTS": "PUNTOS DE TRAYECTORIA SUMINISTRADOS",
+ "RECONSTRUCTED ESTIMATE": "ESTIMACIÓN RECONSTRUIDA",
+ "{value} KM": "{value} KM",
+ "{value} KM/S": "{value} KM/S",
+ "REPLAY ASCENT": "REPETIR ASCENSO",
+ "Replay the estimated ascent with a following camera": "Reproduce el ascenso estimado con una cámara de seguimiento",
+ "Pause replay": "Pausar repetición",
+ "Resume replay": "Reanudar repetición",
+ "Cancel replay": "Cancelar repetición",
+ "REPLAY SPEED": "VELOCIDAD DE REPETICIÓN",
+ "Replay speed multiplier": "Multiplicador de velocidad de repetición",
+ "T−{time} · {mission}": "T−{time} · {mission}",
+ "LAUNCH STANDBY": "EN ESPERA DE LANZAMIENTO",
+ "LIFTOFF · {mission}": "DESPEGUE · {mission}",
+ "ASCENT REPLAY · {mission}": "REPETICIÓN DEL ASCENSO · {mission}",
+ "ASCENT ESTIMATE · {mission}": "ESTIMACIÓN DEL ASCENSO · {mission}",
+ "STAGE RE-ENTRY / RECOVERY · {mission}": "REENTRADA / RECUPERACIÓN DE ETAPA · {mission}",
+ "ORBIT REPLAY · {mission}": "REPETICIÓN EN ÓRBITA · {mission}",
+ "PAUSED · {title}": "EN PAUSA · {title}",
+ "T minus {seconds}": "T menos {seconds}",
+ "Preparing launch site": "Preparando el lugar de lanzamiento",
+ "Liftoff": "Despegue",
+ "Ascent replay": "Repetición del ascenso",
+ "Orbit replay": "Repetición en órbita",
+ ", paused": ", en pausa",
+ "DENSE ···": "DENSO ···",
+ "DENSE ✕": "DENSO ✕",
+ "Add the full Starlink broadband shell (thousands of extra points)": "Añade la capa completa de banda ancha de Starlink (miles de puntos extra)",
+ "Loading the Starlink shell…": "Cargando la capa de Starlink…",
+ "Starlink {detail} — click to retry": "Starlink {detail} — clic para reintentar",
+ "load failed": "carga fallida",
+ "Showing the full Starlink shell — click for the core catalog only": "Mostrando la capa completa de Starlink — clic para ver solo el catálogo principal",
+ "STATION": "ESTACIÓN",
+ "Crewed stations and their visiting vehicles": "Estaciones tripuladas y sus vehículos de visita",
+ "NAV": "NAV",
+ "GNSS navigation — GPS, GLONASS, Galileo": "Navegación GNSS — GPS, GLONASS, Galileo",
+ "GEO": "GEO",
+ "Geostationary belt — comms and weather, fixed over the equator": "Cinturón geoestacionario — comunicaciones y meteorología, fijos sobre el ecuador",
+ "VISUAL": "VISUAL",
+ "Brightest naked-eye objects — CelesTrak visual group": "Objetos más brillantes a simple vista — grupo visual de CelesTrak",
+ "COMMS": "TELECOM",
+ "Broadband constellation shell — shown only in DENSE mode": "Capa de constelación de banda ancha — visible solo en modo DENSO",
+ "refreshing...": "actualizando...",
+ "KEY REQUIRED": "CLAVE REQUERIDA",
+ "STALE · cached {age}": "DESACTUALIZADO · en caché hace {age}",
+ "LIVE · updated {age}": "EN VIVO · actualizado {age}",
+ "<1m ago": "hace <1 min",
+ "FIRE · {frp} MW": "INCENDIO · {frp} MW",
+ "▲ {frp} MW": "▲ {frp} MW",
+ "FIRE": "INCENDIO",
+ "FIRES": "INCENDIOS",
+ "{value} conf": "confianza {value}",
+ "{value} ago": "hace {value}",
+ "max {value} MW": "máx {value} MW",
+ "new {value}": "nueva hace {value}",
+ "NIGHT": "NOCHE",
+ "sensor n/a": "sensor n/d",
+ "Focus fire detection {title}, {details}": "Enfocar la detección de incendio {title}, {details}",
+ "SIMULATED — traffic service unreachable": "SIMULADO — servicio de tráfico inaccesible",
+ "SIMULATED — add TomTom key for live": "SIMULADO — añade una clave de TomTom para datos en vivo",
+ "syncing {count} city feeds...": "sincronizando {count} fuentes de ciudades...",
+ "scanning nearby systems...": "escaneando sistemas cercanos...",
+ "🚲 {bikes} avail · {docks} docks · {capacity} cap": "🚲 {bikes} disp · {docks} anclajes · {capacity} cap",
+ "⚠️ Not installed": "⚠️ No instalada",
+ "⚠️ Not renting": "⚠️ No alquila",
+ "⚠️ Not returning": "⚠️ No admite devoluciones",
+ "Station": "Estación",
+ "Station {id}": "Estación {id}",
+ "MAPPED INSTALLATION": "INSTALACIÓN MAPEADA",
+ "loading mapped installation context": "cargando contexto de instalaciones mapeadas",
+ "Overpass rate-limited": "Overpass con límite de peticiones",
+ "Overpass timed out": "Overpass agotó el tiempo de espera",
+ "Overpass could not complete the query": "Overpass no pudo completar la consulta",
+ "Overpass temporarily unavailable": "Overpass temporalmente no disponible",
+ "Retrying mapped sites…": "Reintentando sitios mapeados…",
+ "Fetching mapped sites…": "Obteniendo sitios mapeados…",
+ "{reason} — retrying in {seconds}s": "{reason} — reintentando en {seconds}s",
+ "{reason} — retry pending": "{reason} — reintento pendiente",
+ "Showing cached mapped sites": "Mostrando sitios mapeados en caché",
+ "Mapped sites not loaded": "Sitios mapeados sin cargar",
+ "Mapped sites loaded": "Sitios mapeados cargados",
+ "CONTEXT READY": "CONTEXTO LISTO",
+ "GLOBAL CONTEXT OFF": "CONTEXTO GLOBAL DESACTIVADO",
+ "SELECT A FLIGHT, VESSEL, OR MAPPED INSTALLATION": "SELECCIONA UN VUELO, BUQUE U INSTALACIÓN MAPEADA",
+ "ENABLE TO LOAD OBSERVED / MAPPED PROXIMITY": "ACTIVA PARA CARGAR PROXIMIDAD OBSERVADA / MAPEADA",
+ "Global Context navigation": "Navegación del Contexto global",
+ "PREVIOUS": "ANT.",
+ "Open-source mapped/observed context. Missing broadcasts, unloaded map areas, or unmapped sites are not evidence of absence.": "Contexto mapeado/observado de fuentes abiertas. Las transmisiones ausentes, las zonas del mapa sin cargar o los sitios sin mapear no son evidencia de ausencia.",
+ "Unavailable": "No disponible",
+ "Focus {label}": "Enfocar {label}",
+ "Flights": "Vuelos",
+ "Military flights": "Vuelos militares",
+ "AIS vessels": "Buques AIS",
+ "Mapped installations": "Instalaciones mapeadas",
+ "CURRENT VIEWPORT ONLY": "SOLO LA VISTA ACTUAL",
+ "BRG {value}°": "BRG {value}°",
+ "CRS {value}°": "CRS {value}°",
+ "feed unavailable": "fuente no disponible",
+ "feed stale": "fuente desactualizada",
+ "observed or mapped nearby context": "contexto cercano observado o mapeado",
+ "no observed or mapped objects in current feeds": "sin objetos observados o mapeados en las fuentes actuales",
+ "CONDITIONS UNKNOWN": "CONDICIONES DESCONOCIDAS",
+ "CLEAR": "DESPEJADO",
+ "PARTLY CLOUDY": "PARCIALMENTE NUBLADO",
+ "OVERCAST": "CUBIERTO",
+ "FOG": "NIEBLA",
+ "DRIZZLE": "LLOVIZNA",
+ "RAIN": "LLUVIA",
+ "SNOW": "NIEVE",
+ "RAIN SHOWERS": "CHUBASCOS",
+ "SNOW SHOWERS": "CHUBASCOS DE NIEVE",
+ "THUNDERSTORM": "TORMENTA",
+ "MIXED CONDITIONS": "CONDICIONES MIXTAS",
+ "TAB PREVIEWS · ENTER / SPACE SELECTS": "TAB VISTA PREVIA · ENTER / SPACE SELECCIONA",
+ "awaiting usable AIS positions…": "esperando posiciones AIS utilizables…",
+ "awaiting first AIS message…": "esperando el primer mensaje AIS…",
+ "EST. DOWNRANGE": "DIST. ESTIMADA",
+ "MISSION CONTROL · FIRST LAUNCH": "CENTRO DE MANDO · PRIMER INICIO",
+ "Choose your first view": "Elige tu primera vista",
+ "LIVE CONTACTS": "CONTACTOS EN VIVO",
+ "Don't show this again": "No volver a mostrar",
+ "POWER UP": "ENCENDER",
+ "GROUND STATION · PROVIDER SETTINGS": "ESTACIÓN TERRENA · AJUSTES DE PROVEEDORES",
+ "Power up the globe": "Enciende el globo",
+ "SAVE KEYS": "GUARDAR CLAVES",
+ "Saving…": "Guardando…",
+ "It feels like a forbidden cockpit—then you realize the sources are public and the data is real.": "Parece una cabina prohibida—hasta que descubres que las fuentes son públicas y los datos son reales.",
+ "Aircraft, vessels and nearby intelligence": "Aeronaves, buques e inteligencia cercana",
+ "Launches, spacecraft and orbital context": "Lanzamientos, naves y contexto orbital",
+ "EXPLORE MANUALLY": "EXPLORAR MANUALMENTE",
+ "Begin with a clean globe": "Empieza con un globo limpio",
+ "ESC to dismiss": "ESC para cerrar",
+ "Tip: the GEV MIC button in the dock lets you talk to the map.": "Consejo: el botón GEV MIC del dock te permite hablar con el mapa.",
+ "Close key setup": "Cerrar la configuración de claves",
+ "The globe already flies keyless. Every key below switches on another real feed — paste one and it's saved into this app's local configuration, then the server restarts itself. Server-side keys stay on this machine; Google Maps and Cesium ion run in the browser and must be provider-restricted. Keys you configured elsewhere are shown but never touched.": "El globo ya funciona sin claves. Cada clave de abajo activa otra fuente real — pega una y queda guardada en la configuración local de esta app, y luego el servidor se reinicia solo. Las claves del servidor se quedan en esta máquina; Google Maps y Cesium ion funcionan en el navegador y sus claves deben restringirse en la consola del proveedor. Las claves que configuraste en otro lugar se muestran, pero nunca se modifican.",
+ "ESC to close": "ESC para cerrar",
+ "The Google Maps key buys the photorealistic planet — everything else stacks on top.": "La clave de Google Maps activa el planeta fotorrealista; todo lo demás se superpone.",
+ "SCENES": "ESCENAS",
+ "Scene recipe": "Receta de escena",
+ "NEW": "NUEVA",
+ "DEL": "BORRAR",
+ "CAPTURE SHOT": "CAPTURAR PLANO",
+ "UPDATE SHOT": "ACTUALIZAR PLANO",
+ "START": "INICIAR",
+ "EXPORT PRESETS": "EXPORTAR PREAJUSTES",
+ "IMPORT": "IMPORTAR",
+ "RUN LOG": "REGISTRO DE EJECUCIÓN",
+ "Starting live contacts…": "Iniciando contactos en vivo…",
+ "Opening space missions…": "Abriendo misiones espaciales…",
+ "Scanning active events…": "Escaneando eventos activos…",
+ "Working…": "Trabajando…",
+ "Could not open that mission{detail}. Retry or explore manually.": "No se pudo abrir esa misión{detail}. Reintenta o explora manualmente.",
+ "This browser is blocking storage, so that could not be saved.": "Este navegador bloquea el almacenamiento, así que no se pudo guardar.",
+ "Live earthquakes and active fires, from USGS and NASA": "Terremotos en vivo e incendios activos, de USGS y NASA",
+ "ENVIRONMENTAL": "MEDIO AMBIENTE",
+ "EARTH WATCH": "VIGILANCIA TERRESTRE",
+ "ACTIVE EVENTS": "EVENTOS ACTIVOS",
+ "POWER UP · {count} KEYS WAITING": {
+ "one": "ENCENDER · {count} CLAVE EN ESPERA",
+ "many": "ENCENDER · {count} DE CLAVES EN ESPERA",
+ "other": "ENCENDER · {count} CLAVES EN ESPERA"
+ },
+ "POWERED UP": "ENCENDIDO",
+ "Save failed ({status}).": "Error al guardar ({status}).",
+ "Save failed: {detail}": "Error al guardar: {detail}",
+ "Paste at least one key first.": "Pega al menos una clave primero.",
+ "Saved to {store}. Restarting — this page reloads itself.": "Guardado en {store}. Reiniciando — esta página se recarga sola.",
+ "Removed from {store}. Restarting — this page reloads itself.": "Eliminado de {store}. Reiniciando — esta página se recarga sola.",
+ "your app configuration": "tu configuración de la app",
+ "your local .env": "tu .env local",
+ "Remove this key from your saved configuration?": "¿Eliminar esta clave de tu configuración guardada?",
+ "This map stack": "Este conjunto de mapas",
+ "{label} is unavailable": "{label} no está disponible",
+ "{label} unavailable: {hint}": "{label} no disponible: {hint}",
+ "Global Flights Radar": "Radar global de vuelos",
+ "Orbital Watch": "Vigilancia orbital",
+ "Thermal Threat Board": "Panel de amenazas térmicas",
+ "City Overload": "Sobrecarga urbana",
+ "Omniscience Pullback": "Alejamiento omnisciente",
+ "CONNECTING": "CONECTANDO",
+ "ERROR": "ERROR",
+ "Session ended — cost cap {cost}": "Sesión finalizada — límite de costo {cost}",
+ "VOICE STANDBY": "VOZ EN ESPERA",
+ "VOICE ACTIVE": "VOZ ACTIVA",
+ "VOICE UNAVAILABLE": "VOZ NO DISPONIBLE",
+ "WebRTC microphone support unavailable": "Este navegador no admite micrófono WebRTC",
+ "Requesting microphone": "Solicitando micrófono",
+ "Hold Space to talk": "Mantén Space y habla",
+ "Release Space to send": "Suelta Space para enviar",
+ "Ask or command": "Pregunta o ordena",
+ "Voice off": "Voz desactivada",
+ "Running command": "Ejecutando comando",
+ "Radio did not start": "La radio no se inició",
+ "Hold Space to speak · tap Space to activate focused controls": "Mantén pulsado Space para hablar · pulsa Space brevemente para activar el control enfocado",
+ "Voice session could not be started.": "No se pudo iniciar la sesión de voz.",
+ "VOICE SYSTEM ERROR": "ERROR DEL SISTEMA DE VOZ",
+ "DISMISS": "CERRAR",
+ "Check microphone permission and network access, then try again.": "Revisa el permiso del micrófono y el acceso a la red, y vuelve a intentarlo.",
+ "AI AGENT": "AGENTE DE IA",
+ "VOICE CONTROL": "CONTROL DE VOZ",
+ "{tier} applies next session": "{tier} desde la próxima sesión",
+ "Voice model tier — applies next session": "Nivel del modelo de voz — se aplica en la próxima sesión",
+ "Estimated session cost": "Costo estimado de la sesión",
+ "Voice control — activate to toggle voice; hold Space to speak": "Control de voz — púlsalo para activar o desactivar la voz; mantén pulsado Space para hablar",
+ "Cannot capture shot: camera not ready": "No se puede capturar el plano: la cámara no está lista",
+ "Shot {n}": "Plano {n}",
+ "Captured: {scene} / {shot}": "Capturado: {scene} / {shot}",
+ "Select a shot first": "Selecciona primero un plano",
+ "Updated: {scene} / {shot}": "Actualizado: {scene} / {shot}",
+ "Delete shot \"{shot}\"?": "¿Eliminar el plano \"{shot}\"?",
+ "Loaded: {scene} / {shot}": "Cargado: {scene} / {shot}",
+ "Camera unavailable — exit cockpit first": "Cámara no disponible — sal primero de la cabina",
+ "No shots to run": "No hay planos para ejecutar",
+ "Running {index}/{total}: {scene} / {shot}": "Ejecutando {index}/{total}: {scene} / {shot}",
+ "Scene run complete": "Ejecución de escenas completada",
+ "Error: {message}": "Error: {message}",
+ "Could not exit {mode} — scene layers may be refused": "No se pudo salir de {mode} — las capas de la escena pueden rechazarse",
+ "REMOVE": "ELIMINAR",
+ "Remove {title} from this app's saved keys": "Elimina {title} de las claves guardadas de esta app",
+ "Needs {envVars} — add it in Provider Settings": "Necesita {envVars} — se añade en Ajustes de proveedores",
+ "Places context + Street View fallback; optional separate key": "Contexto de Places + respaldo de Street View; clave separada opcional",
+ "Live ships, worldwide": "Buques en vivo, en todo el mundo",
+ "Live active-fire detections": "Detecciones de incendios activos en vivo",
+ "Real live traffic (keyless runs a simulation)": "Tráfico real en vivo (sin clave se usa una simulación)",
+ "Bing imagery map stacks + world terrain": "Imágenes de Bing + terreno mundial",
+ "More flight-polling credits (anonymous works without)": "Más créditos de consulta de vuelos (sin clave funciona el modo anónimo)",
+ "Higher space-missions request allowance": "Mayor límite de peticiones para misiones espaciales",
+ "Scene action failed": "La acción de escena falló",
+ "Project exported": "Proyecto exportado",
+ "Next session: {pendingId} — this session stays on {modelId}": "Sesión siguiente: {pendingId} — esta sesión sigue en {modelId}",
+ "Voice model: {pendingId} — click to switch to {target}; applies next session": "Modelo de voz: {pendingId} — haz clic para cambiar a {target}; se aplica en la próxima sesión",
+ "Estimated session cost on {modelId} — {responses} response(s). Warns at {warn}, ends the session at {cap}.": "Costo de sesión estimado en {modelId} — {responses} respuesta(s). Avisa a {warn} y cierra la sesión a {cap}.",
+ "Street-level imagery and coverage in the Street Level layer. Free: register an app in the Mapillary developer dashboard and paste its Client Token": "Imágenes y cobertura a nivel de calle en la capa \"A pie de calle\". Gratis: registra una app en el panel de desarrolladores de Mapillary y pega su token de cliente (Client Token)",
+ "Voice control — API key or ChatGPT OAuth": "Control de voz — clave de API u OAuth de ChatGPT",
+ "WITHIN {km} KM": "A MENOS DE {km} KM",
+ "Syncing flow · Roads: {source}": "Sincronizando flujo · Vías: {source}",
+ "LIVE · Roads: {source} · Roads without flow hidden": "EN VIVO · Vías: {source} · Vías sin flujo ocultas",
+ "LIVE · Roads: {source} · No flow roads in view": "EN VIVO · Vías: {source} · Sin vías con flujo a la vista",
+ "LIVE · Roads: {source} · Flow {percent}%": "EN VIVO · Vías: {source} · Flujo {percent}%",
+ "SIMULATED · Roads: {source} · Flow {percent}%": "SIMULADO · Vías: {source} · Flujo {percent}%",
+ "Syncing flow · Roads: OpenStreetMap · Flow: TomTom · Unmatched: simulated": "Sincronizando flujo · Vías: OpenStreetMap · Flujo: TomTom · Sin coincidencia: simulado",
+ "LIVE · Roads: OpenStreetMap · Flow: TomTom · {percent}% cov · Unmatched: simulated": "EN VIVO · Vías: OpenStreetMap · Flujo: TomTom · {percent}% cob. · Sin coincidencia: simulado",
+ "LIVE · Roads: OpenStreetMap · Flow: TomTom · {percent}% cov": "EN VIVO · Vías: OpenStreetMap · Flujo: TomTom · {percent}% cob.",
+ "SIMULATED · Roads: OpenStreetMap · Flow: TomTom (no matches)": "SIMULADO · Vías: OpenStreetMap · Flujo: TomTom (sin coincidencias)",
+ "Data source unavailable": "Fuente de datos no disponible",
+ "Saturation": "Saturación",
+ "Edge Thickness": "Grosor de bordes",
+ "Contrast": "Contraste",
+ "Grain": "Grano",
+ "Vignette": "Viñeta",
+ "Pixelation": "Pixelado",
+ "Distortion": "Distorsión",
+ "Instability": "Inestabilidad",
+ "Wind": "Viento",
+ "Gain": "Ganancia",
+ "Scanlines": "Líneas de barrido",
+ "Sensitivity": "Sensibilidad",
+ "WHOT/BHOT": "WHOT/BHOT",
+ "Ironbow": "Ironbow",
+ "Pick a shape, then click the map.": "Elige una forma y haz clic en el mapa.",
+ "Enter to place the pin, Esc to cancel.": "Enter para colocar el marcador, Esc para cancelar.",
+ "Click where the pin goes.": "Haz clic donde quieras colocar el marcador.",
+ "Click {count} more points.": {
+ "one": "Haz clic en {count} punto más.",
+ "many": "Haz clic en {count} de puntos más.",
+ "other": "Haz clic en {count} puntos más."
+ },
+ "Those points are in a line — move one off it to enclose an area.": "Esos puntos están en línea: mueve uno fuera de ella para cerrar un área.",
+ "That line has no length — click somewhere further away.": "Esa línea no tiene longitud: haz clic más lejos.",
+ " · {max}-point limit reached": " · límite de {max} puntos alcanzado",
+ "{measure} · double-click or Enter to finish, Backspace undoes, Esc cancels.{full}": "{measure} · doble clic o Enter para terminar, Backspace deshace, Esc cancela.{full}",
+ "That point is off the globe — click on the world.": "Ese punto está fuera del globo: haz clic sobre el mundo.",
+ "That shape could not be placed.": "No se pudo colocar esa forma.",
+ "Board cleared.": "Tablero borrado.",
+ "Draw on the world — click vertices, double-click or Enter to finish, Esc to cancel": "Dibuja sobre el mundo: haz clic en los vértices, doble clic o Enter para terminar, Esc para cancelar",
+ "Draw": "Dibujo",
+ "Shape": "Forma",
+ "Shape to draw": "Forma a dibujar",
+ "Area": "Área",
+ "Line": "Línea",
+ "Pin": "Marcador",
+ "Label (optional)": "Etiqueta (opcional)",
+ "Label for the drawn shape": "Etiqueta de la forma dibujada",
+ "Colour of the drawn shape": "Color de la forma dibujada",
+ "Primary": "Principal",
+ "Amber": "Ámbar",
+ "Cyan": "Cian",
+ "Green": "Verde",
+ "Red": "Rojo",
+ "Clear": "Borrar",
+ "Remove every mark from the board": "Quitar todas las marcas del tablero",
- "Point the camera at the globe for street-level coverage": "Apunta la cámara al globo para ver la cobertura a pie de calle",
+ "No street-level imagery providers configured": "No hay proveedores de imágenes a pie de calle configurados",
- "Selected": "Seleccionada",
+ "Live Vessels": "Buques en vivo",
+ "Bike Share": "Bicis compartidas",
+ "Cameras": "Cámaras",
+ "Street Level": "A pie de calle",
+ "Mapped ALPR Cameras": "Cámaras ALPR mapeadas",
+ "Data Centers": "Centros de datos",
+ "Active Fires": "Incendios activos",
+ "Street Level could not start": "No se pudo iniciar A pie de calle",
+ "Street Level toggle failed": "No se pudo activar o desactivar la capa A pie de calle",
- "Street-level image": "Imagen a pie de calle",
+ "SHRINK": "REDUCIR",
+ "EXPAND": "AMPLIAR",
+ "Shrink": "Reducir",
+ "Expand": "Ampliar",
+ "ANY DATE": "CUALQUIER FECHA",
+ "LAST 10 YEARS": "ÚLTIMOS 10 AÑOS",
+ "LAST 5 YEARS": "ÚLTIMOS 5 AÑOS",
+ "LAST 3 YEARS": "ÚLTIMOS 3 AÑOS",
+ "LAST 2 YEARS": "ÚLTIMOS 2 AÑOS",
+ "LAST YEAR": "ÚLTIMO AÑO",
+ "LAST 6 MONTHS": "ÚLTIMOS 6 MESES",
+ "LAST 3 MONTHS": "ÚLTIMOS 3 MESES",
+ "LAST MONTH": "ÚLTIMO MES",
+ "LAST {count} DAYS": {
+ "one": "ÚLTIMO {count} DÍA",
+ "many": "ÚLTIMOS {count} DE DÍAS",
+ "other": "ÚLTIMOS {count} DÍAS"
+ },
+ "{window} · SINCE {date}": "{window} · DESDE {date}",
+ "Turn Street Level off": "Desactivar A pie de calle",
+ "Turn Street Level on": "Activar A pie de calle",
+ "KEY REJECTED": "CLAVE RECHAZADA",
+ "{name} imagery on": "Imágenes de {name} activadas",
+ "{name} imagery off": "Imágenes de {name} desactivadas",
+ "Image by {creator}": "Imagen de {creator}",
+ "zoom in to see KartaView coverage": "acércate para ver la cobertura de KartaView",
+ "no KartaView photos in view": "no hay fotos de KartaView a la vista",
+ "{names}: by upload date": "{names}: por fecha de subida",
+ "{n} streets in view · click a line for its nearest photo": {
+ "one": "{n} calle a la vista · haz clic en una línea para su foto más cercana",
+ "many": "{n} calles a la vista · haz clic en una línea para su foto más cercana",
+ "other": "{n} calles a la vista · haz clic en una línea para su foto más cercana"
+ },
- "Camera follows view: move the globe camera wherever the street-level view looks": "La cámara sigue la vista: mueve la cámara del globo hacia donde mira la vista a pie de calle",
- "Camera follow needs the Google 3D map: choose Google 3D under MAP SOURCE": "Seguir con la cámara requiere el mapa Google 3D: elige Google 3D en FUENTE DEL MAPA",
- "Switch a provider on to draw its coverage.": "Activa un proveedor para dibujar su cobertura.",
+ "Loading this sequence…": "Cargando esta secuencia…",
+ "{n} images in this sequence · Esc clears": {
+ "one": "{n} imagen en esta secuencia · Esc quita la selección",
+ "many": "{n} de imágenes en esta secuencia · Esc quita la selección",
+ "other": "{n} imágenes en esta secuencia · Esc quita la selección"
+ },
+ "{n} sequences in view · click a line for its photos": {
+ "one": "{n} secuencia a la vista · haz clic en una línea para ver sus fotos",
+ "many": "{n} de secuencias a la vista · haz clic en una línea para ver sus fotos",
+ "other": "{n} secuencias a la vista · haz clic en una línea para ver sus fotos"
+ },
+ "STREET LEVEL": "A PIE DE CALLE",
- "Expand the street-level view (Esc shrinks it)": "Ampliar la vista a pie de calle (Esc la reduce)",
+ "Image fit": "Ajuste de la imagen",
+ "FIT": "AJUSTAR",
+ "Fit: show the whole photo, with dark bars where its shape differs from the frame": "Ajustar: muestra la foto entera, con barras oscuras donde su forma no coincide con el marco",
+ "FILL": "RELLENAR",
+ "Fill: fill the frame edge to edge, cropping the photo": "Rellenar: llena el marco de borde a borde, recortando la foto",
- "Camera follows view": "La cámara sigue la vista",
- "FOLLOW": "SEGUIR",
+ "Close the image and deselect it on the map": "Cerrar la imagen y quitar la selección en el mapa",
+ "Close the street-level image": "Cerrar la imagen a pie de calle",
+ "Street-level viewer": "Visor a pie de calle",
+ "Open this image on the provider's site": "Abrir esta imagen en el sitio del proveedor",
+ "Imagery providers": "Proveedores de imágenes",
+ "PROVIDERS": "PROVEEDORES",
+ "Imagery filters": "Filtros de imágenes",
+ "IMAGERY": "IMÁGENES",
+ "Panorama filter": "Filtro de panoramas",
+ "ALL": "TODAS",
+ "FLAT": "PLANAS",
+ "SINCE": "DESDE",
- "Coverage colours": "Colores de cobertura",
+ "That shape already has {count} points — finish it or press Backspace.": "Esa forma ya tiene {count} puntos — termínala o pulsa Backspace.",
+ "Could not place the shape: {error}": "No se pudo colocar la forma: {error}",
+ "{owner} is using the pointer — close it first.": "Puntero en uso: {owner}. Ciérralo primero.",
+ "{label} · Detailed outline unavailable": "{label} · Contorno detallado no disponible",
+ "Witness source": "Fuente de testigo",
+ "{provider} · EMBEDDED SOURCE": "{provider} · FUENTE INSERTADA",
+ "OPEN ORIGINAL ↗": "ABRIR ORIGINAL ↗",
+ "{provider} media: {source}": "Contenido de {provider}: {source}",
+ "{provider} · PROVIDER CONTROLS": "{provider} · CONTROLES DEL PROVEEDOR",
+ "YOUTUBE {state} · OPEN ORIGINAL": "YOUTUBE {state} · ABRIR ORIGINAL",
+ "Facebook player API did not initialize.": "La API del reproductor de Facebook no se inicializó.",
+ "Facebook player API could not load.": "No se pudo cargar la API del reproductor de Facebook.",
+ "Facebook player API timed out.": "La API del reproductor de Facebook agotó el tiempo de espera.",
+ "X embed API did not initialize.": "La API de inserción de X no se inicializó.",
+ "X embed could not load.": "No se pudo cargar la inserción de X.",
+ "X embed timed out.": "La inserción de X agotó el tiempo de espera.",
+ "TIMEOUT": "TIEMPO AGOTADO",
+ "BLOCKED": "BLOQUEADO",
+ "Facebook embed unavailable. The post may be private, removed, region-restricted, or blocked.": "Inserción de Facebook no disponible. La publicación puede ser privada, haber sido eliminada, estar restringida por región o estar bloqueada.",
+ "Preloading {provider} media": "Precargando contenido de {provider}",
+ "LOADING X POST…": "CARGANDO PUBLICACIÓN DE X…",
+ "The X post is unavailable or cannot be embedded.": "La publicación de X no está disponible o no se puede insertar.",
+ "X POST · PROVIDER CONTROLS": "PUBLICACIÓN DE X · CONTROLES DEL PROVEEDOR",
+ "{reason} OPEN ORIGINAL.": "{reason} ABRE EL ORIGINAL.",
+ "X embed unavailable": "Inserción de X no disponible",
+ "FACEBOOK · PROVIDER CONTROLS": "FACEBOOK · CONTROLES DEL PROVEEDOR",
+ "Facebook embed unavailable": "Inserción de Facebook no disponible",
+ "AUTOPLAY BLOCKED · USE PROVIDER CONTROLS": "REPRODUCCIÓN AUTOMÁTICA BLOQUEADA · USA LOS CONTROLES DEL PROVEEDOR",
+ "Embedded {provider} media for {source}": "Contenido de {provider} insertado para {source}",
+ "witness source": "fuente de testigo",
+ "Rasuwagadhi witness": "Testigo de Rasuwagadhi",
+ "Open original source for {source}; capture time unverified": "Abrir la fuente original de {source}; hora de captura sin verificar",
+ "Historical reference and post-event image divider": "Divisor entre la imagen de referencia histórica y la posterior al evento",
+ "A historical reference {before} percent, B post-event {after} percent": "A, referencia histórica, {before} por ciento; B, posterior al evento, {after} por ciento",
+ "■ RELEASE CAMERA": "■ LIBERAR CÁMARA",
+ "Seek Nepal scene clock": "Desplazarse por el reloj de la escena de Nepal",
+ "NEPAL SCENE CLOCK": "RELOJ DE LA ESCENA DE NEPAL",
+ "… PLAYING SHOT": "… REPRODUCIENDO PLANO",
+ "▶ PLAY SHOT": "▶ REPRODUCIR PLANO",
+ "Ⅱ PAUSE": "Ⅱ PAUSA",
+ "↺ REPLAY CINEMATIC": "↺ REPETIR CINEMÁTICA",
+ "↺ REPLAY": "↺ REPETIR",
+ "… PLAYING SCENE": "… REPRODUCIENDO ESCENA",
+ "Continue {scene} from next shot": "Continuar {scene} desde el siguiente plano",
+ "current scene": "la escena actual",
+ "Replay the full reconstruction": "Repetir la reconstrucción completa",
+ "SCENE SHOT": "PLANO DE ESCENA",
+ "TIME UNVERIFIED": "HORA SIN VERIFICAR",
+ "{count} SOURCES": {
+ "one": "{count} FUENTE",
+ "many": "{count} DE FUENTES",
+ "other": "{count} FUENTES"
+ },
+ "OUTSIDE IMAGERY SWIPE": "FUERA DE LA COMPARACIÓN DE IMÁGENES",
+ "{scene} / AUTHORED SHOT": "{scene} / PLANO DISEÑADO",
+ "NEPAL FLOOD INCIDENT": "INCIDENTE DE INUNDACIÓN EN NEPAL",
+ "Play {shot}": "Reproducir {shot}",
+ "current scene shot": "el plano actual de la escena",
+ "Play reconstruction": "Reproducir la reconstrucción",
+ "Load previous scene shot": "Cargar el plano anterior de la escena",
+ "Load next scene shot": "Cargar el siguiente plano de la escena",
+ "SCHEMATIC CORRIDOR, NOT MODELED ARRIVAL TIME.": "CORREDOR ESQUEMÁTICO; NO ES UN TIEMPO DE LLEGADA MODELADO.",
+ "Rasuwa · 26 Aug 2026": "Rasuwa · 26 ago 2026",
+ "Event reconstruction": "Reconstrucción del evento",
+ "INITIATION": "INICIO",
+ "DAMMING": "REPRESAMIENTO",
+ "SECONDARY FAILURE": "ROTURA SECUNDARIA",
+ "BORDER ARRIVAL": "LLEGADA A LA FRONTERA",
+ "PROPAGATION": "PROPAGACIÓN",
+ "DOWNSTREAM PASSAGE": "PASO AGUAS ABAJO",
+ "CONSEQUENCE": "SECUELAS",
+ "DOWNSTREAM CONSEQUENCE": "SECUELAS AGUAS ABAJO",
+ "EVIDENCE": "EVIDENCIA",
+ "{count} GEOLOCATED SOURCE-MAP PLACEMENTS": {
+ "one": "{count} UBICACIÓN GEOLOCALIZADA EN EL MAPA DE FUENTES",
+ "many": "{count} DE UBICACIONES GEOLOCALIZADAS EN EL MAPA DE FUENTES",
+ "other": "{count} UBICACIONES GEOLOCALIZADAS EN EL MAPA DE FUENTES"
+ },
+ "NO PREVIEW": "SIN VISTA PREVIA",
+ "SOURCE LINK": "ENLACE DE LA FUENTE",
+ "{publisher} / OPEN": "{publisher} / ABRIR",
+ "Bhote Koshi flood reconstruction controls": "Controles de la reconstrucción de la inundación del Bhote Koshi",
+ "EVENT RECONSTRUCTION · 26 AUG 2026": "RECONSTRUCCIÓN DEL EVENTO · 26 AGO 2026",
+ "BHOTE KOSHI OUTBURST FLOOD": "INUNDACIÓN POR DESBORDE DEL BHOTE KOSHI",
+ "Close event layer": "Cerrar la capa del evento",
+ "OBSERVED IMAGERY": "IMÁGENES OBSERVADAS",
+ "SCHEMATIC CORRIDOR": "CORREDOR ESQUEMÁTICO",
+ "2021 HISTORICAL REFERENCE / 2026 POST-EVENT": "REF. HISTÓRICA 2021 / POSTERIOR AL EVENTO 2026",
+ "Historical reference and post-event image split": "División entre la imagen de referencia histórica y la posterior al evento",
+ "RECONSTRUCTION CLOCK": "RELOJ DE LA RECONSTRUCCIÓN",
+ "Schematic downstream progression": "Avance esquemático aguas abajo",
+ "Story beat navigation": "Navegación por momentos del relato",
+ "Previous story beat": "Momento anterior del relato",
+ "CAUSE": "CAUSA",
+ "CAPTURE TIME UNVERIFIED": "HORA DE CAPTURA SIN VERIFICAR",
+ "Next story beat": "Siguiente momento del relato",
+ "▶ PLAY": "▶ REPRODUCIR",
+ "Play the next shot and continue through this scene": "Reproducir el siguiente plano y continuar con esta escena",
+ "▶ PLAY SCENE": "▶ REPRODUCIR ESCENA",
+ "◉ CINEMATIC": "◉ CINEMÁTICA",
+ "↺ FULL STORY": "↺ HISTORIA COMPLETA",
+ "↗ OPEN ORIGINAL": "↗ ABRIR ORIGINAL",
+ "⌖ LOWER GORGE": "⌖ GARGANTA INFERIOR",
+ "FIELD REPORTS · {count}": "INFORMES DE CAMPO · {count}",
+ "GEOLOCATIONS · {credit}": "GEOLOCALIZACIONES · {credit}",
+ "↗ OPEN PUBLIC MAP": "↗ ABRIR MAPA PÚBLICO",
+ "Clouds are preserved from the source imagery.": "Las nubes provienen de las imágenes de origen.",
+ "Show the Nepal context callout without a border or country fill": "Muestra la etiqueta de contexto de Nepal sin frontera ni relleno del país",
+ "Introduce Nepal, draw its border, then reveal the Bhote Koshi incident": "Presenta Nepal, dibuja su frontera y luego revela el incidente del Bhote Koshi",
+ "CITIES": "CIUDADES",
+ "Keep the regional incident context and introduce nearby city labels": "Mantiene el contexto regional del incidente y presenta las etiquetas de las ciudades cercanas",
+ "PLACES": "LUGARES",
+ "Introduce the reconstruction scene key places from trigger to downstream": "Presenta los lugares clave de la escena de reconstrucción, desde el desencadenante hasta aguas abajo",
+ "PATH": "RECORRIDO",
+ "Animate the sourced cyan river-centerline route to Trishuli Bazaar": "Anima la ruta cian documentada por el eje del río hasta Trishuli Bazaar",
+ "OVERVIEW": "VISTA GENERAL",
+ "Keep the completed flood path and location labels visible": "Mantiene visibles el recorrido completo de la inundación y las etiquetas de lugares",
+ "RECORD": "REGISTRO",
+ "Reveal the trigger record while making a slow camera approach": "Revela el registro del desencadenante con una aproximación lenta de la cámara",
+ "BHOTE KOSHI FLOOD INCIDENT": "INCIDENTE DE INUNDACIÓN DEL BHOTE KOSHI",
+ "NEPAL · 26 AUG 2026": "NEPAL · 26 AGO 2026",
+ "USGS INITIAL REPORT": "INFORME INICIAL DEL USGS",
+ "26 AUG 2026 · 08:37 NPT": "26 AGO 2026 · 08:37 NPT",
+ "28.2710° N · 85.5150° E": "28,2710° N · 85,5150° E",
+ "INITIAL M4.4 · RECLASSIFIED M5.2 LANDSLIDE": "INICIAL M4,4 · RECLASIFICADO COMO DESLIZAMIENTO M5,2",
+ "USGS EVENT us7000tbwb · OPEN SOURCE": "EVENTO USGS us7000tbwb · ABRIR FUENTE",
+ "flight": "vuelo",
+ "military flight": "vuelo militar",
+ "satellite": "satélite",
+ "VOICE AUTH · CHATGPT OAUTH": "AUTENTICACIÓN DE VOZ · OAUTH DE CHATGPT",
+ "VOICE AUTH · API KEY": "AUTENTICACIÓN DE VOZ · CLAVE DE API",
+ "USE API KEY": "USAR CLAVE DE API",
+ "USE CHATGPT OAUTH": "USAR OAUTH DE CHATGPT",
+ "Use OPENAI_API_KEY for the next cloud voice session": "Usar OPENAI_API_KEY en la próxima sesión de voz en la nube",
+ "Use the signed-in local ChatGPT/Codex OAuth session for the next cloud voice session": "Usar la sesión OAuth local de ChatGPT/Codex ya iniciada en la próxima sesión de voz en la nube",
+ "Metered — a billing-enabled account": "De pago por uso — una cuenta con facturación activada",
+ "Free key — register, paste, done": "Clave gratuita — regístrate, pégala y listo",
+ "browser-side": "en el navegador",
+ "This key runs in the browser by design — restrict it at the provider (see SECURITY.md)": "Esta clave funciona en el navegador por diseño — restríngela en el proveedor (consulta SECURITY.md)",
+ "configured externally": "configurada externamente",
+ "Supplied by your environment, Keychain, or launcher — change it where it was set": "Proporcionada por tu entorno, Keychain o el lanzador — cámbiala donde se definió",
+ "MANAGE ↗": "GESTIONAR ↗",
+ "GET KEY ↗": "OBTENER CLAVE ↗",
+ "{envVar} saved — paste to replace": "{envVar} guardada — pega otra para reemplazarla",
+ "paste {envVar}": "pega {envVar}",
+ "Project keys: {status}": "Claves del proyecto: {status}",
+ "Mapped camera locations": "Ubicaciones de cámaras mapeadas",
+ "SHOW NEAREST": "MOSTRAR LA MÁS CERCANA",
+ "Stop following the current object before navigating to a camera": "Deja de seguir el objeto actual antes de ir a una cámara",
+ "Move to the nearest loaded camera and show its details": "Ir a la cámara cargada más cercana y mostrar sus detalles",
+ "Camera badges": "Iconos de cámaras",
+ "Cyan cameras turn coral when selected. Wedges illustrate mapped direction, not measured coverage. Nearby cameras may be outside the screen.": "Las cámaras cian se vuelven coral al seleccionarlas. Las cuñas ilustran la dirección mapeada, no la cobertura medida. Las cámaras cercanas pueden estar fuera de la pantalla.",
+ "{count} nearby · {onScreen} on screen": {
+ "one": "{count} cercana · {onScreen} en pantalla",
+ "many": "{count} de cámaras cercanas · {onScreen} en pantalla",
+ "other": "{count} cercanas · {onScreen} en pantalla"
+ },
+ "{count} nearby": {
+ "one": "{count} cercana",
+ "many": "{count} de cámaras cercanas",
+ "other": "{count} cercanas"
+ },
+ "retrying mapped ALPR cameras": "reintentando cámaras ALPR mapeadas",
+ "loading mapped ALPR cameras": "cargando cámaras ALPR mapeadas",
+ "No ALPR data for this area — US and Canada only": "Sin datos ALPR para esta zona — solo EE. UU. y Canadá",
+ "Zoom in to load mapped cameras": "Acércate para cargar las cámaras mapeadas",
+ "Showing cached locations": "Mostrando ubicaciones en caché",
+ "Coverage limited — zoom in": "Cobertura limitada: acércate",
+ "No ALPR data for this area": "Sin datos ALPR para esta zona",
+ "None on screen — nearby cameras are outside the view": "Ninguna en pantalla — las cámaras cercanas están fuera de la vista",
+ "ALPR camera": "Cámara ALPR",
+ "OpenStreetMap · community mapped": "OpenStreetMap · mapeado por la comunidad",
+ "Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Atlántico y Pacífico Norte oriental/central; no es una cobertura mundial de ciclones.",
+ "Potential tropical cyclone": "Posible ciclón tropical",
+ "Hurricane": "Huracán",
+ "Tropical storm": "Tormenta tropical",
+ "Tropical depression": "Depresión tropical",
+ "Subtropical storm": "Tormenta subtropical",
+ "Subtropical depression": "Depresión subtropical",
+ "Track and cone match this advisory": "La trayectoria y el cono coinciden con este aviso",
+ "Track/cone awaiting advisory {number}": "Trayectoria/cono a la espera del aviso {number}",
+ "Track/cone unavailable": "Trayectoria/cono no disponible",
+ "Cached advisory · stale source": "Aviso en caché · fuente desactualizada",
+ "Loading advisories…": "Cargando avisos…",
+ "{count} active storms": {
+ "one": "{count} ciclón activo",
+ "many": "{count} de ciclones activos",
+ "other": "{count} ciclones activos"
+ },
+ "Position as of {time}": "Posición a las {time}",
+ "Maximum sustained wind: {wind} · Pressure: {pressure}": "Viento máximo sostenido: {wind} · Presión: {pressure}",
+ "{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Aviso {number} · emitido {time}",
+ "No active NHC/CPHC systems": "Sin sistemas activos del NHC/CPHC",
+ "Advisories unavailable": "Avisos no disponibles",
+ "Cyclones · NHC / CPHC": "Ciclones · NHC / CPHC",
+ "Atlantic · E/C Pacific": "Atlántico · Pacífico E/C",
+ "{storms} · {name} selected": "{storms} · {name} seleccionado",
+ "Official advisory ↗": "Aviso oficial ↗",
+ "Active NHC and CPHC cyclone advisories": "Avisos de ciclones activos del NHC y el CPHC",
+ "Wind unavailable": "Viento no disponible",
+ "Advisory center / forecast track": "Centro del ciclón según el aviso / trayectoria pronosticada",
+ "Center-track uncertainty cone": "Cono de incertidumbre de la trayectoria del centro",
+ "Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Selecciona un ciclón en el mapa, o elige uno en la lista para seleccionarlo y mover la cámara. Haz clic en un espacio vacío del mapa para borrar la selección. Contexto de avisos NOAA NHC/CPHC. El cono describe la incertidumbre de la trayectoria pronosticada del centro, no el tamaño del ciclón ni toda el área de peligro. Las etiquetas de los puntos de pronóstico son horas de anticipación de la fuente, no horas calculadas a partir de la emisión del aviso. La geometría sigue la superficie; la altura no es altitud meteorológica. Consulta el aviso oficial.",
+ "Directions": "Indicaciones",
+ "{mode} — reroute for {modeLower}": "{mode} — recalcular la ruta {modeLower}",
+ "CLICK MAP": "CLIC EN EL MAPA",
+ "SET A": "FIJAR A",
+ "Click a spot on the globe to place A (click again to cancel)": "Haz clic en un punto del globo para colocar A (vuelve a hacer clic para cancelar)",
+ "Then click the globe to place the start": "Luego haz clic en el globo para colocar el inicio",
+ "SET B": "FIJAR B",
+ "Click a spot on the globe to place B (click again to cancel)": "Haz clic en un punto del globo para colocar B (vuelve a hacer clic para cancelar)",
+ "Then click the globe to place the destination": "Luego haz clic en el globo para colocar el destino",
+ "Swap A and B": "Intercambiar A y B",
+ "FLY ···": "VOLAR ···",
+ "FLYING": "VOLANDO",
+ "FLY": "VOLAR",
+ "Fly the camera along the route": "Volar con la cámara a lo largo de la ruta",
+ "Place A and B first": "Coloca primero A y B",
+ "Remove the route and both markers": "Eliminar la ruta y ambos marcadores",
+ "press Escape twice to leave Draw": "pulsa Esc dos veces para salir de Dibujo",
+ "{name} is active — turn {name} off, then set {endpoint}": "{name} está activo — desactiva {name} y luego fija {endpoint}",
+ "{name} is active — {leave}, then set {endpoint}": "{name} está activo — {leave} y luego fija {endpoint}",
+ "Only the first {count} turns of this route are shown": "Solo se muestran los primeros {count} giros de esta ruta",
+ "Turn-by-turn directions": "Indicaciones paso a paso",
+ "OSM routing": "Rutas de OSM",
+ "DRIVE": "COCHE",
+ "Drive": "En coche",
+ "Another map tool is using clicks — close it, then SET A again": "Otra herramienta del mapa está usando los clics — ciérrala y vuelve a pulsar FIJAR A",
+ "WALK": "A PIE",
+ "Walk": "A pie",
+ "Routing…": "Calculando ruta…",
+ "BIKE": "BICI",
+ "Bike": "En bici",
+ "No route found": "No se encontró ninguna ruta",
+ "{distance} · {duration} · {mode} · first {count} turns": "{distance} · {duration} · {mode} · primeros {count} giros",
+ "{distance} · {duration} · {mode}": "{distance} · {duration} · {mode}",
+ "Click the globe to place {endpoint}": "Haz clic en el globo para colocar {endpoint}",
+ "SET B, then click the globe": "Pulsa FIJAR B y luego haz clic en el globo",
+ "SET A, then click the globe": "Pulsa FIJAR A y luego haz clic en el globo",
+ "Step {step} of {total} · then {leg}": "Paso {step} de {total} · luego {leg}",
+ "Step {step} of {total}": "Paso {step} de {total}",
+ "Then: {instruction}": "Luego: {instruction}",
+ "No route found between A and B": "No se encontró ninguna ruta entre A y B",
+ "Routing failed: {error}": "Falló el cálculo de la ruta: {error}",
+ "Routing timed out": "El cálculo de la ruta agotó el tiempo de espera",
+ "Routing unavailable — no response from the routing service": "Rutas no disponibles — sin respuesta del servicio de rutas",
+ "Routing unavailable": "Rutas no disponibles",
+ "Fire · FRP {frp} MW": "Incendio · FRP {frp} MW",
+ "Not contained or unknown": "Sin contener o desconocido",
+ "Under 50% contained": "Contenido por debajo del 50%",
+ "50–99% contained": "Contenido al 50–99%",
+ "Fully contained": "Totalmente contenido",
+ "Colour shows reported containment. Perimeters are simplified to about 100 m.": "El color indica la contención notificada. Los perímetros se simplifican a unos 100 m.",
+ "MORE DETAIL · 30 m": "MÁS DETALLE · 30 m",
+ "Sentinel-2 and Landsat via HLS, 30 m, every 2–6 days": "Sentinel‑2 y Landsat vía HLS, 30 m, cada 2–6 días",
+ "DAILY OVERVIEW · 250 m": "VISTA GENERAL DIARIA · 250 m",
+ "VIIRS daily mosaic, 250 m, follows broad changes; little detail under 25 km": "Mosaico diario de VIIRS, 250 m, sigue los cambios amplios; poco detalle por debajo de 25 km",
+ "Catalog truncated · a newer clear day may exist": "Catálogo truncado · puede existir un día despejado más reciente",
+ "{label} catalog unavailable · {detail}": "Catálogo de {label} no disponible · {detail}",
+ "Daily overview for today may still be empty until the pass": "La vista general diaria de hoy puede seguir vacía hasta el paso del satélite",
+ "Sentinel-2": "Sentinel‑2",
+ "Landsat 8/9": "Landsat 8/9",
+ "Daily overview": "Vista general diaria",
+ "No frame within {gap} min of {time}": "Sin fotograma a ±{gap} min de {time}",
+ "No frame within {gap} h of {time}": "Sin fotograma a ±{gap} h de {time}",
+ "{hours}h {minutes}m ago": "hace {hours} h {minutes} min",
+ "{minutes}m ago": "hace {minutes} min",
+ "{state} · {time} · {lag}": "{state} · {time} · {lag}",
+ "Observed": "Observado",
+ "History": "Historial",
+ "Observation unavailable": "Observación no disponible",
+ "Waiting for observation": "Esperando observación",
+ "{detail} · synced": "{detail} · sincr.",
+ "{detail} · nearest": "{detail} · más cercano",
+ "RADAR REFLECTIVITY · dBZ": "REFLECTIVIDAD DE RADAR · dBZ",
+ "LIGHTNING DENSITY · 15 min accumulation": "DENSIDAD DE RAYOS · acumulación de 15 min",
+ "GLOBAL INFRARED · hourly": "INFRARROJO GLOBAL · cada hora",
+ "GOES INFRARED · ~5 min": "INFRARROJO GOES · ~5 min",
+ "{state}: {time}": "{state}: {time}",
+ "Latest observation": "Última observación",
+ "frame {index}/{total}": "fotograma {index}/{total}",
+ "loading": "cargando",
+ "Observation: unavailable": "Observación: no disponible",
+ "Contiguous US · gaps ≠ no rain": "EE. UU. contiguos · huecos ≠ sin lluvia",
+ "Americas + Pacific · not individual strikes": "América + Pacífico · no son rayos individuales",
+ "Color: strikes/km²/min ×10³": "Color: rayos/km²/min ×10³",
+ "60°S–60°N · typically 2–3 h delayed": "60°S–60°N · normalmente con 2–3 h de retraso",
+ "North America · infrared imagery": "Norteamérica · imágenes infrarrojas",
+ "Reduced motion · history playback unavailable": "Movimiento reducido · reproducción del historial no disponible",
+ "Reduced motion · manual history available": "Movimiento reducido · puedes recorrer el historial a mano",
+ "Rain radar · US": "Radar de lluvia · EE. UU.",
+ "Lightning density · 15 min": "Densidad de rayos · 15 min",
+ "Satellite clouds": "Nubes por satélite",
+ "Americas + Pacific": "América + Pacífico",
+ "Global · 60°S–60°N": "Global · 60°S–60°N",
+ "North America": "Norteamérica",
+ "Source observations delayed": "Observaciones de la fuente con retraso",
+ "Stale source": "Fuente desactualizada",
+ "Loading next frame…": "Cargando el siguiente fotograma…",
+ "Map center outside coverage": "Centro del mapa fuera de cobertura",
+ "strikes/km²/min ×10³": "rayos/km²/min ×10³",
+ "N. America": "Norteamérica",
+ "Global": "Global",
+ "Hourly global mosaic; usually 2–3 hours delayed": "Mosaico global horario; normalmente con 2–3 horas de retraso",
+ "GOES regional clouds; approximately 5-minute updates": "Nubes regionales de GOES; actualizaciones cada 5 minutos aproximadamente",
+ "Clouds only": "Solo nubes",
+ "Full": "Completa",
+ "Soft": "Suave",
+ "Vivid": "Intensa",
+ "Image opacity; does not alter the observed values": "Opacidad de la imagen; no altera los valores observados",
+ "View US radar": "Ver radar de EE. UU.",
+ "View Americas & Pacific": "Ver América y Pacífico",
+ "View coverage": "Ver cobertura",
+ "{value} strikes/km²/min ×10³ (15-minute density)": "{value} rayos/km²/min ×10³ (densidad de 15 minutos)",
+ "{value} dBZ radar reflectivity": "{value} dBZ de reflectividad de radar",
+ "STALE · cached source metadata": "DESACTUALIZADO · metadatos de la fuente en caché",
+ "Map center is outside source coverage": "El centro del mapa está fuera de la cobertura de la fuente",
+ "NOAA/NWS 15-minute lightning density derived from Vaisala NLDN/GLD360. Coverage 110°E across the Pacific/Americas to 0°, 25°S–80°N. Not a live strike count, global coverage or a safety warning.": "Densidad de rayos de 15 minutos de NOAA/NWS derivada de Vaisala NLDN/GLD360. Cobertura desde 110°E, a través del Pacífico/América, hasta 0°, 25°S–80°N. No es un recuento de rayos en vivo, ni una cobertura global, ni un aviso de seguridad.",
+ "NOAA MRMS radar echoes indicate precipitation patterns, not rain rate, a storm warning or a future forecast. Native source approximately 1 km; display is limited to level 6. Frames use exact advertised observation times.": "Los ecos de radar NOAA MRMS indican patrones de precipitación, no la intensidad de lluvia, ni un aviso de tormenta, ni un pronóstico futuro. Fuente nativa de aproximadamente 1 km; la visualización se limita al nivel 6. Los fotogramas usan las horas de observación exactas anunciadas.",
+ "GOES-19/18 longwave infrared Band 14 regional; NESDIS global longwave mosaic. Clouds only dims everything but bright, cold cloud tops; a brightness filter, not a cloud mask. Coverage and freshness differ by region.": "Infrarrojo de onda larga GOES-19/18, banda 14, regional; mosaico global de onda larga de NESDIS. Solo nubes atenúa todo excepto las cimas de nubes brillantes y frías; un filtro de brillo, no una máscara de nubes. La cobertura y la actualidad varían según la región.",
+ "REGION": "REGIÓN",
+ "IMAGE": "IMAGEN",
+ "OPACITY": "OPACIDAD",
+ "Forecast · does not follow history": "Pronóstico · no sigue el historial",
+ "Wind motion": "Movimiento del viento",
+ "Wind speed": "Velocidad del viento",
+ "Sea-level pressure": "Presión a nivel del mar",
+ "Air temperature · 2 m": "Temperatura del aire · 2 m",
+ "Global · 1° grid": "Global · cuadrícula de 1°",
+ "{model} forecast · {time}": "Pronóstico {model} · {time}",
+ "Loading forecast": "Cargando pronóstico",
+ "Preparing flow": "Preparando flujo",
+ "Selected field unavailable": "Campo seleccionado no disponible",
+ "Cached forecast · stale": "Pronóstico en caché · desactualizado",
+ "ECMWF IFS surface forecast": "Pronóstico de superficie ECMWF IFS",
+ "NOAA GFS surface forecast": "Pronóstico de superficie NOAA GFS",
+ "Reduced motion": "Movimiento reducido",
+ "Pause visual flow; forecast time does not advance with animation": "Pausa el flujo visual; la hora del pronóstico no avanza con la animación",
+ "None": "Ninguno",
+ "Speed": "Velocidad",
+ "Pressure": "Presión",
+ "Temperature": "Temperatura",
+ "Wind trails with no field shading": "Trazas de viento sin sombreado del campo",
+ "How hard the surface wind is blowing": "Con qué fuerza sopla el viento en superficie",
+ "Sea-level air pressure: broad highs and lows": "Presión del aire a nivel del mar: altas y bajas amplias",
+ "Air temperature two meters above the surface": "Temperatura del aire a dos metros sobre la superficie",
+ "Wind speed units": "Unidades de velocidad del viento",
+ "Read wind at map center": "Leer el viento en el centro del mapa",
+ "Read the forecast at the center of the map without changing selection": "Leer el pronóstico en el centro del mapa sin cambiar la selección",
+ "{model} forecast · {field} ({unit})": "Pronóstico {model} · {field} ({unit})",
+ "Valid: {time}": "Válido: {time}",
+ "preparing": "preparando",
+ "Issued: {time}": "Emitido: {time}",
+ "Selected field unavailable · wind remains visible": "Campo seleccionado no disponible · el viento sigue visible",
+ "{error} · wind remains visible": "{error} · el viento sigue visible",
+ "Surface wind at 10 m. Approximately 1° global grid. Curves follow the 10 m wind field, lifted 12 km for visibility; display height is not weather altitude. View lighting is for readability. Animation shows flow through one fixed forecast; it does not advance time. Color fields drape the globe basemap or the active photorealistic 3D Tiles.": "Viento en superficie a 10 m. Cuadrícula global de aproximadamente 1°. Las curvas siguen el campo de viento a 10 m, elevadas 12 km para que sean visibles; la altura mostrada no es altitud meteorológica. La iluminación de la vista es para facilitar la lectura. La animación muestra el flujo de un único pronóstico fijo; no avanza el tiempo. Los campos de color cubren el mapa base del globo o las 3D Tiles fotorrealistas activas.",
+ "MODEL": "MODELO",
+ "FIELD": "CAMPO",
+ "UNITS": "UNIDADES",
+ "MOTION": "MOVIMIENTO",
+ "Forecast": "Pronóstico",
+ "Interpolated model forecast on an approximately 1° grid. Broad weather patterns, not a street-level measurement.": "Pronóstico de modelo interpolado en una cuadrícula de aproximadamente 1°. Patrones meteorológicos generales, no una medición a pie de calle.",
+ "No surface reading": "Sin lectura en superficie",
+ "Aim the map center at Earth": "Apunta el centro del mapa a la Tierra",
+ " · calm": " · calma",
+ " from {direction}": " del {direction}",
+ "WIND AT {coordinates}": "VIENTO EN {coordinates}",
+ "{model} · valid {time}": "{model} · válido {time}",
+ "Focusing {label}": "Enfocando {label}",
+ "Source": "Fuente",
+ "Could not leave scene: {scene}": "No se pudo salir de la escena: {scene}",
+ "Seeked: {scene} / {shot}": "Saltado a: {scene} / {shot}",
+ "Scene transition limit reached — load a shot to reset": "Límite de transiciones de escena alcanzado — carga un plano para restablecer",
+ "Export failed: {error}": "La exportación falló: {error}",
+ "Imported {file}": "Importado: {file}",
+ "Import failed: {error}": "La importación falló: {error}",
+ "Import failed (could not read JSON file)": "La importación falló (no se pudo leer el archivo JSON)",
+ "Layers refused: {layers}": "Capas rechazadas: {layers}",
+ "Scene {n}": "Escena {n}",
+ "Cannot update {scene}: shot inventory changed": "No se puede actualizar {scene}: el inventario de planos cambió",
+ "Cannot update {scene}: evidence beats changed": "No se puede actualizar {scene}: los momentos de evidencia cambiaron",
+ "Cannot update {scene}: shot bindings are incomplete": "No se puede actualizar {scene}: los vínculos de los planos están incompletos",
+ "Updated {count} shots: {scene}": {
+ "one": "{count} plano actualizado: {scene}",
+ "many": "{count} de planos actualizados: {scene}",
+ "other": "{count} planos actualizados: {scene}"
+ },
+ "Appended {count} shots: {scene}": {
+ "one": "{count} plano añadido: {scene}",
+ "many": "{count} de planos añadidos: {scene}",
+ "other": "{count} planos añadidos: {scene}"
+ },
+ "Select a feature or use Tab and Enter to choose an action.": "Selecciona un elemento o usa Tab y Enter para elegir una acción.",
+ "Selected feature: {feature}. Choose an action.": "Elemento seleccionado: {feature}. Elige una acción.",
+ "Action complete": "Acción completada",
+ "Action unavailable or cancelled": "Acción no disponible o cancelada",
+ "Scene actions": "Acciones de escena",
+ "Bhote Koshi Evidence Sequence": "Secuencia de evidencia del Bhote Koshi",
+ "Nepal Flood Incident": "Incidente de inundación en Nepal",
+ "{count} scenes": {
+ "one": "{count} escena",
+ "many": "{count} de escenas",
+ "other": "{count} escenas"
+ },
+ "{count} shots": {
+ "one": "{count} plano",
+ "many": "{count} de planos",
+ "other": "{count} planos"
+ },
+ "{count} data packs": {
+ "one": "{count} paquete de datos",
+ "many": "{count} de paquetes de datos",
+ "other": "{count} paquetes de datos"
+ },
+ "{scene} / {pack}: {status}. File: {path}. {attribution} · {license}": "{scene} / {pack}: {status}. Archivo: {path}. {attribution} · {license}",
+ "Unavailable layers: {layers}": "Capas no disponibles: {layers}",
+ "{bytes} bundled bytes verified. Files stay in memory for this session. Reimport the bundle after reloading the app.": "{bytes} bytes empaquetados verificados. Los archivos permanecen en memoria durante esta sesión. Vuelve a importar el paquete después de recargar la app.",
+ "Review scene import": "Revisar la importación de escena",
+ "Nothing is loaded or changed until you apply this file.": "No se carga ni se cambia nada hasta que apliques este archivo.",
+ "Ready to import": "Listo para importar",
+ "Apply replaces the current project. Export your current project first if you want to keep both.": "Aplicar reemplaza el proyecto actual. Exporta primero tu proyecto actual si quieres conservar ambos.",
+ "Apply import": "Aplicar importación",
+ "Import was not applied. The current project may have changed.": "La importación no se aplicó. Es posible que el proyecto actual haya cambiado.",
+ "Select a scene and shot first": "Selecciona primero una escena y un plano",
+ "Edit scene details": "Editar los detalles de la escena",
+ "Camera positions use degrees and meters above the ellipsoid. Drafts are validated before they replace your saved scene.": "Las posiciones de cámara usan grados y metros sobre el elipsoide. Los borradores se validan antes de reemplazar tu escena guardada.",
+ "Anchors and data packs": "Anclas y paquetes de datos",
+ "Shot camera, timing, packs and actions": "Cámara, tiempos, paquetes y acciones del plano",
+ "New anchor ID": "ID del ancla nueva",
+ "Capture camera as anchor": "Capturar la cámara como ancla",
+ "Anchor added to draft": "Ancla añadida al borrador",
+ "Set move start to current camera": "Fijar el inicio del movimiento en la cámara actual",
+ "Move added to draft; destination remains the shot camera": "Movimiento añadido al borrador; el destino sigue siendo la cámara del plano",
+ "Use ordinary flight": "Usar vuelo normal",
+ "Invalid shot JSON": "JSON de plano no válido",
+ "Apply details": "Aplicar detalles",
+ "Select a scene first": "Selecciona primero una escena",
+ "Share selected scene": "Compartir la escena seleccionada",
+ "Scene JSON preserves authored settings and attribution. It does not include asset files. Bundles include only pack files you choose here or previously imported bundle files.": "El JSON de escena conserva los ajustes definidos por el autor y la atribución. No incluye archivos de recursos. Los paquetes de escena solo incluyen los archivos de paquetes de datos que elijas aquí o los que se importaron antes.",
+ "Download scene JSON": "Descargar JSON de escena",
+ "Choose data-pack files": "Elegir archivos de paquete de datos",
+ "Or choose a data-pack folder": "O elige una carpeta de paquete de datos",
+ "Download asset bundle": "Descargar paquete de recursos",
+ "Asset bundle downloaded": "Paquete de recursos descargado",
+ "Could not complete this action. Check the file, references and selected assets.": "No se pudo completar esta acción. Revisa el archivo, las referencias y los recursos seleccionados.",
+ "RTL-SDR sample stream stopped": "Flujo de muestras RTL-SDR detenido",
+ "Switching to {mode}…": "Cambiando a {mode}…",
+ "Browser audio is suspended; select FM again to resume it": "El audio del navegador está suspendido; selecciona FM de nuevo para reanudarlo",
+ "RTL-SDR gain change failed": "No se pudo cambiar la ganancia del RTL-SDR",
+ "Tuned to {mhz} MHz FM": "Sintonizado en {mhz} MHz FM",
+ "FM signal found at {mhz} MHz": "Señal FM encontrada en {mhz} MHz",
+ "No FM signal found": "No se encontró ninguna señal FM",
+ "Seek stopped": "Búsqueda detenida",
+ "Browser location is unavailable": "La ubicación del navegador no está disponible",
+ "Receiver location was not granted": "No se concedió permiso para la ubicación del receptor",
+ "RTL-SDR disconnected": "RTL-SDR desconectado",
+ "No RTL-SDR device selected": "No hay ningún dispositivo RTL-SDR seleccionado",
+ "WebUSB requires desktop Chrome or Edge on localhost/HTTPS": "WebUSB requiere Chrome o Edge de escritorio en localhost/HTTPS",
+ "RTL-SDR access failed; close other SDR apps and check USB permissions": "No se pudo acceder al RTL-SDR; cierra otras apps de SDR y revisa los permisos USB",
+ "RTL-SDR connection failed": "La conexión con el RTL-SDR falló",
+ "Receiving 1090 MHz ADS-B": "Recibiendo ADS-B en 1090 MHz",
+ "Receiving broadcast FM": "Recibiendo FM de radiodifusión",
+ "Connect an RTL-SDR to begin.": "Conecta un RTL-SDR para empezar.",
+ "WebUSB is unavailable in this browser": "WebUSB no está disponible en este navegador",
+ "SDR decoder worker failed": "Falló el proceso del decodificador SDR",
+ "WebUSB requires desktop Chrome or Edge": "WebUSB requiere Chrome o Edge de escritorio",
+ "Waiting for an RTL-SDR device…": "Esperando un dispositivo RTL-SDR…",
+ "Browser audio is suspended; press Connect again to resume it": "El audio del navegador está suspendido; pulsa Conectar de nuevo para reanudarlo",
+ "Return map to straight-down view": "Volver el mapa a la vista cenital",
+ "Tilt map to oblique view": "Inclinar el mapa a una vista oblicua",
+ "Reset map to north up. Current heading {heading} degrees": "Orientar el mapa al norte. Rumbo actual: {heading} grados",
+ "HDG": "HDG",
+ "PITCH": "INCL.",
+ "FOV": "FOV",
+ "RANGE": "RANGE",
+ "HGT": "ALT.",
+ "{value} KM/H": "{value} KM/H",
+ "NORMAL": "NORMAL",
+ "ANIME": "ANIME",
+ "NOIR": "NOIR",
+ "Rendered globe frames per second · toggle with `": "Fotogramas por segundo renderizados del globo · alterna con `",
+ "Utilities": "Utilidades",
+ "Other layers": "Otras capas",
+ "Movement": "Movimiento",
+ "Infrastructure": "Infraestructura",
+ "Events": "Eventos",
+ "Weather": "Clima",
+ "LOCATED": "UBICADO",
+ "LOCATE": "UBICAR",
+ "IDLE": "EN ESPERA",
+ "TUNING": "SINTONIZANDO",
+ "STREAMING": "RECIBIENDO",
+ "UNSUPPORTED": "NO COMPATIBLE",
+ "waiting for IQ": "esperando IQ",
+ "{count} messages": {
+ "one": "{count} mensaje",
+ "many": "{count} de mensajes",
+ "other": "{count} mensajes"
+ },
+ "DSP {count} blocks": {
+ "one": "DSP {count} bloque",
+ "many": "DSP {count} de bloques",
+ "other": "DSP {count} bloques"
+ },
+ "DSP waiting": "DSP en espera",
+ "{level} dBFS audio": "audio {level} dBFS",
+ "audio signal --": "señal de audio --",
+ "audio {state}": "audio {state}",
+ "{count} HEARD": {
+ "one": "CAPTADAS: {count}",
+ "many": "CAPTADAS: {count}",
+ "other": "CAPTADAS: {count}"
+ },
+ "DISCONNECT": "DESCONECTAR",
+ "CONNECT": "CONECTAR",
+ "LOCATING…": "UBICANDO…",
- "Drag to resize · double-click the header to snap back": "Arrastra para cambiar el tamaño · doble clic en el encabezado para restaurarlo",
+ "CH {index} / {total}": "CANAL {index} / {total}",
+ "Station unavailable after directory refresh": "Emisora no disponible tras actualizar el directorio",
+ "Clear reading": "Borrar lectura",
+ "Earlier observation": "Observación anterior",
+ "Observed history": "Historial observado",
+ "Later observation": "Observación posterior",
+ "Latest": "Último",
+ "Newest frame per product": "Fotograma más reciente por producto",
+ "Replay observed history": "Reproducir el historial observado",
+ "S on another day replaces it · × unpins": "S en otro día lo reemplaza · × quita la fijación",
+ "← → preview · S shows the focused day": "← → vista previa · S muestra el día enfocado",
+ "Recent imagery": "Imágenes recientes",
+ "ZOOM IN": "ACERCAR",
+ "Fly in until the view fits the 1,000 km limit": "Acércate hasta que la vista quepa en el límite de 1000 km",
+ "Imagery days, newest first · arrows move, S or A and B pin": "Días de imágenes, el más reciente primero · las flechas mueven, S o A y B fijan",
+ "On the map": "En el mapa",
+ "Mode": "Modo",
+ "Imagery on Esri · Google 3D returns when cleared": "Imágenes sobre Esri · BORRAR restaura Google 3D",
+ "Imagery opacity": "Opacidad de las imágenes",
+ "SWAP": "INVERTIR",
+ "VS BASEMAP": "VS MAPA BASE",
+ "Trade the two sides of the divider": "Intercambiar los dos lados del divisor",
+ "A / B": "A / B",
+ "Newest low-cloud day for this box · scene cloud, not box cloud": "Día más reciente con pocas nubes para este recuadro · nubes de la escena, no del recuadro",
+ "Newest day covering this box · cloudier than 20%": "Día más reciente que cubre este recuadro · más de un 20% de nubes",
+ "SELECT BOX": "SELECCIONAR",
+ "Drag a box on the map (Esc cancels)": "Arrastra un recuadro en el mapa (Esc cancela)",
+ "Newest day with imagery for this box · partial coverage": "Día más reciente con imágenes para este recuadro · cobertura parcial",
+ "USE VIEW": "USAR VISTA",
+ "Use the current view as the box": "Usar la vista actual como recuadro",
+ "Newest daily overview for this box": "Vista general diaria más reciente para este recuadro",
+ "Forget the box and its images": "Olvidar el recuadro y sus imágenes",
+ "newest clear day": "día despejado más reciente",
+ "newest day (cloudy)": "día más reciente (nublado)",
+ "newest day (partial coverage)": "día más reciente (cobertura parcial)",
+ "START HERE": "EMPIEZA AQUÍ",
+ "newest overview": "vista general más reciente",
+ "No imagery": "Sin imágenes",
+ "Checking": "Comprobando",
+ "Loading": "Cargando",
+ "PREVIEW": "VISTA PREVIA",
+ "Newest day with imagery for this box": "Día más reciente con imágenes para este recuadro",
+ "SHOW": "MOSTRAR",
+ "Pin {day} as {slot}": "Fijar {day} como {slot}",
+ "Show {day}": "Mostrar {day}",
+ "pinned {slot}": "fijado en {slot}",
+ "shown": "mostrado",
+ "preview": "vista previa",
+ "start here": "empieza aquí",
+ "No box": "Sin recuadro",
+ "Searching": "Buscando",
+ "Every day is empty here": "Todos los días están vacíos aquí",
+ "Sources off": "Fuentes desactivadas",
+ "VS": "VS",
+ "Not set": "Sin definir",
+ "Basemap": "Mapa base",
+ "Source off": "Fuente desactivada",
+ "Unpin {slot}": "Quitar {slot}",
+ "Unpin the image": "Quitar la imagen fijada",
+ "EXPORT {slot}": "EXP. {slot}",
+ "EXPORT": "EXPORTAR",
+ "Download {slot} as a PNG": "Descargar {slot} como PNG",
+ "Download the image as a PNG": "Descargar la imagen como PNG",
+ "Box {width} × {height} km": "Recuadro de {width} × {height} km",
+ "no imagery": "sin imágenes",
+ "Acquired {time}": "Adquirida {time}",
+ "cloud unknown": "nubosidad desconocida",
+ "Coverage {coverage}": "Cobertura {coverage}",
+ "unknown": "desconocida",
+ "START HERE · {reason}": "EMPIEZA AQUÍ · {reason}",
+ "Daily overview shows little detail in a box this small": "La vista general diaria muestra poco detalle en un recuadro tan pequeño",
+ "{percent}% cloud": "{percent}% de nubes",
+ "Imagery: NASA GIBS and Worldview · HLS (Sentinel-2, Landsat 8/9) and VIIRS": "Imágenes: NASA GIBS y Worldview · HLS (Sentinel‑2, Landsat 8/9) y VIIRS",
+ "{min}–{max}% cloud": "{min}–{max}% de nubes",
+ "Details": "Detalles",
+ "Times, coverage, sources": "Horas, cobertura, fuentes",
+ "HIDE EMPTY DAYS": "OCULTAR DÍAS VACÍOS",
+ "SHOW EMPTY DAYS · {count}": "MOSTRAR DÍAS VACÍOS · {count}",
+ "Days the probe found empty in this box": "Días que el sondeo encontró vacíos en este recuadro",
+ "NO BOX": "SIN RECUADRO",
+ "image": "imagen",
+ "BASEMAP": "MAPA BASE",
+ "The basemap": "El mapa base",
+ "basemap": "mapa base",
+ "SEARCHING": "BUSCANDO",
+ "{count} DAYS": {
+ "one": "{count} DÍA",
+ "many": "{count} DE DÍAS",
+ "other": "{count} DÍAS"
+ },
+ "Recent imagery against the basemap divider": "Divisor de imágenes recientes frente al mapa base",
+ "Recent imagery A and B divider": "Divisor A y B de imágenes recientes",
+ "{before} {left} percent, {after} {right} percent": "{before} {left} por ciento, {after} {right} por ciento",
+ "Zoom in or draw a smaller box": "Acércate o dibuja un recuadro más pequeño",
+ "Select a box or use the view": "Selecciona un recuadro o usa la vista",
+ "Searching the last 30 days": "Buscando en los últimos 30 días",
+ "No days to show for this box": "No hay días que mostrar para este recuadro",
+ "Drag the divider · SWAP trades sides": "Arrastra el divisor · INVERTIR cambia los lados",
+ "Export failed · {error}": "La exportación falló · {error}",
+ "← → preview · A or B pins the focused day": "← → vista previa · A o B fija el día enfocado",
+ "← → preview the other side · A or B pins it": "← → vista previa del otro lado · A o B lo fija",
+ "LOAD": "CARGAR",
+ "No shots yet. Use CAPTURE SHOT to save current look.": "Aún no hay planos. Usa CAPTURAR PLANO para guardar el aspecto actual.",
+ "Double-click to rename": "Doble clic para cambiar el nombre",
+ "Shot name": "Nombre del plano",
+ "RETRYING ALPR CAMERAS": "REINTENTANDO CÁMARAS ALPR",
+ "FETCHING ALPR CAMERAS": "OBTENIENDO CÁMARAS ALPR",
+ "OVERPASS TEMPORARILY UNAVAILABLE": "OVERPASS TEMPORALMENTE NO DISPONIBLE",
+ "Weather data by Open-Meteo.com": "Datos meteorológicos de Open-Meteo.com",
+ "ESC EXIT": "ESC SALIR",
+ "C TOGGLE": "C ALTERNAR",
+ "SIG": "SIG",
+ "NEWS": "NOTICIAS",
+ "LOCAL": "LOCAL",
+ "Cockpit briefing pages": "Páginas de información de la cabina",
+ "MM": "MM",
+ "KTS": "KN",
+ "FT": "FT",
+ "FLT": "FLT",
+ "MIL": "MIL",
+ "SITE": "SITIOS",
+ "WX": "WX",
+ "DIRECTORY: RADIO BROWSER": "DIRECTORIO: RADIO BROWSER",
+ "Use your location for faster ADS-B position decoding": "Usa tu ubicación para decodificar más rápido las posiciones ADS-B",
+ "CHANGE DEVICE": "CAMBIAR",
+ "Choose a different RTL-SDR or receiver channel": "Elige otro RTL-SDR u otro canal del receptor",
+ "TUNE": "SINTONIZAR",
+ "◀ SEEK": "◀ BUSCAR",
+ "SEEK ▶": "BUSCAR ▶",
+ "Local RTL-SDR receiver": "Receptor RTL-SDR local",
+ "RTL-SDR receiver mode": "Modo del receptor RTL-SDR",
+ "Seek broadcast FM stations": "Buscar emisoras de FM",
+ "Tune available internet radio stations": "Sintonizar las emisoras de radio por Internet disponibles",
+ "Local SDR volume": "Volumen del SDR local",
+ "GAIN": "GANANCIA",
+ "FM MHZ": "FM MHZ",
+ "AUTO": "AUTO",
+ "Chrome/Edge · WebUSB · one local tuner shared by FM and the Local ADS-B layer.": "Chrome/Edge · WebUSB · un sintonizador local compartido entre FM y la capa ADS-B local.",
+ "RTL-SDR tuner gain for the current mode": "Ganancia del sintonizador RTL-SDR para el modo actual",
+ "WEATHER": "CLIMA",
+ "Active weather products": "Productos meteorológicos activos",
+ "RECENT IMAGERY": "IMÁGENES RECIENTES",
+ "Imagery days in the box": "Días de imágenes en el recuadro",
+ "MSG/S": "MSG/S",
+ "HEARD": "CAPTADAS",
+ "POSITIONED": "POSICIONADAS",
+ "SDR VOL": "VOL. SDR",
+ "LOCAL RTL-SDR": "RTL-SDR LOCAL",
+ "Cyber sonar contact scanner": "Escáner de contactos del sonar Ciber",
+ "Sonar ring count": "Número de anillos del sonar",
+ "Sonar ring range": "Alcance de los anillos del sonar",
+ "Sonar intensity": "Intensidad del sonar",
+ "Cyber contact and label opacity": "Opacidad de contactos y etiquetas Ciber",
+ "Minimum opacity for map dots, icons, models, brackets, and labels between sonar passes": "Opacidad mínima de puntos, iconos, modelos, corchetes y etiquetas del mapa entre pasadas del sonar",
+ "Sonar sector width": "Ancho del sector del sonar",
+ "Rings": "Anillos",
+ "Range": "Alcance",
+ "Power": "Potencia",
+ "Opacity": "Opacidad",
+ "Sector": "Sector",
+ "Cyber": "Ciber",
+ "Sonar": "Sonar",
+ "Turn Street Level on or off": "Activar o desactivar A pie de calle",
+ "Toggle straight-down and tilted map views": "Alternar entre la vista cenital y la vista inclinada del mapa",
+ "Reset map to north up": "Orientar el mapa al norte",
+ "Reset map bearing to north": "Restablecer la orientación del mapa al norte",
+ "Rain radar": "Radar de lluvia",
+ "Lightning density": "Densidad de rayos",
+ "LATEST · newest per product": "ÚLTIMO · más reciente por producto",
+ "Forecast · valid {valid} · issued {issued}": "Pronóstico · válido {valid} · emitido {issued}",
+ "{detail} · Does not follow history": "{detail} · No sigue el historial",
+ "Forecast · valid {valid}": "Pronóstico · válido {valid}",
+ "{time} · {minutes} min ago": "{time} · hace {minutes} min",
+ "Active weather": "Capas meteorológicas activas",
+ "MINI": "MINI",
+ "STD": "STD",
+ "standard": "estándar",
+ "mini": "mini",
+ "COST UNKNOWN": "COSTO DESCONOCIDO",
+ "ChatGPT OAuth session: {responses} response(s), {input} input and {output} output tokens, {captions} caption transcription(s) reported.": "Sesión OAuth de ChatGPT (datos informados): {responses} respuesta(s), {input} tokens de entrada y {output} de salida, {captions} transcripción(es) de subtítulos.",
+ "USD cost and the API spend cap are unavailable for this auth mode.": "El costo en USD y el límite de gasto de la API no están disponibles con este modo de autenticación.",
+ "Usage is incomplete because a response was still in flight when the session ended.": "El uso está incompleto porque una respuesta seguía en curso cuando terminó la sesión.",
+ "Toggle voice control": "Alternar el control de voz",
+ "Activate to toggle voice": "Pulsa para activar o desactivar la voz",
+ "Voice active": "Voz activa",
+ "Voice could not be started.": "No se pudo iniciar la voz.",
+ "degraded": "degradado",
+ "stale": "desactualizado",
+ "partial": "parcial",
+ "fallback": "respaldo",
+ "unavailable": "no disponible",
+ "{label} on": "{label}: activado",
+ "{label} off": "{label}: desactivado",
+ "Frame aircraft": "Encuadrar aeronaves",
+ "Frame military aircraft": "Encuadrar aeronaves militares",
+ "Frame ships": "Encuadrar buques",
+ "Frame satellites": "Encuadrar satélites",
+ "Frame contacts": "Encuadrar contactos",
+ "{count} aircraft in frame": {
+ "one": "{count} aeronave en el encuadre",
+ "many": "{count} de aeronaves en el encuadre",
+ "other": "{count} aeronaves en el encuadre"
+ },
+ "{count} military aircraft in frame": {
+ "one": "{count} aeronave militar en el encuadre",
+ "many": "{count} de aeronaves militares en el encuadre",
+ "other": "{count} aeronaves militares en el encuadre"
+ },
+ "{count} ships in frame": {
+ "one": "{count} buque en el encuadre",
+ "many": "{count} de buques en el encuadre",
+ "other": "{count} buques en el encuadre"
+ },
+ "{count} satellites in frame": {
+ "one": "{count} satélite en el encuadre",
+ "many": "{count} de satélites en el encuadre",
+ "other": "{count} satélites en el encuadre"
+ },
+ "{count} contacts in frame": {
+ "one": "{count} contacto en el encuadre",
+ "many": "{count} de contactos en el encuadre",
+ "other": "{count} contactos en el encuadre"
+ },
+ "Nearest military aircraft": "Aeronaves militares más cercanas",
+ "Nearest ships": "Buques más cercanos",
+ "Nearest satellites": "Satélites más cercanos",
+ "Nearest aircraft": "Aeronaves más cercanas",
+ "{first} and {second}": "{first} y {second}",
+ "Camera range {range}": "Alcance de la cámara {range}",
+ "Within {radius} of the view": "En un radio de {radius} desde la vista",
+ "Labels on": "Etiquetas activadas",
+ "Framing uses the nearest 80 loaded contacts": "El encuadre usa los 80 contactos cargados más cercanos",
+ "{distance} from {location}": "A {distance} de {location}",
+ "Altitude {altitude}": "Altitud {altitude}",
+ "{origin} to {destination}": "De {origin} a {destination}",
+ "from {origin}": "desde {origin}",
+ "to {destination}": "a {destination}",
+ "Registration {registration}": "Matrícula {registration}",
+ "Route {route}": "Ruta {route}",
+ "View state": "Estado de la vista",
+ "Marked {count} places": {
+ "one": "{count} lugar marcado",
+ "many": "{count} de lugares marcados",
+ "other": "{count} lugares marcados"
+ },
+ "Nothing marked": "Nada marcado",
+ "Not found: {places}": "No encontrado: {places}",
+ "Tracing outlines": "Trazando contornos",
+ "Mark the map": "Marcar el mapa",
+ "Mark {targets} +{more}": "Marcar {targets} +{more}",
+ "Mark {targets}": "Marcar: {targets}",
+ "Fly to {place}": "Volar a {place}",
+ "Nearest aircraft to {place}": "Aeronave más cercana a {place}",
+ "Read the view": "Consultar la vista",
+ "Check view state": "Comprobar el estado de la vista",
+ "Frame {target}": "Encuadrar {target}",
+ "Finding places": "Buscando lugares",
+ "Tracing outline": "Trazando contorno",
+ "Looking up place": "Buscando lugar",
+ "Flying": "Volando",
+ "Turning on layer": "Activando capa",
+ "Loading aircraft": "Cargando aeronaves",
+ "Picking nearest": "Eligiendo la más cercana",
+ "Working": "Procesando",
+ "{value} feet": "{value} pies",
+ "nominal": "nominal",
+ "Source: {label}": "Fuente: {label}",
+ "N": "N",
+ "NNE": "NNE",
+ "NE": "NE",
+ "ENE": "ENE",
+ "E": "E",
+ "ESE": "ESE",
+ "SE": "SE",
+ "SSE": "SSE",
+ "S": "S",
+ "SSW": "SSO",
+ "SW": "SO",
+ "WSW": "OSO",
+ "W": "O",
+ "WNW": "ONO",
+ "NW": "NO",
+ "NNW": "NNO",
+ "Local ADS-B": "ADS-B local",
+ "Transit": "Transporte público",
+ "Recent Imagery": "Imágenes recientes",
+ "Fire Perimeters": "Perímetros de incendios",
+ "Cyclone advisories": "Avisos de ciclones",
+ "EDIT DETAILS": "EDITAR DETALLES",
+ "SHARE SCENE": "COMPARTIR ESCENA",
+ "ON/OFF": "ENC./APAG.",
+ "Voice assistant": "Asistente de voz",
+ "VOICE": "VOZ",
+ "Dismiss voice card": "Cerrar la tarjeta de voz",
+ "YOU": "TÚ",
+ "THIS": "ESTO",
+ "HERE": "AQUÍ",
+ "Plan": "Plan",
+ "Referenced items": "Elementos citados",
+ "NOTES & SOURCES": "NOTAS Y FUENTES",
+ "ΔN": "ΔN",
+ "ΔE": "ΔE",
+ "action|CLEAR": "BORRAR",
+ "ALPR Cameras": "Cámaras ALPR",
+ "Military aircraft": "Aeronaves militares",
+ "Vessels": "Buques",
+ "CCTV + Street View fallback": "CCTV + respaldo de Street View",
+ "OpenStreetMap + optional Google Maps Places": "OpenStreetMap + Google Maps Places opcional",
+ "GFS / ECMWF IFS · FORECAST": "GFS / ECMWF IFS · PRONÓSTICO",
+ "NOAA nowCOAST · OBSERVED": "NOAA nowCOAST · OBSERVADO",
+ "NASA FIRMS · LIVE": "NASA FIRMS · EN VIVO",
+ "data source|Local": "Datos locales",
+ "overview": "vista general",
+ "{percent}% scene cloud": "{percent}% de nubes en la escena",
+ "{min}–{max}% scene cloud": "{min}–{max}% de nubes en la escena",
+ "Sentinel-2 via HLS": "Sentinel‑2 vía HLS",
+ "Landsat 8/9 via HLS": "Landsat 8/9 vía HLS",
+ "coverage|full": "completa",
+ "coverage|partial": "parcial",
+ "m": "m",
+ "km/h": "km/h",
+ "m/s": "m/s",
+ "mph": "mph",
+ "hPa": "hPa",
+ "kt": "kn",
+ "km": "km",
+ "h": "h",
+ "min": "min",
+ "s": "s",
+ "direction|left": "a la izquierda",
+ "direction|right": "a la derecha",
+ "direction|slightly left": "ligeramente a la izquierda",
+ "direction|slightly right": "ligeramente a la derecha",
+ "direction|sharply left": "bruscamente a la izquierda",
+ "direction|sharply right": "bruscamente a la derecha",
+ "direction|straight": "recto",
+ "direction|around": "en sentido contrario",
+ "ordinal|{number}st": "{number}.ª",
+ "ordinal|{number}nd": "{number}.ª",
+ "ordinal|{number}rd": "{number}.ª",
+ "ordinal|{number}th": "{number}.ª",
+ "Head out on {road}": "Sal por {road}",
+ "Head out": "Inicia el recorrido",
+ "Arrive at your destination": "Has llegado a tu destino",
+ "Arrive at your destination, on the left": "Tu destino está a la izquierda",
+ "Arrive at your destination, on the right": "Tu destino está a la derecha",
+ "Make a U-turn": "Da la vuelta",
+ "Make a U-turn onto {road}": "Da la vuelta hacia {road}",
+ "Continue straight": "Sigue recto",
+ "Continue straight onto {road}": "Sigue recto por {road}",
+ "Turn {direction}": "Gira {direction}",
+ "Turn {direction} onto {road}": "Gira {direction} hacia {road}",
+ "maneuver|Turn": "Gira",
+ "Turn onto {road}": "Gira hacia {road}",
+ "Continue {direction}": "Sigue {direction}",
+ "Continue {direction} onto {road}": "Sigue {direction} por {road}",
+ "maneuver|Continue": "Continúa",
+ "Continue onto {road}": "Continúa por {road}",
+ "At the end of the road, turn {direction}": "Al final de la vía, gira {direction}",
+ "At the end of the road, turn {direction} onto {road}": "Al final de la vía, gira {direction} hacia {road}",
+ "At the end of the road, continue": "Al final de la vía, continúa",
+ "At the end of the road, continue onto {road}": "Al final de la vía, continúa por {road}",
+ "Keep {direction} at the fork": "En la bifurcación, mantente {direction}",
+ "Keep {direction} at the fork onto {road}": "En la bifurcación, mantente {direction} hacia {road}",
+ "Continue at the fork": "En la bifurcación, continúa",
+ "Continue at the fork onto {road}": "En la bifurcación, continúa por {road}",
+ "Merge {direction}": "Incorpórate {direction}",
+ "Merge {direction} onto {road}": "Incorpórate {direction} a {road}",
+ "maneuver|Merge": "Incorpórate",
+ "Merge onto {road}": "Incorpórate a {road}",
+ "Take the ramp on the {direction}": "Toma la rampa {direction}",
+ "Take the ramp on the {direction} onto {road}": "Toma la rampa {direction} hacia {road}",
+ "Take the ramp": "Toma la rampa",
+ "Take the ramp onto {road}": "Toma la rampa hacia {road}",
+ "Take the exit on the {direction}": "Toma la salida {direction}",
+ "Take the exit on the {direction} onto {road}": "Toma la salida {direction} hacia {road}",
+ "Take the exit": "Toma la salida",
+ "Take the exit onto {road}": "Toma la salida hacia {road}",
+ "At the roundabout, take the {exit} exit": "En la rotonda, toma la {exit} salida",
+ "At the roundabout, take the {exit} exit onto {road}": "En la rotonda, toma la {exit} salida hacia {road}",
+ "Enter the roundabout": "Entra en la rotonda",
+ "Enter the roundabout onto {road}": "Entra en la rotonda hacia {road}",
+ "At the roundabout, turn {direction}": "En la rotonda, gira {direction}",
+ "At the roundabout, turn {direction} onto {road}": "En la rotonda, gira {direction} hacia {road}",
+ "At the roundabout, continue": "En la rotonda, continúa",
+ "At the roundabout, continue onto {road}": "En la rotonda, continúa por {road}",
+ "Exit the roundabout": "Sal de la rotonda",
+ "Exit the roundabout onto {road}": "Sal de la rotonda hacia {road}",
+ "Use the {direction} lane": "Toma el carril {direction}",
+ "Use the {direction} lane onto {road}": "Toma el carril {direction} hacia {road}",
+ "voice|OFF": "APAG.",
+ "voice|CONNECTING": "CONEX…",
+ "voice|LISTENING": "OYENDO",
+ "voice|EXECUTING": "ACCIÓN",
+ "voice|ERROR": "ERROR",
+ "MIC": "MIC",
+ "WORKING": "EN CURSO",
+ "DONE": "HECHO",
+ "Outline traced": "Contorno trazado",
+ "Outline unavailable": "Contorno no disponible",
+ "in progress": "en curso",
+ "done": "hecho",
+ "failed": "fallido",
+ "cancelled": "cancelado",
+ "view band|STREET": "CALLE",
+ "view band|CITY": "CIUDAD",
+ "view band|METRO": "METRÓPOLI",
+ "view band|REGIONAL": "REGIÓN",
+ "view band|GLOBAL": "GLOBAL",
+ "NEAR {poi} ({city}) {distance}": "CERCA DE {poi} ({city}) {distance}",
+ "SECTOR {lat} {lon}": "SECTOR {lat} {lon}",
+ "ARCTIC": "ÁRTICO",
+ "ANTARCTIC": "ANTÁRTICO",
+ "NORTH AMERICA": "NORTEAMÉRICA",
+ "SOUTH AMERICA": "SUDAMÉRICA",
+ "EUROPE": "EUROPA",
+ "AFRICA": "ÁFRICA",
+ "ASIA": "ASIA",
+ "OCEANIA": "OCEANÍA",
+ "NORTHERN OCEANIC GRID": "CUADRÍCULA OCEÁNICA NORTE",
+ "SOUTHERN OCEANIC GRID": "CUADRÍCULA OCEÁNICA SUR",
+ "N/A": "N/D",
+ "{label} · {radius} AIR/SEA WINDOW": "{label} · VENTANA AIRE/MAR {radius}",
+ "{scope} · INSTALLATIONS {coverage}": "{scope} · INSTALACIONES: {coverage}",
+ "{source} · LOCATION QUERY · RECENT": "{source} · CONSULTA POR UBICACIÓN · RECIENTE",
+ "ft": "ft",
+ "kts": "kn",
+ "PAUSE": "PAUSA",
+ "RESUME": "REANUDAR",
+ "dB": "dB",
+ "radio|NEWS": "NOTICIAS",
+ "radio|TALK": "RADIO HABLADA",
+ "radio|WEATHER": "CLIMA",
+ "radio|SAFETY": "SEGURIDAD",
+ "radio|AIR / SEA": "AIRE / MAR",
+ "radio|TRANSIT": "TRANSPORTE",
+ "radio|MUSIC": "MÚSICA",
+ "radio|OTHER": "OTROS",
+ "SNAPSHOT": "INSTANTÁNEA",
+ "LIVE": "EN VIVO",
+ "UPSTREAM": "ORIGEN",
+ "SYNTHETIC": "SINTÉTICO",
+ "CONFIGURED": "CONFIGURADO",
+ "SEED": "CATÁLOGO",
+ "Live HLS connected": "HLS en vivo conectado",
+ "Live HLS unavailable": "HLS en vivo no disponible",
+ "No stream URL configured": "No hay URL de transmisión configurada",
+ "Live stream connected": "Transmisión en vivo conectada",
+ "Snapshot feed connected": "Fuente de instantáneas conectada",
+ "Media fetch failed": "Error al obtener el contenido multimedia",
+ "Upstream snapshot active": "Instantánea de origen activa",
+ "Fallback Street View frame": "Fotograma de respaldo de Street View",
+ "Upstream unavailable": "Origen no disponible",
+ "No source configured": "No hay fuente configurada",
+ "Upstream HTTP {status}": "Origen: HTTP {status}",
+ "Unexpected media type {type}": "Tipo de contenido inesperado: {type}",
+ "Configured source": "Fuente configurada",
+ "Synthetic fallback": "Respaldo sintético",
+ "Cancel": "Cancelar",
+ "Choose files": "Elegir archivos",
+ "No file chosen": "Ningún archivo seleccionado",
+ "{count} files selected": {
+ "one": "{count} archivo seleccionado",
+ "many": "{count} de archivos seleccionados",
+ "other": "{count} archivos seleccionados"
+ },
+ "Rasuwagadhi witness video": "Video del testigo de Rasuwagadhi",
+ "Bhote Koshi valley footage": "Imágenes del valle del Bhote Koshi",
+ "Flood footage": "Imágenes de la inundación",
+ "Compilation and casualty claims": "Recopilación y afirmaciones sobre víctimas",
+ "SOURCE GEOCONFIRMED · WORLD-PINNED": "FUENTE GEOCONFIRMADA · FIJADA EN EL MAPA",
+ "SOURCE CREDITED · LOCATION UNRESOLVED": "AUTORÍA INDICADA · UBICACIÓN SIN DETERMINAR",
+ "REFERENCE ONLY · CLAIMS UNVERIFIED": "SOLO REFERENCIA · AFIRMACIONES SIN VERIFICAR",
+ "SOURCE GEOCONFIRMED": "FUENTE GEOCONFIRMADA",
+ "2021 historical reference versus 2026 post-event imagery; changes are cumulative and include the July 2025 Rasuwagadhi flood. Schematic downstream progression, not modeled arrival time; not an official hazard model.": "Referencia histórica de 2021 frente a imágenes posteriores al evento de 2026; los cambios son acumulativos e incluyen la inundación de Rasuwagadhi de julio de 2025. Avance esquemático aguas abajo, no un tiempo de llegada modelado; no es un modelo oficial de peligro.",
+ "Immediate collapse viewpoint": "Punto de vista junto al colapso",
+ "Collapse viewpoint": "Vista del colapso",
+ "Debris-dammed lake": "Lago represado por escombros",
+ "Dammed lake": "Lago represado",
+ "Second landslide": "Segundo deslizamiento",
+ "Gyirong border gate": "Paso fronterizo de Gyirong",
+ "Border gate": "Paso fronterizo",
+ "Timure evidence cluster": "Grupo de evidencias de Timure",
+ "Mailung / Upper Trishuli bridge": "Mailung / puente de Upper Trishuli",
+ "Dandagaun viewpoint restaurant": "Restaurante mirador de Dandagaun",
+ "Dandagaun viewpoint": "Mirador de Dandagaun",
+ "Bidur - Trishuli bridge": "Puente Bidur - Trishuli",
+ "Bidur bridge": "Puente de Bidur",
+ "Devighat / Taadi Khola Bridge": "Devighat / puente de Taadi Khola",
+ "Devighat bridge": "Puente de Devighat",
+ "Global Incident Context": "Contexto global del incidente",
+ "Nepal-Focused Globe Rotation": "Rotación del globo hacia Nepal",
+ "Bhote Koshi Regional Approach": "Aproximación regional al Bhote Koshi",
+ "Bhote Koshi Nearby Cities": "Ciudades cercanas al Bhote Koshi",
+ "Bhote Koshi Incident Corridor": "Corredor del incidente del Bhote Koshi",
+ "Bhote Koshi Flood Path": "Trayectoria de la inundación del Bhote Koshi",
+ "Bhote Koshi Corridor Overview": "Vista general del corredor del Bhote Koshi",
+ "Bhote Koshi Upper Valley": "Valle alto del Bhote Koshi",
+ "Upper Valley Collapse": "Colapso en el valle alto",
+ "Debris-Dammed Lake": "Lago represado por escombros",
+ "Nepal-China Border Gate": "Paso fronterizo Nepal-China",
+ "Timure Evidence Cluster": "Grupo de evidencias de Timure",
+ "Syabru Besi Passage": "Paso por Syabru Besi",
+ "Bidur / Trishuli Consequence": "Consecuencias en Bidur / Trishuli",
+ "Final view": "Vista final",
+ "{year} HISTORICAL REFERENCE": "REFERENCIA HISTÓRICA {year}",
+ "{year} POST-EVENT": "POSTERIOR AL EVENTO {year}",
+ "Esri map unavailable · no swipe": "Mapa Esri no disponible · sin comparación",
+ "Swipe needs a globe map": "La comparación necesita un mapa de globo",
+ "Imagery stays on Esri · CLEAR to use Google 3D": "Las imágenes siguen en Esri · BORRAR para usar Google 3D",
+ "Box and images cleared": "Recuadro e imágenes borrados",
+ "Box is {size} wide · limit {limit}": "El recuadro mide {size} de ancho · límite {limit}",
+ "View is {size} wide · limit {limit}": "La vista mide {size} de ancho · límite {limit}",
+ "Frame unavailable; previous observation retained": "Fotograma no disponible; se mantiene la observación anterior",
+ "Weather imagery unavailable": "Imágenes meteorológicas no disponibles",
+ "Weather source unavailable; previous observation retained": "Fuente meteorológica no disponible; se mantiene la observación anterior",
+ "Weather unavailable": "Clima no disponible",
+ "Weather tiles unavailable · previous frame retained": "Teselas meteorológicas no disponibles · se mantiene el fotograma anterior",
+ "Some weather tiles unavailable": "Algunas teselas meteorológicas no disponibles",
+ "Hidden by this map source · choose a globe map": "Oculto con esta fuente del mapa · elige un mapa de globo",
+ "Wind source unavailable": "Fuente de viento no disponible",
+ "Globe imagery unavailable": "Imágenes del globo no disponibles",
+ "Globe field image unavailable": "Imagen del campo en el globo no disponible",
+ "status chip|UNAVAILABLE": "NO DISP.",
+ "Uses registered content or linked media. Those external files are not included in a scene bundle. Their original notices still apply.": "Contiene referencias a contenido registrado o medios vinculados. Esos archivos externos no se incluyen en un paquete de escena. Sus avisos originales siguen vigentes.",
+ "{state} {layers}": "{state}: {layers}",
+ "Selected Space Mission": "Misión espacial seleccionada",
+ "{duration}s + {hold}s": "{duration} s + {hold} s",
+ "Configured Source": "Fuente configurada",
+ "subject": "objetivo",
+ "{value}m": "{value} m",
+ "Google 3D tiles unavailable — check the key's API restrictions, quota, or network": "Teselas de Google 3D no disponibles: revisa las restricciones de API de la clave, la cuota o la red",
+ "Needs {envVars} — add it in Provider Settings — or a Cesium ion token for the ion-hosted route": "Necesita {envVars} — se añade en Ajustes de proveedores — o un token de Cesium ion para la ruta alojada en ion",
+ "Comparison in use by another scene": "La comparación está en uso por otra escena",
+ "A location reading needs a loaded forecast and the Earth at the center of the view.": "Una lectura en un punto necesita un pronóstico cargado y la Tierra en el centro de la vista.",
+ "{mode} {band} {locality} | {region} | ALT {alt} | WINDOW {window} | SUN {sun}° | ONA {ona}° | {zone}": "{mode} · {band} · {locality} | {region} | ALT {alt} | VENTANA {window} | SOL {sun}° | ONA {ona}° | {zone}",
+ "light {source} to use your {name} key": "activa {source} para usar tu clave de {name}",
+ "light {source}": "activa {source}",
+ ", or ": ", o ",
+ "{requirement}, or {offer}": "{requirement}, o {offer}",
+ "The photorealistic 3D planet, place search + Street View": "El planeta 3D fotorrealista, búsqueda de lugares + Street View",
+ "{name} needs the Google 3D map: choose it under MAP SOURCE": "{name} requiere el mapa Google 3D: elígelo en FUENTE DEL MAPA",
+ "zoom in to a street to open {name}": "acércate a una calle para abrir {name}",
+ "Google Street View": "Google Street View",
+ "GOOGLE STREET VIEW": "GOOGLE STREET VIEW",
+ "Google refused GOOGLE_MAPS_API_KEY for Street View — check that the Maps JavaScript API is enabled for it and this site is an allowed referrer": "Google rechazó GOOGLE_MAPS_API_KEY para Street View — comprueba que la clave tenga habilitada la API Maps JavaScript y que este sitio figure entre sus referentes HTTP (sitios web) permitidos",
+ "Street View did not answer — check the network, and that the Maps JavaScript API is enabled for GOOGLE_MAPS_API_KEY": "Street View no respondió — comprueba la red y que la API Maps JavaScript esté habilitada para GOOGLE_MAPS_API_KEY",
+ "click a street to open Street View": "haz clic en una calle para abrir Street View",
+ " or ": " o ",
+ "OPEN {labels}": "ABRIR {labels}",
+ "Open {names} at the centre of the view": "Abrir {names} en el centro de la vista",
+ "Zoom in to a street to open {names} here": "Acércate a una calle para abrir {names} aquí",
+ "radio tag|All": "Todas",
+ "Alternative": "Alternativa",
+ "Ambient": "Ambient",
+ "Blues": "Blues",
+ "Classical": "Clásica",
+ "Country": "Country",
+ "Dance": "Dance",
+ "Electronic": "Electrónica",
+ "Folk": "Folk",
+ "Funk": "Funk",
+ "Hip-Hop": "Hip-Hop",
+ "House": "House",
+ "Indie": "Indie",
+ "Jazz": "Jazz",
+ "Latin": "Latina",
+ "Metal": "Metal",
+ "Oldies": "Clásicos de siempre",
+ "Pop": "Pop",
+ "Punk": "Punk",
+ "R&B": "R&B",
+ "Reggae": "Reggae",
+ "Rock": "Rock",
+ "Soul": "Soul",
+ "Techno": "Techno",
+ "Trance": "Trance",
+ "World": "Músicas del mundo",
+ "{speed}KT": "{speed} KN",
+ "{heading}DEG": "{heading}°",
+ "At least {count}": "Al menos {count}",
+ "Named areas ({n})": "Zonas con nombre ({n})",
+ "{distance} FLIGHT / VESSEL WINDOW": "VENTANA DE VUELOS / BUQUES DE {distance}",
+ "mapped matches within {km} km of the subject": "coincidencias mapeadas a menos de {km} km del objetivo",
+ "none mapped within {km} km; not a complete 250 km survey": "ninguna mapeada a menos de {km} km; no es un barrido completo de 250 km",
+ "mapped matches from the loaded viewport": "coincidencias mapeadas en la vista cargada",
+ "viewport feed is not a complete 250 km survey": "los datos de la vista no son un barrido completo de 250 km",
+ "lane direction|left": "izquierdo",
+ "lane direction|right": "derecho",
+ "lane direction|slightly left": "izquierdo",
+ "lane direction|slightly right": "derecho",
+ "lane direction|sharply left": "del extremo izquierdo",
+ "lane direction|sharply right": "del extremo derecho",
+ "lane direction|straight": "central",
+ "{value}°N": "{value}°N",
+ "{value}°S": "{value}°S",
+ "{value}°E": "{value}°E",
+ "{value}°W": "{value}°O",
+ "fork direction|left": "a la izquierda",
+ "fork direction|right": "a la derecha",
+ "fork direction|slightly left": "ligeramente a la izquierda",
+ "fork direction|slightly right": "ligeramente a la derecha",
+ "fork direction|sharply left": "bruscamente a la izquierda",
+ "fork direction|sharply right": "bruscamente a la derecha",
+ "fork direction|straight": "recto",
+ "installation class|AIRFIELD": "AERÓDROMO",
+ "installation class|NAVAL BASE": "BASE NAVAL",
+ "installation class|RANGE": "CAMPO DE TIRO",
+ "installation class|MILITARY LAND": "TERRENO MILITAR",
+ "installation class|BASE": "BASE",
+ "installation class|PLACES CANDIDATE": "DE GOOGLE PLACES",
+ "installation class|INSTALLATION": "INSTALACIÓN",
+ "fire confidence|high": "alta",
+ "fire confidence|nominal": "nominal",
+ "fire confidence|low": "baja",
+ "age|<1h": "<1 h",
+ "age|{count}h": "{count} h",
+ "age|{count}d": "{count} d",
+ "General emergency": "Emergencia general",
+ "Unlawful interference": "Interferencia ilícita",
+ "Radio failure": "Fallo de radio",
+ "Downed aircraft": "Aeronave siniestrada",
+ "Minimum fuel": "Combustible mínimo",
+ "Lifeguard (medical priority)": "Lifeguard (prioridad médica)",
+ "That file is not valid JSON.": "Ese archivo no es un JSON válido.",
+ "That JSON file is not GeoJSON.": "Ese archivo JSON no es GeoJSON.",
+ "That FeatureCollection has no features list.": "Esa FeatureCollection no tiene lista de features.",
+ "Every GeoJSON feature must have type Feature.": "Cada elemento GeoJSON debe tener el tipo Feature.",
+ "That GeoJSON has invalid geometries.": "Ese GeoJSON tiene geometrías no válidas.",
+ "That GeoJSON contains an unsupported geometry.": "Ese GeoJSON contiene una geometría no admitida.",
+ "That GeoJSON has invalid coordinates.": "Ese GeoJSON tiene coordenadas no válidas.",
+ "That file creates more than {limit} map objects (the limit).": "Ese archivo crea más de {limit} objetos en el mapa (el límite).",
+ "That file has more than {limit} style definitions and image links after cleanup (the limit).": "Tras la limpieza, ese archivo tiene más de {limit} definiciones de estilo y enlaces a imágenes (el límite).",
+ "That file has more than {limit} features (the limit).": "Ese archivo tiene más de {limit} elementos (el límite).",
+ "That file has more than {limit} points (the limit) across {features} features.": "Ese archivo tiene más de {limit} puntos (el límite) en {features} elementos.",
+ "That file has more than {limit} points (the limit).": "Ese archivo tiene más de {limit} puntos (el límite).",
+ "That KMZ unpacks to more than the import limit.": "Al descomprimirse, ese KMZ supera el límite de importación.",
+ "That KMZ is damaged and could not be unpacked.": "Ese KMZ está dañado y no se pudo descomprimir.",
+ "That KMZ is not a readable zip archive.": "Ese KMZ no es un archivo zip legible.",
+ "That KMZ uses a zip format this import does not read.": "Ese KMZ usa un formato zip que esta importación no lee.",
+ "That KMZ is encrypted.": "Ese KMZ está cifrado.",
+ "That KMZ uses a compression method this import does not read.": "Ese KMZ usa un método de compresión que esta importación no lee.",
+ "That KML has invalid geometry bounds.": "Ese KML tiene límites de geometría no válidos.",
+ "That KML has invalid coordinates.": "Ese KML tiene coordenadas no válidas.",
+ "That GPX file has no <gpx> document.": "Ese archivo GPX no tiene documento <gpx>.",
+ "That {format} file is not valid XML.": "Ese archivo {format} no es un XML válido.",
+ "That file has an unreadable image or exceeds the 16-megapixel image limit.": "Ese archivo tiene una imagen ilegible o supera el límite de imagen de 16 megapíxeles.",
+ "That KML could not be read.": "No se pudo leer ese KML.",
+ "That file has invalid point coordinates.": "Ese archivo tiene coordenadas de puntos no válidas.",
+ "Ground heights are not available for that file. Try again when the map has loaded.": "Las alturas del terreno no están disponibles para ese archivo. Vuelve a intentarlo cuando el mapa haya cargado.",
+ "That file took too long to read.": "La lectura de ese archivo tardó demasiado.",
+ "Nothing to import.": "No hay nada que importar.",
+ "That file is larger than {size} MiB.": "Ese archivo pesa más de {size} MiB.",
+ "Only GeoJSON, KML, KMZ and GPX files can be imported.": "Solo se pueden importar archivos GeoJSON, KML, KMZ y GPX.",
+ "That file has nothing to draw.": "Ese archivo no tiene nada que dibujar.",
+ "That KMZ holds no KML document.": "Ese KMZ no contiene ningún documento KML.",
+ "That {format} file could not be read.": "No se pudo leer ese archivo {format}.",
+ "That file has {count} map objects; the limit is {limit}.": "Ese archivo tiene {count} objetos en el mapa; el límite es {limit}.",
+ "Ground heights could not be read. Try that file again.": "No se pudieron leer las alturas del terreno. Vuelve a intentarlo con ese archivo.",
+ "That file has invalid point graphics.": "Ese archivo tiene gráficos de puntos no válidos.",
+ "Low-accuracy score < 2%": "Índice de baja precisión < 2%",
+ "Low-accuracy score 2–10%": "Índice de baja precisión 2–10%",
+ "Low-accuracy score > 10%": "Índice de baja precisión > 10%",
+ "GNSS integrity source unavailable": "Fuente de integridad GNSS no disponible",
+ "Regional sample · 250 nm radius · cells from visited views over 30 min": "Muestra regional · radio de 250 NM · celdas de las vistas visitadas en 30 min",
+ "Retrying automatically at {time} UTC": "Reintento automático a las {time} UTC",
+ "Retrying automatically after provider cooldown": "Reintento automático tras la pausa del proveedor",
+ "Updates automatically after pan or zoom and once a minute. The public feed covers a 250-nautical-mile circle around the view centre; zooming out does not make it a worldwide snapshot. Blank cells are outside sampled coverage or have insufficient observations.": "Se actualiza automáticamente al desplazar o hacer zoom y una vez por minuto. El feed público cubre un círculo de 250 millas náuticas alrededor del centro de la vista; alejarte no lo convierte en una instantánea mundial. Las celdas vacías están fuera de la cobertura muestreada o no tienen observaciones suficientes.",
+ "Low-accuracy score = 100 × max(0, bad − 1) / total: one aircraft is discounted, so this is not the raw share. Cells need {aircraft} aircraft over {minutes} minutes. Navigation-integrity anomalies are not a detection of jamming or spoofing.": "Índice de baja precisión = 100 × max(0, malas − 1) / total: se descuenta una aeronave, así que no es la proporción bruta. Cada celda necesita {aircraft} aeronaves en {minutes} minutos. Las anomalías de integridad de navegación no son una detección de interferencias ni de suplantación.",
+ "SQUAWK {code} · {status}": "SQUAWK {code} · {status}",
+ "ADS-B PRIORITY · {status}": "ADS-B PRIORIDAD · {status}",
+ "ADS-B EMERGENCY · {status}": "ADS-B EMERGENCIA · {status}",
+ "{aircraftClass} · {emergency} · {feedState}": "{aircraftClass} · {emergency} · {feedState}",
+ "Ground heights could not be refreshed. Try the file again when the map has loaded.": "No se pudieron actualizar las alturas del terreno. Vuelve a intentarlo con el archivo cuando el mapa haya cargado.",
+ "{count} map objects": {
+ "one": "{count} objeto en el mapa",
+ "many": "{count} de objetos en el mapa",
+ "other": "{count} objetos en el mapa"
+ },
+ ", drawn with its own styles": ", dibujado con sus propios estilos",
+ "Hide {name}": "Ocultar {name}",
+ "Show {name}": "Mostrar {name}",
+ "Fly to {name}": "Volar a {name}",
+ "Remove {name}": "Quitar {name}",
+ "At most {count} files at once — remove one first.": "Como máximo {count} archivos a la vez: quita uno primero.",
+ "Reading {name}…": "Leyendo {name}…",
+ "That file could not be read.": "No se pudo leer ese archivo.",
+ "Added {count} files.": {
+ "one": "Se añadió {count} archivo.",
+ "many": "Se añadieron {count} de archivos.",
+ "other": "Se añadieron {count} archivos."
+ },
+ "{count} files could not be added ({name}: {error})": {
+ "one": "No se pudo añadir {count} archivo ({name}: {error})",
+ "many": "No se pudieron añadir {count} de archivos ({name}: {error})",
+ "other": "No se pudieron añadir {count} archivos ({name}: {error})"
+ },
+ "Some KML content was left out.": "Se omitió parte del contenido KML.",
+ "GNSS Integrity": "Integridad GNSS",
+ "Show your own GeoJSON, KML, KMZ or GPX files on the globe (or drop them onto it). File bytes stay on this device; overlays can appear in map screenshots shared with voice.": "Muestra en el globo tus propios archivos GeoJSON, KML, KMZ o GPX (o suéltalos sobre él). Los archivos no salen de este dispositivo; las capas pueden aparecer en capturas del mapa compartidas con la voz.",
+ "Import": "Importar",
+ "Choose GeoJSON, KML, KMZ or GPX files": "Elige archivos GeoJSON, KML, KMZ o GPX",
+ "Imported files": "Archivos importados",
+ "DOCKED · {name}": "ACOPLE · {name}",
+ "DOCKED · {name} · +{extra}": "ACOPLE · {name} · +{extra}",
+ "loading coverage...": "cargando cobertura...",
+ "live feed unavailable": "fuente en vivo no disponible",
+ "GBFS fetch error": "error al obtener datos GBFS",
+ "Open the Street Level panel to view imagery": "Abre el panel \"A pie de calle\" para ver las imágenes",
+ "Image could not be opened": "No se pudo abrir la imagen",
+ "Mapillary rejected MAPILLARY_CLIENT_TOKEN — replace it in Provider Settings": "Mapillary rechazó MAPILLARY_CLIENT_TOKEN — sustitúyelo en Ajustes de proveedores",
+ "Coverage requests are being rate-limited — they resume on their own": "Las peticiones de cobertura están limitadas por frecuencia — se reanudan solas",
+ "No street-level imagery within {radius} m of that point": "No hay imágenes a pie de calle a menos de {radius} m de ese punto",
+ "No street-level imagery within {radius} m of the view centre": "No hay imágenes a pie de calle a menos de {radius} m del centro de la vista",
+ "Aim the middle of the view at a street to look for imagery there": "Apunta el centro de la vista a una calle para buscar imágenes allí",
+ "Street View has no imagery for this place": "Street View no tiene imágenes de este lugar",
+ "GOOGLE_MAPS_API_KEY is not set": "GOOGLE_MAPS_API_KEY no está configurada",
+ "The Google Maps JavaScript API could not load": "No se pudo cargar la API de Maps JavaScript de Google",
+ "Weather request timed out": "La petición del clima agotó el tiempo de espera",
+ "Malformed weather manifest": "Manifiesto del clima mal formado",
+ "Weather HTTP {status}": "Clima: HTTP {status}",
+ "Weather image HTTP {status}": "Imagen del clima: HTTP {status}",
+ "Weather prefetch unavailable": "Precarga del clima no disponible",
+ "Infrared decode failed": "Falló la decodificación del infrarrojo",
+ "rate limited": "límite de peticiones superado",
+ "routing service is rate limited": "el servicio de rutas superó el límite de peticiones",
+ "route leg too long": "tramo de la ruta demasiado largo",
+ "route too long": "ruta demasiado larga",
+ "Routing is rate limited — try again in a moment": "Se alcanzó el límite de peticiones de rutas — inténtalo de nuevo en un momento",
+ "{error} — try again in a moment": "{error} — inténtalo de nuevo en un momento",
+ "Routing unavailable (HTTP {status})": "Rutas no disponibles (HTTP {status})",
+ "CelesTrak unreachable": "CelesTrak inaccesible",
+ "KartaView is rate-limiting requests — they resume on their own": "KartaView está limitando las peticiones — se reanudan solas",
+ "KartaView’s photos here are archived and cannot be shown": "Las fotos de KartaView de aquí están archivadas y no se pueden mostrar",
+ "KartaView did not filter this area in time — move the map to ask again": "KartaView no filtró esta zona a tiempo — mueve el mapa para pedirlo de nuevo",
+ "None of KartaView’s photos here pass the imagery filter": "Ninguna foto de KartaView de aquí pasa el filtro de imágenes",
+ "KartaView did not answer in time — try again": "KartaView no respondió a tiempo — inténtalo de nuevo",
+ "KartaView could not be reached — check the network": "No se pudo conectar con KartaView — comprueba la red",
+ "KartaView sent an answer that could not be read": "KartaView envió una respuesta que no se pudo leer",
+ "KartaView is rate-limiting requests": "KartaView está limitando las peticiones",
+ "KartaView is rate-limiting requests — try again in a moment": "KartaView está limitando las peticiones — inténtalo de nuevo en un momento",
+ "KartaView sent too much data": "KartaView envió demasiados datos",
+ "KartaView has no such photo": "KartaView no tiene esa foto",
+ "The KartaView photo could not be loaded": "No se pudo cargar la foto de KartaView",
+ "KartaView has no position for this photo": "KartaView no tiene la posición de esta foto",
+ "Map tiles temporarily unavailable": "Teselas del mapa temporalmente no disponibles",
+ "Mapped names temporarily unavailable": "Nombres mapeados temporalmente no disponibles",
+ "No mapped sites in view": "No hay sitios mapeados a la vista",
+ "No mapped sites within {km} km of the contact": "No hay sitios mapeados a menos de {km} km del contacto",
+ "{count} mapped sites in view": {
+ "one": "{count} sitio mapeado a la vista",
+ "many": "{count} de sitios mapeados a la vista",
+ "other": "{count} sitios mapeados a la vista"
+ },
+ "{count} mapped sites within {km} km of the contact": {
+ "one": "{count} sitio mapeado a menos de {km} km del contacto",
+ "many": "{count} de sitios mapeados a menos de {km} km del contacto",
+ "other": "{count} sitios mapeados a menos de {km} km del contacto"
+ },
+ "Too many mapped sites in view to list them all": "Hay demasiados sitios mapeados a la vista para listarlos todos",
+ "Installation context unavailable": "Contexto de instalaciones no disponible",
+ "Focus vessel {name}, MMSI {mmsi}": "Enfocar el buque {name}, MMSI {mmsi}",
+ "Open the USGS initial report for the 26 August 2026 Nepal landslide": "Abrir el informe inicial del USGS sobre el deslizamiento del 26 de agosto de 2026 en Nepal",
+ "YouTube source": "Fuente de YouTube",
+ "Facebook source": "Fuente de Facebook",
+ "Military airfield": "Aeródromo militar",
+ "Naval base": "Base naval",
+ "Firing range": "Campo de tiro",
+ "Military land": "Terreno militar",
+ "Mapped installation": "Instalación mapeada",
+ "Military area": "Zona militar",
+ "SIMULATED — {reason}": "SIMULADO — {reason}",
+ "TomTom key unavailable": "Clave de TomTom no disponible",
+ "TomTom daily budget reached": "Se alcanzó el límite diario de TomTom",
+ "TomTom upstream unreachable": "Servidor de TomTom inaccesible",
+ "TomTom flow unavailable": "Flujo de TomTom no disponible",
+ "API key rejected — check AISSTREAM_API_KEY": "Clave de API rechazada — revisa AISSTREAM_API_KEY",
+ "feed silent {seconds}s — no AIS data": "fuente en silencio {seconds} s — sin datos AIS",
+ "feed silent — no AIS data": "fuente en silencio — sin datos AIS",
+ "feed down — retrying slowly (attempt {attempt})": "fuente caída — reintentando despacio (intento {attempt})",
+ "feed down — retrying slowly": "fuente caída — reintentando despacio",
+ "reconnecting to feed… (attempt {attempt})": "reconectando con la fuente… (intento {attempt})",
+ "reconnecting to feed…": "reconectando con la fuente…",
+ "AISSTREAM_API_KEY not set": "AISSTREAM_API_KEY no está configurada",
+ "live feed unsupported": "fuente en vivo no compatible",
+ "connecting to feed…": "conectando con la fuente…",
+ "feed disconnected": "fuente desconectada",
+ "feed down": "fuente caída",
+ "feed idle": "fuente inactiva",
+ "AIS live load failed": "Falló la carga de AIS en vivo",
+ "age|{count}m": "{count} min",
+ "{acres} ac": {
+ "one": "{acres} acre",
+ "many": "{acres} de acres",
+ "other": "{acres} acres"
+ },
+ "{percent}% contained": "contenido al {percent}%",
+ "containment unknown": "contención desconocida",
+ "{cause} cause": "causa: {cause}",
+ "{personnel} personnel": {
+ "one": "{personnel} efectivo",
+ "many": "{personnel} de efectivos",
+ "other": "{personnel} efectivos"
+ },
+ "{county} County": "condado de {county}",
+ "{cost} to date": "{cost} hasta la fecha",
+ "discovered {age} ago": "detectado hace {age}",
+ "updated {age} ago": "actualizado hace {age}",
+ "part of {complex}": "parte de {complex}",
+ "InciWeb ↗ · click card to open": "InciWeb ↗ · haz clic en la tarjeta para abrir",
+ "FIRE · {name}": "INCENDIO · {name}",
+ "Unnamed incident": "Sin nombre",
+ "Open {title} on InciWeb": "Abrir {title} en InciWeb",
+ "Vehicle {vehicle}": "Vehículo {vehicle}",
+ "Bus": "Autobús",
+ "Tram": "Tranvía",
+ "Subway": "Metro",
+ "Train": "Tren",
+ "Ferry": "Ferri",
+ "Transit vehicle": "Vehículo de transporte público",
+ "No recent fix": "Sin posición reciente",
+ "Waiting for update": "Esperando actualización",
+ "Moving": "En movimiento",
+ "reported {speed} km/h": "velocidad notificada: {speed} km/h",
+ "reported hdg {heading}°": "rumbo notificado: {heading}°",
+ "Last report: stopped at stop {stop}": "Último informe: detenido en la parada {stop}",
+ "Last report: arriving at stop {stop}": "Último informe: llegando a la parada {stop}",
+ "Last report: next stop {stop}": "Último informe: próxima parada {stop}",
+ "occupancy|empty": "vacío",
+ "occupancy|many seats available": "muchos asientos libres",
+ "occupancy|few seats available": "pocos asientos libres",
+ "occupancy|standing room only": "solo de pie",
+ "occupancy|crushed standing room only": "abarrotado, solo de pie",
+ "occupancy|full": "lleno",
+ "occupancy|not accepting passengers": "no admite pasajeros",
+ "occupancy|not boardable": "no se puede subir",
+ "Shown at street level · depth not in the feed": "Se muestra a nivel de calle · la fuente no indica la profundidad",
+ "Reported {seconds} s ago": "Notificado hace {seconds} s",
+ "Reported {minutes} min ago": "Notificado hace {minutes} min",
+ "{reported} (feed time)": "{reported} (hora de la fuente)",
+ "shown {seconds} s behind": "se muestra con {seconds} s de retraso",
+ "Available trail: {minutes} min": "Rastro disponible: {minutes} min",
+ "Available trail: {minutes} min (limited)": "Rastro disponible: {minutes} min (limitado)",
+ "UNAVAILABLE · {source} · Roads unavailable": "NO DISPONIBLE · {source} · Vías no disponibles",
+ "Roads: {source}": "Vías: {source}",
+ "TomTom roads unavailable while the traffic service is unreachable": "Vías de TomTom no disponibles mientras el servicio de tráfico esté inaccesible",
+ "Hybrid unavailable while the traffic service is unreachable": "Modo híbrido no disponible mientras el servicio de tráfico esté inaccesible",
+ "TomTom roads need a TomTom key": "Las vías de TomTom necesitan una clave de TomTom",
+ "Hybrid needs a TomTom key": "El modo híbrido necesita una clave de TomTom",
+ "Local surface still loading": "La superficie bajo las vías aún se está cargando",
+ "Partial coverage": "Cobertura parcial",
+ "Detailed roads unavailable": "Vías detalladas no disponibles",
+ "Reduced detail coverage": "Cobertura con menos detalle",
+ "OpenFreeMap tiles rate-limited": "Teselas de OpenFreeMap con límite de peticiones",
+ "OpenFreeMap tiles timed out": "Las teselas de OpenFreeMap agotaron el tiempo de espera",
+ "OpenFreeMap tiles unavailable": "Teselas de OpenFreeMap no disponibles",
+ "Heard by your receiver": "Captado por tu receptor",
+ "browser SDR": "SDR del navegador",
+ "decoder feed": "fuente del decodificador",
+ "Your RTL-SDR receiver and decoder feed": "Tu receptor RTL-SDR y la fuente del decodificador",
+ "Your decoder feed": "Tu fuente del decodificador",
+ "Your RTL-SDR receiver": "Tu receptor RTL-SDR",
+ "NO CALLSIGN": "SIN INDICATIVO",
+ "ALT {altitude} FT · GS {speed} KT · TRK {track}": "ALT {altitude} FT · VEL. SUELO {speed} KN · TRK {track}",
+ "V/S {rate}": "VEL. VERT. {rate}",
+ "V/S {rate} FPM": "VEL. VERT. {rate} FT/MIN",
+ "POSITION {age}": "POSICIÓN {age}",
+ "POSITION {seconds} S AGO": "POSICIÓN HACE {seconds} S",
+ "{count} MSGS": {
+ "one": "{count} MENSAJE",
+ "many": "{count} DE MENSAJES",
+ "other": "{count} MENSAJES"
+ },
+ "installation class|BARRACKS": "CUARTEL",
+ "installation class|TRAINING AREA": "ZONA DE INSTRUCCIÓN",
+ "Seeking up…": "Buscando hacia arriba…",
+ "Seeking down…": "Buscando hacia abajo…",
+ "Scanning {mhz} MHz…": "Escaneando {mhz} MHz…",
+ "Found {mhz} MHz · {snr} dB": "Encontrado {mhz} MHz · {snr} dB",
+ "Broadcaster stream is unavailable or blocked by the browser.": "El flujo de la emisora no está disponible o el navegador lo ha bloqueado.",
+ "Playback requires a direct click or tap.": "La reproducción requiere un clic o un toque directo.",
+ "Broadcaster stream could not be started.": "No se pudo iniciar el flujo de la emisora.",
+ "Directory refresh degraded; showing the previous station catalog.": "La actualización del directorio fue parcial; se muestra el catálogo de emisoras anterior.",
+ "Radio directory coverage is degraded.": "El directorio de radio funciona con interrupciones.",
+ "Directory refresh failed; showing the previous station catalog.": "La actualización del directorio falló; se muestra el catálogo de emisoras anterior.",
+ "Radio directory is temporarily unavailable.": "El directorio de radio no está disponible temporalmente.",
+ "Decoder feeds: {feeds}": "Fuentes del decodificador: {feeds}",
+ " · read while Local ADS-B is on": " · se leen mientras ADS-B local está activo",
+ "idle": "en espera",
+ "running": "activo",
+ "suspended": "suspendido",
+ "closed": "cerrado",
+ "Local FM stopped: internet radio started": "FM local detenida: se inició la radio por Internet",
+ "ALPR cameras": "cámaras ALPR",
+ "OVERPASS RATE-LIMITED": "OVERPASS CON LÍMITE DE PETICIONES",
+ "OVERPASS TIMED OUT": "OVERPASS AGOTÓ EL TIEMPO DE ESPERA",
+ "OVERPASS COULD NOT COMPLETE THE QUERY": "OVERPASS NO PUDO COMPLETAR LA CONSULTA",
+ "MAP TILES TEMPORARILY UNAVAILABLE": "TESELAS DEL MAPA TEMPORALMENTE NO DISPONIBLES",
+ "MAPPED NAMES TEMPORARILY UNAVAILABLE": "NOMBRES MAPEADOS TEMPORALMENTE NO DISPONIBLES",
+ "Shared flight follow expired": "El seguimiento del vuelo compartido ha caducado",
+ "Shared military flight follow expired": "El seguimiento del vuelo militar compartido ha caducado",
+ "Shared satellite follow expired": "El seguimiento del satélite compartido ha caducado",
+ "Shared flight could not be restored — feed unavailable": "No se pudo restaurar el vuelo compartido — fuente no disponible",
+ "Shared military flight could not be restored — feed unavailable": "No se pudo restaurar el vuelo militar compartido — fuente no disponible",
+ "Shared satellite could not be restored — feed unavailable": "No se pudo restaurar el satélite compartido — fuente no disponible",
+ "Shared flight is unavailable": "El vuelo compartido no está disponible",
+ "Shared military flight is unavailable": "El vuelo militar compartido no está disponible",
+ "Shared satellite is unavailable": "El satélite compartido no está disponible",
+ "Scene not saved — browser storage unavailable": "Escena no guardada — almacenamiento del navegador no disponible",
+ "Scene not saved — existing saved project could not be read. Export edits or import a valid file.": "Escena no guardada — no se pudo leer el proyecto guardado. Exporta los cambios o importa un archivo válido.",
+ "Saved project could not be read; storage preserved. Import a valid file to resume saving.": "No se pudo leer el proyecto guardado; el almacenamiento se conserva. Importa un archivo válido para volver a guardar.",
+ "Scene not saved — {reason}": "Escena no guardada — {reason}",
+ "Stopped": "Detenido",
+ "Stopped (Esc)": "Detenido (Esc)",
+ "Camera ownership changed": "Cambió el control de la cámara",
+ "Scene layer turned off": "Capa de la escena desactivada",
+ "Seeking scene clock": "Desplazando el reloj de la escena",
+ "Importing project": "Importando proyecto",
+ "Camera move interrupted": "Movimiento de cámara interrumpido",
+ "Scene media timed out": "El contenido multimedia de la escena agotó el tiempo de espera",
+ "Space Missions isolates replay data. Exit the mode to enable {layer}.": "El modo Misiones espaciales aísla los datos de repetición. Sal del modo para activar {layer}.",
+ "Tilted view": "Vista inclinada",
+ "Straight-down view": "Vista cenital",
+ "North up": "Norte arriba",
+ "Exit cockpit to fly to a camera": "Sal de la cabina para volar a una cámara",
+ "Exit cockpit to fly to a location": "Sal de la cabina para volar a una ubicación",
+ "Exit cockpit to fly to a photo": "Sal de la cabina para volar a una foto",
+ "Exit cockpit to fly to a shared view": "Sal de la cabina para volar a una vista compartida",
+ "Exit cockpit to fly to a target": "Sal de la cabina para volar a un objetivo",
+ "Exit cockpit to fly to a vessel": "Sal de la cabina para volar a un buque",
+ "Exit cockpit to fly to a fire": "Sal de la cabina para volar a un incendio",
+ "Exit cockpit to fly to a route": "Sal de la cabina para volar a una ruta",
+ "Exit cockpit to fly to a file": "Sal de la cabina para volar a un archivo",
+ "Exit cockpit to fly to a scene": "Sal de la cabina para volar a una escena",
+ "Go to expanded Radio section": "Ir a la sección de Radio expandida",
+ "Expand Radio section in Context": "Expandir la sección de Radio en Contexto",
- "Double-click the header to snap the panel back": "Haz doble clic en el encabezado para devolver el panel a su sitio",
+ "New scene name": "Nombre de la nueva escena",
+ "Delete scene \"{scene}\" and all shots?": "¿Eliminar la escena \"{scene}\" y todos sus planos?",
+ "Detailed outline unavailable": "Contorno detallado no disponible",
+ "Provider Settings does not answer proxied requests": "Ajustes de proveedores no responde a peticiones a través de un proxy",
+ "Provider Settings is disabled while sharing is enabled": "El panel \"Ajustes de proveedores\" está desactivado mientras el uso compartido esté activado",
+ "Provider Settings answers only the machine running the server": "Ajustes de proveedores solo responde al equipo que ejecuta el servidor",
+ "Provider Settings answers only local hostnames": "Ajustes de proveedores solo responde a nombres de host locales",
+ "Provider Settings requires an exact local Origin": "Ajustes de proveedores requiere un Origin local exacto",
+ "Unrecognized Origin refused": "Origin no reconocido: petición rechazada",
+ "Cross-origin requests are refused": "Se rechazan las peticiones de otro origen",
+ "Content-Type must be application/json": "Content-Type debe ser application/json",
+ "Method not allowed": "Método no permitido",
+ "Request too large": "Petición demasiado grande",
+ "Invalid JSON": "JSON no válido",
+ "Body must be a JSON object of {ENV_VAR: value}": "El cuerpo debe ser un objeto JSON de {ENV_VAR: value}",
+ "No keys provided": "No se envió ninguna clave",
+ "At most {limit} keys per save": "Como máximo {limit} claves por guardado",
+ "Unknown key: {name}": "Clave desconocida: {name}",
+ "{name} must be a string": "{name}: el valor debe ser una cadena de texto",
+ "{name} is empty": "{name}: el valor está vacío",
+ "{name} is longer than any real key ({limit} max)": "{name}: el valor es más largo que cualquier clave real (máximo {limit})",
+ "{name} may only contain printable characters with no spaces": "{name}: solo se admiten caracteres imprimibles, sin espacios",
+ "{name} contains a character that is not valid in a key (#, quotes, $, \\, or backtick)": "{name}: hay un carácter no válido en una clave (#, comillas, $, \\ o acento grave)",
+ "{name} is configured outside Provider Settings and can only be changed where it was set": "{name} se configuró fuera de Ajustes de proveedores y solo se puede cambiar donde se definió",
+ "The key was not saved: could not restrict the credential file to your account; nothing was saved": "La clave no se guardó: no se pudo restringir el archivo de credenciales a tu cuenta; no se guardó nada",
+ "The key was not saved: the existing configuration could not be read, so nothing was changed": "La clave no se guardó: no se pudo leer la configuración existente, así que no se cambió nada",
+ "Could not write the {store} store": "No se pudo escribir en el almacén {store}",
+ "Could not check ChatGPT sign-in. Try again.": "No se pudo comprobar el inicio de sesión de ChatGPT. Inténtalo de nuevo.",
+ "Cloud voice will use OPENAI_API_KEY on the next session.": "La voz en la nube usará OPENAI_API_KEY en la próxima sesión.",
+ "Checking local ChatGPT OAuth sign-in…": "Comprobando el inicio de sesión OAuth local de ChatGPT…",
+ "Could not check ChatGPT sign-in.": "No se pudo comprobar el inicio de sesión de ChatGPT.",
+ "ChatGPT OAuth selected for cloud voice. Your API key stays saved and available.": "OAuth de ChatGPT seleccionado para la voz en la nube. Tu clave de API sigue guardada y disponible.",
+ "ChatGPT sign-in expired. Opening sign-in again…": "El inicio de sesión de ChatGPT caducó. Abriéndolo de nuevo…",
+ "Opening ChatGPT sign-in in your browser…": "Abriendo el inicio de sesión de ChatGPT en tu navegador…",
+ "Could not start ChatGPT sign-in on this machine.": "No se pudo abrir el inicio de sesión de ChatGPT en este equipo.",
+ "Finish ChatGPT sign-in in the browser. Waiting for it to complete…": "Termina de iniciar sesión en ChatGPT en el navegador. Esperando a que se complete…",
+ "ChatGPT sign-in timed out. Click {button} to try again.": "Se agotó el tiempo para iniciar sesión en ChatGPT. Haz clic en \"{button}\" para intentarlo de nuevo.",
+ "ChatGPT sign-in complete. OAuth will be used for the next cloud voice session.": "Sesión de ChatGPT iniciada. Se usará OAuth en la próxima sesión de voz en la nube.",
+ "OAuth check failed: {detail}": "Error al comprobar OAuth: {detail}",
+ "unsaved CCTV calibration": "la calibración de CCTV sin guardar",
+ "the open cockpit": "la cabina abierta",
+ "Switching language reloads the page. This will be lost: {items}. Switch anyway?": "Cambiar de idioma recarga la página. Se perderá lo siguiente: {items}. ¿Cambiar de todos modos?",
+ "Wind upstream unavailable": "Origen de datos de viento no disponible",
+ "WebUSB needs desktop Chrome or Edge": "WebUSB requiere Chrome o Edge de escritorio",
+ "connect a receiver in Radio": "conecta un receptor en Radio",
+ "receiver is in FM mode": "el receptor está en modo FM",
+ "Cyclone advisories unavailable": "Avisos de ciclones no disponibles",
+ "Cyclone data unavailable": "Datos de ciclones no disponibles",
+ "Drag to size the box": "Arrastra para dar tamaño al recuadro",
+ "Press on the ground, not the sky": "Pulsa sobre el suelo, no sobre el cielo",
+ "Point the camera at the ground to use the view": "Apunta la cámara al suelo para usar la vista",
+ "That point cannot anchor a box": "Ese punto no puede anclar un recuadro",
+ "Box edges must be finite": "Coordenadas del recuadro no válidas",
+ "Longitudes must be within ±180°": "Las longitudes deben estar dentro de ±180°",
+ "Select one side of the dateline": "No cruces la línea de cambio de fecha",
+ "Box must enclose an area": "El recuadro debe abarcar un área",
+ "Imagery stops at ±{limit}° latitude": "Las imágenes llegan hasta ±{limit}° de latitud",
+ "{owner} is using the pointer — close it first": "Puntero en uso: {owner}. Ciérralo primero",
+ "OpenSky OAuth client missing/invalid": "Cliente OAuth de OpenSky ausente o no válido",
+ "OpenSky OAuth rejected credentials": "OpenSky OAuth rechazó las credenciales",
+ "OpenSky username/password rejected": "OpenSky rechazó el usuario o la contraseña",
+ "OpenSky auth missing": "Falta la autenticación de OpenSky",
+ "OpenSky auth required": "OpenSky requiere autenticación",
+ "OpenSky auth invalid": "Autenticación de OpenSky no válida",
+ "OpenSky auth failed": "Falló la autenticación de OpenSky",
+ "Source snapshot {minutes} min old": "La instantánea de la fuente tiene {minutes} min",
+ "{source} rate limited (anonymous)": "{source}: límite de peticiones (anónimo)",
+ "{source} rate limited": "{source}: límite de peticiones",
+ "{source} HTTP {status}": "{source}: HTTP {status}",
+ "{source} network error": "{source}: error de red",
+ "Malformed {source} aircraft rows": "{source}: filas de aeronaves mal formadas",
+ "Malformed {source} response": "{source}: respuesta mal formada",
+ "Source snapshot time unavailable": "Hora de la instantánea de la fuente no disponible",
+ "Live data unavailable": "Datos en vivo no disponibles",
+ "{n} aircraft": {
+ "one": "{n} aeronave",
+ "many": "{n} de aeronaves",
+ "other": "{n} aeronaves"
+ },
+ "{n} military aircraft": {
+ "one": "{n} aeronave militar",
+ "many": "{n} de aeronaves militares",
+ "other": "{n} aeronaves militares"
+ },
+ "{n} ships": {
+ "one": "{n} buque",
+ "many": "{n} de buques",
+ "other": "{n} buques"
+ },
+ "{n} satellites": {
+ "one": "{n} satélite",
+ "many": "{n} de satélites",
+ "other": "{n} satélites"
+ },
+ "{n} launches": {
+ "one": "{n} lanzamiento",
+ "many": "{n} de lanzamientos",
+ "other": "{n} lanzamientos"
+ },
+ "{n} earthquakes": {
+ "one": "{n} terremoto",
+ "many": "{n} de terremotos",
+ "other": "{n} terremotos"
+ },
+ "{n} fires": {
+ "one": "{n} incendio",
+ "many": "{n} de incendios",
+ "other": "{n} incendios"
+ },
+ "{n} fire perimeters": {
+ "one": "{n} perímetro de incendio",
+ "many": "{n} de perímetros de incendio",
+ "other": "{n} perímetros de incendio"
+ },
+ "{n} cyclones": {
+ "one": "{n} ciclón",
+ "many": "{n} de ciclones",
+ "other": "{n} ciclones"
+ },
+ "{n} buses": {
+ "one": "{n} autobús",
+ "many": "{n} de autobuses",
+ "other": "{n} autobuses"
+ },
+ "{n} bike share": {
+ "one": "{n} estación de bicicletas compartidas",
+ "many": "{n} de estaciones de bicicletas compartidas",
+ "other": "{n} estaciones de bicicletas compartidas"
+ },
+ "{n} flock cameras": {
+ "one": "{n} cámara ALPR",
+ "many": "{n} de cámaras ALPR",
+ "other": "{n} cámaras ALPR"
+ },
+ "{n} military bases": {
+ "one": "{n} base militar",
+ "many": "{n} de bases militares",
+ "other": "{n} bases militares"
+ },
+ "{n} datacenters": {
+ "one": "{n} centro de datos",
+ "many": "{n} de centros de datos",
+ "other": "{n} centros de datos"
+ },
+ "{n} dams": {
+ "one": "{n} presa",
+ "many": "{n} de presas",
+ "other": "{n} presas"
+ },
+ "{n} results": {
+ "one": "{n} resultado",
+ "many": "{n} de resultados",
+ "other": "{n} resultados"
+ },
+ "anywhere in the loaded data": "en todos los datos cargados",
+ "in view": "a la vista",
+ "within {radius} of the view centre": "en un radio de {radius} del centro de la vista",
+ "within {radius} of {place} (Contacts window)": "en un radio de {radius} de {place} (ventana de Contactos)",
+ "within {radius} of {place}": "en un radio de {radius} de {place}",
+ "within {radius}": "en un radio de {radius}",
+ "over {region}": "en {region}",
+ "At least {items}": "Al menos {items}",
+ "{items} {scope}": "{items} {scope}",
+ "last 24 h": "últimas 24 h",
+ "past 30 d and upcoming": "últimos 30 d y próximos",
+ "the flights layer loads by viewport": "la capa de vuelos se carga según la vista",
+ "distance is ground distance, not overhead": "la distancia es sobre el terreno hasta el punto subsatélite, no hasta el satélite",
+ "the count is a lower bound because at least one layer reached its retained limit.": "el recuento es un mínimo porque al menos una capa alcanzó su límite de retención.",
+ "{label} loading": "{label}: cargando",
+ "{label} error": "{label}: error",
+ "counted the first {returned} loaded records": "se contaron los primeros {returned} registros cargados",
+ "counted {returned} of {total} loaded records": "se contaron {returned} de {total} registros cargados",
+ "{layers} just turned on — still loading, counts will rise": "{layers}: recién activado — aún se está cargando, los recuentos subirán",
+ "Contacts panel snapshot at {time} — the same retained cohort supplies the card, speech, and follow-up memory": "Instantánea del panel Contactos ({time}) — el mismo conjunto retenido alimenta la tarjeta, la voz y la memoria de seguimiento",
+ "Contacts panel snapshot — the same retained cohort supplies the card, speech, and follow-up memory": "Instantánea del panel Contactos — el mismo conjunto retenido alimenta la tarjeta, la voz y la memoria de seguimiento",
+ "Not answered: {layers}": "Sin respuesta: {layers}",
+ "The flights layer is not enabled": "La capa de vuelos no está activada",
+ "The military layer is not enabled": "La capa de vuelos militares no está activada",
+ "The satellites layer is not enabled": "La capa de satélites no está activada",
+ "The ais-live-vessels layer is not enabled": "La capa de buques AIS no está activada",
+ "Could not enable the requested layer": "No se pudo activar la capa solicitada",
+ "Could not disable the requested layer": "No se pudo desactivar la capa solicitada",
+ "Radio layer unavailable": "La capa de radio no está disponible",
+ "Camera navigation is unavailable in the current view": "La navegación de la cámara no está disponible en la vista actual",
+ "Camera navigation policy unavailable": "La política de navegación de la cámara no está disponible",
+ "Nearest-aircraft selection supports Flights or Military Flights only": "La selección de la aeronave más cercana solo funciona con vuelos o vuelos militares",
+ "Nearest-aircraft selection needs a preset, place name, or latitude and longitude": "Para seleccionar la aeronave más cercana se necesita un preajuste, un nombre de lugar o la latitud y la longitud",
+ "Could not arrive at the requested place": "No se pudo llegar al lugar solicitado",
+ "The nearest airborne aircraft could not be selected": "No se pudo seleccionar la aeronave en vuelo más cercana",
+ "No flights within {radius} of the current view": "No hay vuelos en un radio de {radius} de la vista actual",
+ "No military within {radius} of the current view": "No hay vuelos militares en un radio de {radius} de la vista actual",
+ "No satellites within {radius} of the current view": "No hay satélites en un radio de {radius} de la vista actual",
+ "No vessels within {radius} of the current view": "No hay buques en un radio de {radius} de la vista actual",
+ "{layer} is enabled on the {source} feed, but no airborne aircraft is loaded in the {place} view yet": "La capa {layer} está activada con la fuente {source}, pero aún no hay aeronaves en vuelo cargadas en la vista de {place}",
+ "{layer} is enabled, but no airborne aircraft is loaded in the {place} view yet": "La capa {layer} está activada, pero aún no hay aeronaves en vuelo cargadas en la vista de {place}",
+ "{layer} is enabled, but its aircraft feed is unavailable": "La capa {layer} está activada, pero su fuente de aeronaves no está disponible",
+ "{layer} is enabled, but its destination refresh did not complete": "La capa {layer} está activada, pero la actualización en el destino no terminó",
+ "{layer} is enabled, but {source} is unavailable": "La capa {layer} está activada, pero {source} no está disponible",
+ "Could not arrive at {place}": "No se pudo llegar a {place}",
+ "{name} is no longer loaded": "{name} ya no está cargado",
+ "Unknown target layer: {target}": "Capa de destino desconocida: {target}",
+ "Layer": "Capa",
+ "there": "allí",
+ "Frame flights": "Encuadrar aeronaves",
+ "Frame military": "Encuadrar aeronaves militares",
+ "Frame vessels": "Encuadrar buques",
+ "Fly to Location": "Volar al lugar",
+ "Nearest aircraft to Here": "Aeronave más cercana aquí",
+ "Estimate is incomplete — a response was still in flight when the session ended, so its usage was never reported.": "La estimación está incompleta: una respuesta seguía en curso cuando terminó la sesión, así que su uso nunca se informó.",
+ "STANDARD": "ESTÁNDAR",
+ "vehicle motion|Stopped": "Detenido",
+ "ACQUIRING FRAME": "OBTENIENDO FOTOGRAMA",
+ "Camera source temporarily unavailable": "Fuente de cámaras no disponible temporalmente",
+ "Perimeter source unavailable": "Fuente de perímetros no disponible",
+ "Imagery catalog unavailable": "Catálogo de imágenes no disponible",
+ "Earthquake source unavailable": "Fuente de terremotos no disponible",
+ "TeleGeography load failed": "Falló la carga de TeleGeography",
+ "Wind request timed out": "La petición del viento agotó el tiempo de espera",
+ "Malformed wind manifest": "Manifiesto del viento mal formado",
+ "Malformed wind grid": "Malla del viento mal formada",
+ "Unknown wind model": "Modelo de viento desconocido",
+ "Unknown weather overlay": "Capa de clima desconocida",
+ "Temperature field unavailable": "Campo de temperatura no disponible",
+ "Mean sea level pressure field unavailable": "Campo de presión a nivel del mar no disponible",
+ "KartaView answered HTTP {status}": "KartaView respondió HTTP {status}",
+ "KartaView refused the request (code {code})": "KartaView rechazó la petición (código {code})",
+ "Stopped by voice": "Detenido por voz",
+ "drawings on the map": "los dibujos del mapa",
+ "imported map files": "los archivos importados en el mapa",
+ "the active voice session": "la sesión de voz activa",
+ "Light aircraft": "Avioneta",
+ "Glider": "Planeador",
+ "Turboprop": "Turbohélice",
+ "Airliner": "Avión comercial",
+ "Widebody": "Avión de fuselaje ancho",
+ "Four-engine jet": "Reactor cuatrimotor",
+ "Helicopter": "Helicóptero",
+ "Fast jet": "Avión de alto rendimiento",
+ "Business jet": "Reactor ejecutivo",
+ "Drone": "Dron",
+ "fire cause|Human": "humana",
+ "fire cause|Natural": "natural",
+ "fire cause|Undetermined": "indeterminada",
+ "fire cause|Unknown": "desconocida",
+ "fire behavior|Minimal": "actividad mínima",
+ "fire behavior|Moderate": "actividad moderada",
+ "fire behavior|Active": "actividad alta",
+ "fire behavior|Extreme": "actividad extrema",
+ "Type {level} Incident": "incidente de tipo {level}",
+ "${amount}K": "{amount} mil $",
+ "${amount}M": "{amount} M$",
+ "${amount}B": "{amount} mil M$",
+ "{speed} kn": "{speed} kn",
+ "1090 MHz": "1090 MHz",
+ "978 MHz UAT": "978 MHz UAT",
+ "feed status|live": "en vivo",
+ "feed status|stale": "desactualizada",
+ "feed status|unreachable": "inaccesible",
+ "feed status|invalid": "no válida",
+ "Vector tile metadata unavailable": "Metadatos de teselas vectoriales no disponibles",
+ "Vector tiles unavailable": "Teselas vectoriales no disponibles",
+ "Vector tiles unavailable (HTTP {status})": "Teselas vectoriales no disponibles (HTTP {status})",
+ "Vector tile request timed out": "Las teselas vectoriales agotaron el tiempo de espera",
+ "Zoom in for vector tile coverage": "Acércate para cargar las teselas vectoriales",
+ "Camera coverage unavailable": "Cobertura de cámaras no disponible",
+ "Hybrid": "Híbrido",
+ "TomTom roads only, each with its live flow": "Solo vías de TomTom, cada una con su flujo en vivo",
+ "TomTom roads only, each with its live flow (needs a TomTom key)": "Solo vías de TomTom, cada una con su flujo en vivo (necesita una clave de TomTom)",
+ "OpenStreetMap roads, with TomTom flow matched when available": "Vías de OpenStreetMap, con el flujo de TomTom emparejado cuando está disponible",
+ "TomTom roads first; OpenStreetMap fills the rest, simulated": "Primero las vías de TomTom; OpenStreetMap completa el resto con flujo simulado",
+ "TomTom roads first; OpenStreetMap fills the rest, simulated (needs a TomTom key)": "Primero las vías de TomTom; OpenStreetMap completa el resto con flujo simulado (necesita una clave de TomTom)",
+ "Austin": "Austin",
+ "San Francisco": "San Francisco",
+ "New York": "Nueva York",
+ "Tokyo": "Tokio",
+ "London": "Londres",
+ "Paris": "París",
+ "Dubai": "Dubái",
+ "Washington DC": "Washington D. C.",
+ "Tallinn": "Tallin",
+ "Los Angeles": "Los Ángeles",
+ "Data attribution": "Atribución de datos",
+ "Data provided by:": "Datos proporcionados por:",
+ "Exit cockpit to view weather coverage": "Sal de la cabina para ver la cobertura de la capa meteorológica",
+ "Exit cockpit to fly to a cyclone": "Sal de la cabina para volar a un ciclón",
+ "the title of scene {scene} is empty or longer than {max} characters": "el título de la escena {scene} está vacío o supera los {max} caracteres",
+ "the title of shot {shot} in scene {scene} is empty or longer than {max} characters": "el título del plano {shot} de la escena {scene} está vacío o supera los {max} caracteres",
+ "the project is larger than 5 MiB": "el proyecto pesa más de 5 MiB",
+ "the project has too many shots": "el proyecto tiene demasiados planos",
+ "the scene data failed validation": "los datos de la escena no superaron la validación",
+ "Layer on": "Capa: activada",
+ "Layer off": "Capa: desactivada",
+ "Zoom in": "Acercar",
+ "Zoom out": "Alejar",
+ "Zoom out to globe": "Alejar hasta el globo",
+ "Open data layers": "Abrir las capas de datos",
+ "Open or close a panel": "Abrir o cerrar un panel",
+ "Change context mode": "Cambiar el modo de contexto",
+ "Control cockpit": "Controlar la cabina",
+ "Change visual style": "Cambiar el estilo visual",
+ "Adjust HUD": "Ajustar el HUD",
+ "Adjust cyber sonar": "Ajustar el sonar Ciber",
+ "Adjust detection overlay": "Ajustar la superposición de detección",
+ "Change map stack": "Cambiar el conjunto de mapas",
+ "Adjust post-processing": "Ajustar el posprocesado",
+ "Control scene": "Controlar la escena",
+ "Control CCTV": "Controlar las cámaras CCTV",
+ "Control radio": "Controlar la radio",
+ "Track contact": "Rastrear el contacto",
+ "Stop tracking": "Detener el rastreo",
+ "Clear marks": "Borrar las marcas",
+ "Move camera": "Mover la cámara",
+ "Fly route": "Recorrer la ruta",
+ "Analyst query": "Consulta analítica",
+ "Next ISS pass": "Próximo paso de la EEI",
+ "Next satellite pass": "Próximo paso del satélite",
+ "Action": "Acción",
+ "The photo could not be loaded": "No se pudo cargar la foto",
+ "{name} photo. ← and → step along the sequence. On a 360° photo, drag or use Shift+← →, ↑ ↓ to look around, and + − to zoom": "Foto de {name}. ← y → avanzan por la secuencia. En una foto de 360°, arrastra o usa Mayús+← →, ↑ ↓ para mirar alrededor, y + − para hacer zoom",
+ "{name} street-level photo": "Foto a pie de calle de {name}",
+ "Previous photo in this sequence (←)": "Foto anterior de la secuencia (←)",
+ "Next photo in this sequence (→)": "Foto siguiente de la secuencia (→)",
+ "The Panoramax photo could not be loaded": "No se pudo cargar la foto de Panoramax",
+ "Panoramax is busy — coverage resumes on its own": "Panoramax está saturado — la cobertura se reanuda sola",
+ "no Panoramax photos in view": "no hay fotos de Panoramax a la vista",
+ "no Panoramax photos here match the filters": "aquí no hay fotos de Panoramax que cumplan los filtros",
+ "Panoramax sent a map tile that could not be read": "Panoramax envió una tesela del mapa que no se pudo leer",
+ "This Panoramax photo is no longer available": "Esta foto de Panoramax ya no está disponible",
+ "zoom in to see Panoramax coverage": "acércate para ver la cobertura de Panoramax",
+ "Panoramax did not answer in time — try again": "Panoramax no respondió a tiempo — inténtalo de nuevo",
+ "Panoramax could not be reached — check the connection": "No se pudo conectar con Panoramax — comprueba la conexión",
+ "Panoramax sent too much data": "Panoramax envió demasiados datos",
+ "Panoramax is busy": "Panoramax está saturado",
+ "Panoramax sent an unreadable answer": "Panoramax envió una respuesta que no se pudo leer",
+ "Apply the full cloud brightness key; 100% filter strength": "Aplica el filtro de brillo de nubes completo; intensidad del filtro 100%",
+ "Show the complete infrared image; 0% filter strength": "Muestra la imagen infrarroja completa; intensidad del filtro 0%",
+ "FILTER": "FILTRO",
+ "Cloud filter strength": "Intensidad del filtro de nubes",
+ "Panoramax answered HTTP {status}": "Panoramax respondió HTTP {status}",
+ "Highest air-quality readings in view": "Lecturas de calidad del aire más altas a la vista",
+ "Low": "Baja",
+ "Moderate": "Moderada",
+ "High": "Alta",
+ "Very High": "Muy alta",
+ "Air quality": "Calidad del aire",
+ "{n} sequences in view · click a line for its nearest photo": {
+ "one": "{n} secuencia a la vista · haz clic en una línea para su foto más cercana",
+ "many": "{n} secuencias a la vista · haz clic en una línea para su foto más cercana",
+ "other": "{n} secuencias a la vista · haz clic en una línea para su foto más cercana"
+ },
+ "FOV {value}° (DATASHEET)": "FOV {value}° (FICHA TÉCNICA)",
+ "SPEC FOV {span}° (CAPABILITY)": "FOV DE FICHA {span}° (CAPACIDAD)",
+ "{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · ESPECIFICACIONES: CCTV-DATABASE.COM",
+ "Canada only · ECCC AQHI network": "Solo Canadá · red AQHI de ECCC",
+ "{count} stations reporting": {
+ "one": "{count} estación con datos",
+ "many": "{count} de estaciones con datos",
+ "other": "{count} estaciones con datos"
+ },
+ "No readings available": "No hay lecturas disponibles",
+ "No current readings": "Sin lecturas actuales",
+ "Low health risk": "Riesgo bajo para la salud",
+ "Moderate health risk": "Riesgo moderado para la salud",
+ "High health risk": "Riesgo alto para la salud",
+ "Very High health risk": "Riesgo muy alto para la salud",
+ "Air quality request failed": "Falló la petición de calidad del aire",
+ "ECCC request timed out": "La petición a ECCC agotó el tiempo de espera",
+ "Malformed AQHI station response": "Respuesta de estaciones AQHI mal formada",
+ "Malformed AQHI observation response": "Respuesta de observaciones AQHI mal formada",
+ "No AQHI stations available": "No hay estaciones AQHI disponibles",
+ "{n} air quality": {
+ "one": "{n} estación de calidad del aire",
+ "many": "{n} de estaciones de calidad del aire",
+ "other": "{n} estaciones de calidad del aire"
+ },
+ "GNSS feed rate limited (HTTP 429)": "Fuente GNSS: límite de peticiones superado (HTTP 429)",
+ "GNSS feed unavailable (HTTP {status})": "Fuente GNSS no disponible (HTTP {status})",
+ "GNSS snapshot needs a view anchor": "La instantánea GNSS necesita un punto de referencia de la vista",
+ "Malformed GNSS integrity snapshot": "Instantánea de integridad GNSS mal formada",
+ "GNSS integrity snapshot has no observation time": "La instantánea de integridad GNSS no tiene hora de observación",
+ "{feed} feed unavailable": "Fuente {feed} no disponible",
+ "Loading {feeds}": "Cargando {feeds}",
+ "{count} CelesTrak groups unavailable": {
+ "one": "{count} grupo de CelesTrak no disponible",
+ "many": "{count} de grupos de CelesTrak no disponibles",
+ "other": "{count} grupos de CelesTrak no disponibles"
+ },
+ "Malformed launch snapshot": "Instantánea de lanzamientos mal formada",
+ "Malformed perimeter snapshot": "Instantánea de perímetros mal formada",
+ "Overpass returned an incomplete camera response": "Overpass devolvió una respuesta de cámaras incompleta",
+ "Fly below {km} km to a covered region": "Desciende por debajo de {km} km sobre una región con cobertura",
+ "No feed here yet · {n} regions available": {
+ "one": "Aún no hay fuente aquí · {n} región disponible",
+ "many": "Aún no hay fuente aquí · {n} de regiones disponibles",
+ "other": "Aún no hay fuente aquí · {n} regiones disponibles"
+ },
+ "Wind speed field unavailable": "Campo de velocidad del viento no disponible",
+ "Decoder feeds": "Fuentes del decodificador",
+ "WebUSB + decoder feeds": "WebUSB + fuentes del decodificador",
+ "opening receiver": "abriendo el receptor",
+ "checking decoder feeds": "comprobando las fuentes del decodificador",
+ "listening": "escuchando",
+ "USB error": "error de USB",
+ "{count} heard": {
+ "one": "{count} aeronave captada",
+ "many": "{count} de aeronaves captadas",
+ "other": "{count} aeronaves captadas"
+ },
+ "{rate} msg/s": "{rate} msg/s",
+ "USB {rate} msg/s": "USB {rate} msg/s",
+ "{count} feeds live": {
+ "one": "{count} fuente en vivo",
+ "many": "{count} de fuentes en vivo",
+ "other": "{count} fuentes en vivo"
+ },
+ "feeds {names} stale": {
+ "one": "fuente {names} desactualizada",
+ "many": "fuentes {names} desactualizadas",
+ "other": "fuentes {names} desactualizadas"
+ },
+ "feeds {names} unreachable": {
+ "one": "fuente {names} inaccesible",
+ "many": "fuentes {names} inaccesibles",
+ "other": "fuentes {names} inaccesibles"
+ },
+ "feeds {names} invalid": {
+ "one": "fuente {names} no válida",
+ "many": "fuentes {names} no válidas",
+ "other": "fuentes {names} no válidas"
+ },
+ "unsaved provider keys": "las claves de proveedores sin guardar",
+ "Exit cockpit to fly to an aircraft": "Sal de la cabina para volar a una aeronave",
+ "Exit cockpit to fly to a satellite": "Sal de la cabina para volar a un satélite",
+ "Exit cockpit to frame contacts": "Sal de la cabina para encuadrar contactos",
+ "{feed} {count} ({seconds}s old)": "{feed} {count} (hace {seconds} s)",
+ "entry {n}": "n.º {n}",
+ "Upstream response too large": "Respuesta del origen demasiado grande",
+ "Included in bundle": "Incluido en el paquete",
+ "Missing bundle file — reimport its bundle": "Falta el archivo en el paquete — vuelve a importar su paquete",
+ "Source configured; file checked when loaded": "Fuente configurada; el archivo se comprobará al cargarlo",
+ "Source unavailable": "Fuente no disponible",
+ "Coverage tile failed": "No se pudo cargar la tesela de cobertura",
+ "Unknown": "Desconocido",
+ "USB work abandoned after a stalled transfer": "Trabajo USB cancelado tras una transferencia bloqueada",
+ "SDR decoder did not start; receiver stopped": "El decodificador SDR no arrancó; receptor detenido",
+ "SDR decoder stopped responding; receiver stopped": "El decodificador SDR dejó de responder; receptor detenido",
- "SDR decoder fell behind; receiver stopped": "El decodificador SDR se quedó atrás; receptor detenido"
++ "SDR decoder fell behind; receiver stopped": "El decodificador SDR se quedó atrás; receptor detenido",
++ "Zoom in to see street-level coverage": "Acércate para ver la cobertura a pie de calle",
++ "Point the camera at the ground for street-level coverage": "Apunta la cámara al suelo para ver la cobertura a pie de calle",
++ "Sequence images unavailable": "Las imágenes de la secuencia no están disponibles",
++ "Switch Street Level on to draw its coverage.": "Activa Street Level para dibujar su cobertura.",
++ "Every provider is switched off: light a chip to draw its coverage.": "Todos los proveedores están apagados: enciende uno para dibujar su cobertura.",
++ "No sequences in view match the filter": "Ninguna secuencia a la vista coincide con el filtro",
++ "No coverage in view": "No hay cobertura a la vista",
++ "Show the street-level view full screen (Esc shrinks it)": "Mostrar la vista a pie de calle a pantalla completa (Esc la reduce)"
+ }
diff --cc src/i18n/locales/ru.json
index 000000000,019415690..48b5af9de
mode 000000,100644..100644
--- a/src/i18n/locales/ru.json
+++ b/src/i18n/locales/ru.json
@@@ -1,0 -1,2960 +1,2956 @@@
+ {
+ "Flying to Austin, TX...": "Перелёт в Остин, Техас...",
+ "Restoring shared view...": "Восстановление общего вида...",
+ "Initializing systems...": "Инициализация систем...",
+ "Configuring viewer...": "Настройка просмотрщика...",
+ "Loading Google 3D Tiles...": "Загрузка Google 3D Tiles...",
+ "Loading the keyless globe...": "Загрузка глобуса без ключа...",
+ "Google 3D Tiles unavailable ({detail}). Loading the keyless globe...": "Google 3D Tiles недоступны ({detail}). Загрузка глобуса без ключа...",
+ "Close data attribution": "Закрыть атрибуцию данных",
+ "observed or mapped nearby context": "наблюдаемая или картографическая обстановка",
+ "no observed or mapped objects in current feeds": "нет наблюдаемых или картографированных объектов в текущих потоках",
+ "feed unavailable": "поток данных недоступен",
+ "feed stale": "поток данных устарел",
+ "Brightest naked-eye objects — CelesTrak visual group": "Самые яркие объекты невооружённым глазом — визуальная группа CelesTrak",
+ "COMMS": "СВЯЗЬ",
+ "Broadband constellation shell — shown only in DENSE mode": "Оболочка широкополосной группировки — только в режиме ПЛОТНО",
+ "STATION": "СТАНЦИЯ",
+ "Crewed stations and their visiting vehicles": "Пилотируемые станции и прибывающие к ним корабли",
+ "NAV": "NAV",
+ "GNSS navigation — GPS, GLONASS, Galileo": "Навигация GNSS — GPS, ГЛОНАСС, Galileo",
+ "GEO": "GEO",
+ "Geostationary belt — comms and weather, fixed over the equator": "Геостационарный пояс — связь и погода, неподвижно над экватором",
+ "VISUAL": "ВИДИМЫЕ",
+ "FISHING": "РЫБОЛОВНОЕ",
+ "TOWING": "БУКСИРОВКА",
+ "DREDGER": "ЗЕМСНАРЯД",
+ "DIVE OPS": "ВОДОЛАЗНОЕ",
+ "MILITARY": "ВОЕННОЕ",
+ "SAILING": "ПАРУСНИК",
+ "PLEASURE": "ПРОГУЛОЧНОЕ",
+ "PILOT": "ЛОЦМАН",
+ "SAR": "СПАСАТЕЛЬНОЕ",
+ "TUG": "БУКСИР",
+ "PORT TENDER": "ПОРТОВОЕ",
+ "ANTI-POLLUTION": "НЕФТЕСБОРЩИК",
+ "LAW ENFORCE": "ПАТРУЛЬНОЕ",
+ "MEDICAL": "МЕДИЦИНСКОЕ",
+ "HIGH-SPEED": "СКОРОСТНОЕ",
+ "PASSENGER": "ПАССАЖИРСКОЕ",
+ "CARGO": "ГРУЗОВОЕ",
+ "TANKER": "ТАНКЕР",
+ "OTHER": "ДРУГОЕ",
+ "Starting live contacts…": "Запуск контактов в реальном времени…",
+ "Opening space missions…": "Открытие космических миссий…",
+ "Scanning active events…": "Сканирование активных событий…",
+ "Live earthquakes and active fires, from USGS and NASA": "Землетрясения и активные пожары в реальном времени от USGS и NASA",
+ "It feels like a forbidden cockpit—then you realize the sources are public and the data is real.": "Будто вы в запретной кабине — а потом понимаете: источники открыты, а данные настоящие.",
+ "ENVIRONMENTAL": "ПРИРОДА",
+ "EARTH WATCH": "ДОЗОР ЗЕМЛИ",
+ "ACTIVE EVENTS": "АКТИВНЫЕ СОБЫТИЯ",
+ "Working…": "Работаем…",
+ "Could not open that mission{detail}. Retry or explore manually.": "Не удалось открыть эту миссию{detail}. Повторите попытку или исследуйте вручную.",
+ "This browser is blocking storage, so that could not be saved.": "Браузер блокирует хранилище, поэтому сохранить не удалось.",
+ "SUMMARY": "СВОДКА",
+ "Awaiting telemetry...": "Ожидание телеметрии...",
+ "REC": "REC",
+ "REMOVE": "УДАЛИТЬ",
+ "Remove {title} from this app's saved keys": "Удалить {title} из сохранённых ключей этого приложения",
+ "POWER UP · {count} KEYS WAITING": {
+ "one": "ЗАПУСК · {count} КЛЮЧ В ОЖИДАНИИ",
+ "few": "ЗАПУСК · {count} КЛЮЧА В ОЖИДАНИИ",
+ "many": "ЗАПУСК · {count} КЛЮЧЕЙ В ОЖИДАНИИ",
+ "other": "ЗАПУСК · {count} КЛЮЧА В ОЖИДАНИИ"
+ },
+ "POWERED UP": "ЗАПУЩЕНО",
+ "your app configuration": "ваша конфигурация приложения",
+ "your local .env": "ваш локальный .env",
+ "Saving…": "Сохранение…",
+ "Save failed ({status}).": "Не удалось сохранить ({status}).",
+ "Save failed: {detail}": "Не удалось сохранить: {detail}",
+ "Paste at least one key first.": "Сначала вставьте хотя бы один ключ.",
+ "Saved to {store}. Restarting — this page reloads itself.": "Сохранено: {store}. Перезапуск — страница перезагрузится сама.",
+ "Remove this key from your saved configuration?": "Удалить этот ключ из сохранённой конфигурации?",
+ "Removed from {store}. Restarting — this page reloads itself.": "Удалено: {store}. Перезапуск — страница перезагрузится сама.",
+ "More flight-polling credits (anonymous works without)": "Повышенный лимит запросов рейсов (анонимно работает и без ключа)",
+ "Street-level imagery and coverage in the Street Level layer. Free: register an app in the Mapillary developer dashboard and paste its Client Token": "Уличные снимки и покрытие в слое «Уличные снимки». Бесплатно: зарегистрируйте приложение в панели разработчика Mapillary и вставьте его клиентский токен (Client Token).",
+ "Higher space-missions request allowance": "Повышенный лимит запросов для космических миссий",
+ "Places context + Street View fallback; optional separate key": "Контекст Places + резерв: Просмотр улиц; отдельный ключ — по желанию",
+ "Voice control — API key or ChatGPT OAuth": "Голосовое управление — ключ API или ChatGPT OAuth",
+ "Live ships, worldwide": "Суда в реальном времени по всему миру",
+ "Live active-fire detections": "Обнаружение активных пожаров в реальном времени",
+ "Real live traffic (keyless runs a simulation)": "Настоящие пробки в реальном времени (без ключа — симуляция)",
+ "Bing imagery map stacks + world terrain": "Снимки Bing + рельеф мира",
+ "Global Context navigation": "Навигация глобального контекста",
+ "Previous — prior visited contact in the 250 km window": "Назад — предыдущий посещённый контакт в радиусе 250 км",
+ "PREVIOUS": "ПРЕД.",
+ "FOCUS": "ФОКУС",
+ "Next — nearest unvisited contact in the 250 km window": "Далее — ближайший непосещённый контакт в радиусе 250 км",
+ "NEXT": "СЛЕД.",
+ "Open-source mapped/observed context. Missing broadcasts, unloaded map areas, or unmapped sites are not evidence of absence.": "Контекст из открытых источников. Отсутствие трансляций, незагруженные области карты или неотмеченные объекты — не доказательство отсутствия.",
+ "CONTEXT READY": "КОНТЕКСТ ГОТОВ",
+ "GLOBAL CONTEXT OFF": "ГЛОБАЛЬНЫЙ КОНТЕКСТ ВЫКЛ.",
+ "SELECT A FLIGHT, VESSEL, OR MAPPED INSTALLATION": "ВЫБЕРИТЕ РЕЙС, СУДНО ИЛИ ОБЪЕКТ НА КАРТЕ",
+ "ENABLE TO LOAD OBSERVED / MAPPED PROXIMITY": "ВКЛЮЧИТЕ ДЛЯ ЗАГРУЗКИ НАБЛЮДАЕМОГО / КАРТОГРАФИРОВАННОГО ОКРУЖЕНИЯ",
+ "Unavailable": "Недоступно",
+ "Focus {label}": "Фокус на {label}",
+ "HDG {value}°": "КУРС {value}°",
+ "BRG {value}°": "ПЕЛ. {value}°",
+ "BRG —": "ПЕЛ. —",
+ "CRS {value}°": "ПУТЬ {value}°",
+ "Military flights": "Военные рейсы",
+ "AIS vessels": "Суда AIS",
+ "Mapped installations": "Картографированные объекты",
+ "CURRENT VIEWPORT ONLY": "ТОЛЬКО ТЕКУЩАЯ ОБЛАСТЬ ОБЗОРА",
+ "WITHIN {km} KM": "В РАДИУСЕ {km} КМ",
+ "Flights": "Рейсы",
+ "syncing {count} city feeds...": "синхронизация городских потоков: {count}...",
+ "scanning nearby systems...": "поиск ближайших систем...",
+ "Station {id}": "Станция {id}",
+ "Station": "Станция",
+ "🚲 {bikes} avail · {docks} docks · {capacity} cap": "🚲 доступно {bikes} · своб. мест {docks} · вмест. {capacity}",
+ "⚠️ Not installed": "⚠️ Не установлена",
+ "⚠️ Not renting": "⚠️ Не выдаёт",
+ "⚠️ Not returning": "⚠️ Не принимает",
+ "HDG {value}° (ESTIMATED)": "КУРС {value}° (ОЦЕНКА)",
+ "{count} CAMERAS STANDING BY · NO CAMERA SELECTED · CLICK A CAMERA TO ACTIVATE": "КАМЕР В ГОТОВНОСТИ: {count} · КАМЕРА НЕ ВЫБРАНА · НАЖМИТЕ КАМЕРУ ДЛЯ АКТИВАЦИИ",
+ "No cameras available in catalog.": "В каталоге нет доступных камер.",
+ "{city} CCTV": "CCTV: {city}",
+ "FOV {value}°": "ОБЗОР {value}°",
+ "COVERAGE {value}km²": "ОХВАТ {value} КМ²",
+ "OVERLAP {count} cams": "ПЕРЕКРЫТИЕ {count} кам.",
+ "ISOLATED VIEW": "ИЗОЛИРОВАННЫЙ ВИД",
+ "PROJ MONITOR": "ПРОЕКЦ. МОНИТОР",
+ "PROJ OFF": "ПРОЕКЦ. ВЫКЛ.",
+ "VIEWSHED": "ЗОНА ВИДИМОСТИ",
+ "CAL {value}": "КАЛИБР. {value}",
+ "SRC {value}": "ИСТ. {value}",
+ "{value} CONTEXT": "КОНТЕКСТ {value}",
+ "Focus fire detection {title}, {details}": "Фокус на очаге пожара {title}, {details}",
+ "{value} conf": "увер.: {value}",
+ "{value} ago": "{value} назад",
+ "sensor n/a": "сенсор н/д",
+ "FIRE · {frp} MW": "ПОЖАР · {frp} МВт",
+ "NIGHT": "НОЧЬ",
+ "▲ {frp} MW": "▲ {frp} МВт",
+ "FIRE": "ПОЖАР",
+ "FIRES": "ПОЖ.",
+ "max {value} MW": "макс. {value} МВт",
+ "new {value}": "последний {value}",
+ "just now": "только что",
+ "<1m ago": "<1 мин назад",
+ "{count}m ago": "{count} мин назад",
+ "{count}h ago": "{count} ч назад",
+ "STALE · cached {age}": "УСТАРЕЛ · кэш {age}",
+ "STALE": "УСТАРЕЛ",
+ "refreshing...": "обновление...",
+ "loading...": "загрузка...",
+ "KEY REQUIRED": "ТРЕБУЕТСЯ КЛЮЧ",
+ "LIVE · updated {age}": "ОНЛАЙН · обновлено {age}",
+ "Retrying mapped sites…": "Повторный запрос объектов…",
+ "Fetching mapped sites…": "Загрузка объектов…",
+ "Zoom in to search mapped installations": "Приблизьте, чтобы искать картографированные объекты",
+ "Showing cached mapped sites": "Показаны объекты из кэша",
+ "Mapped sites not loaded": "Объекты не загружены",
+ "Mapped sites loaded": "Объекты загружены",
+ "Overpass rate-limited": "Overpass: превышен лимит запросов",
+ "Overpass timed out": "Overpass: истекло время ожидания",
+ "Overpass could not complete the query": "Overpass не смог завершить запрос",
+ "Overpass temporarily unavailable": "Overpass временно недоступен",
+ "loading mapped installation context": "загрузка контекста объектов",
+ "{reason} — retrying in {seconds}s": "{reason} — повтор через {seconds} с",
+ "{reason} — retry pending": "{reason} — ожидается повтор",
+ "MAPPED INSTALLATION": "КАРТОГРАФИРОВАННЫЙ ОБЪЕКТ",
+ "LAUNCH SITE · {site}": "МЕСТО ПУСКА · {site}",
+ "LAUNCH SITE": "МЕСТО ПУСКА",
+ "T−{time} · {mission}": "T−{time} · {mission}",
+ "LAUNCH STANDBY": "ОЖИДАНИЕ ПУСКА",
+ "LIFTOFF · {mission}": "СТАРТ · {mission}",
+ "ASCENT REPLAY · {mission}": "ПОВТОР ВЫВЕДЕНИЯ · {mission}",
+ "ASCENT ESTIMATE · {mission}": "РАСЧЁТНОЕ ВЫВЕДЕНИЕ · {mission}",
+ "STAGE RE-ENTRY / RECOVERY · {mission}": "ВХОД В АТМОСФЕРУ / ВОЗВРАТ СТУПЕНИ · {mission}",
+ "ORBIT REPLAY · {mission}": "ПОВТОР ОРБИТЫ · {mission}",
+ "PAUSED · {title}": "ПАУЗА · {title}",
+ "UNSPECIFIED": "НЕ УКАЗАНО",
+ "UNAVAILABLE": "НЕДОСТУПНО",
+ "+{count} additional payload records": "+{count} доп. записи о полезной нагрузке",
+ "PAYLOAD DATA UNAVAILABLE": "ДАННЫЕ ПОЛЕЗНОЙ НАГРУЗКИ НЕДОСТУПНЫ",
+ "{value} KM DOWNRANGE": "{value} КМ ПО ТРАССЕ",
+ "POSITION UNAVAILABLE": "ПОЗИЦИЯ НЕДОСТУПНА",
+ "FLIGHT {count}": "ПОЛЁТ {count}",
+ "REUSED": "ЛЕТАВШАЯ",
+ "NO STAGE RE-ENTRY / RECOVERY DATA": "НЕТ ДАННЫХ О ВХОДЕ В АТМОСФЕРУ / ВОЗВРАТЕ СТУПЕНИ",
+ "{count} / 30D": "{count} / 30 ДН.",
+ "NO MISSIONS AVAILABLE IN THE CURRENT 30-DAY WINDOW": "НЕТ МИССИЙ В ТЕКУЩЕМ 30-ДНЕВНОМ ОКНЕ",
+ "DATE UNAVAILABLE": "ДАТА НЕДОСТУПНА",
+ "UNSPECIFIED OPERATOR": "ОПЕРАТОР НЕ УКАЗАН",
+ "Select {mission}": "Выбрать {mission}",
+ "{value} KM": "{value} КМ",
+ "{value} KM/S": "{value} КМ/С",
+ "SELECTED SPACE MISSION": "ВЫБРАННАЯ КОСМИЧЕСКАЯ МИССИЯ",
+ "Show all missions": "Показать все миссии",
+ "Deselect mission": "Снять выбор миссии",
+ "MISSION": "МИССИЯ",
+ "STATUS · ": "СТАТУС · ",
+ "LAUNCH SITE · ": "МЕСТО ПУСКА · ",
+ "LAUNCH TIME · ": "ВРЕМЯ ПУСКА · ",
+ "ORBIT · ": "ОРБИТА · ",
+ "ASCENT PATH · ": "ТРАЕКТОРИЯ ВЫВЕДЕНИЯ · ",
+ "CURRENT DISTANCE FROM EARTH · ": "ТЕКУЩЕЕ РАССТОЯНИЕ ОТ ЗЕМЛИ · ",
+ "SATELLITE SPEED · ": "СКОРОСТЬ СПУТНИКА · ",
+ "PAYLOAD": "ПОЛЕЗНАЯ НАГРУЗКА",
+ "NAME": "НАЗВАНИЕ",
+ "TYPE": "ТИП",
+ "DESTINATION": "ПУНКТ НАЗНАЧЕНИЯ",
+ "STAGE / RE-ENTRY / RECOVERY": "СТУПЕНЬ / ВХОД В АТМОСФЕРУ / ВОЗВРАТ",
+ "STAGE": "СТУПЕНЬ",
+ "STATUS": "СТАТУС",
+ "FINAL POSITION": "КОНЕЧНОЕ ПОЛОЖЕНИЕ",
+ "REPLAY SPEED": "СКОРОСТЬ ПОВТОРА",
+ "Replay speed multiplier": "Множитель скорости повтора",
+ "REPLAY ASCENT": "ПОВТОРИТЬ ВЫВЕДЕНИЕ",
+ "Previous mission": "Предыдущая миссия",
+ "PREV": "ПРЕД.",
+ "Next mission": "Следующая миссия",
+ "SHOW ALL / DESELECT": "ПОКАЗАТЬ ВСЕ / СНЯТЬ ВЫБОР",
+ "Pause replay": "Приостановить повтор",
+ "Cancel replay": "Отменить повтор",
+ "EST. DOWNRANGE": "РАСЧЁТ ПО ТРАССЕ",
+ "PLANNED · ": "ПЛАН · ",
+ "SUPPLIED TRAJECTORY POINTS": "ПРЕДОСТАВЛЕННЫЕ ТОЧКИ ТРАЕКТОРИИ",
+ "RECONSTRUCTED ESTIMATE": "РЕКОНСТРУИРОВАННАЯ ОЦЕНКА",
+ "Replay the estimated ascent with a following camera": "Повторить расчётное выведение с камерой сопровождения",
+ "Resume replay": "Возобновить повтор",
+ "T minus {seconds}": "T минус {seconds}",
+ "Preparing launch site": "Подготовка стартовой площадки",
+ "Liftoff": "Старт",
+ "Ascent replay": "Повтор выведения",
+ "Orbit replay": "Повтор: орбита",
+ ", paused": ", пауза",
+ "Alt unknown": "Высота неизвестна",
+ "Type unknown": "Тип неизвестен",
+ "Reg unknown": "Рег. номер неизвестен",
+ "Operator unknown": "Оператор неизвестен",
+ "All": "Все",
+ "News": "Новости",
+ "Talk": "Разговорное",
+ "Weather / Emergency": "Погода / ЧС",
+ "Public Safety": "Общественная безопасность",
+ "Aviation / Marine": "Авиация / Море",
+ "Traffic / Transit": "Трафик / Транспорт",
+ "Music": "Музыка",
+ "Other": "Другое",
+ "Add the full Starlink broadband shell (thousands of extra points)": "Добавить полную широкополосную оболочку Starlink (тысячи дополнительных точек)",
+ "Loading the Starlink shell…": "Загрузка оболочки Starlink…",
+ "Starlink {detail} — click to retry": "Starlink: {detail} — нажмите, чтобы повторить",
+ "load failed": "ошибка загрузки",
+ "Showing the full Starlink shell — click for the core catalog only": "Показана полная оболочка Starlink — нажмите, чтобы оставить только основной каталог",
+ "DENSE ···": "ПЛОТНО ···",
+ "DENSE ✕": "ПЛОТНО ✕",
+ "DENSE": "ПЛОТНЫЙ",
+ "Syncing flow · Roads: {source}": "Синхронизация потока · Дороги: {source}",
+ "LIVE · Roads: {source} · Roads without flow hidden": "ОНЛАЙН · Дороги: {source} · Дороги без потока скрыты",
+ "LIVE · Roads: {source} · No flow roads in view": "ОНЛАЙН · Дороги: {source} · В кадре нет дорог с потоком",
+ "LIVE · Roads: {source} · Flow {percent}%": "ОНЛАЙН · Дороги: {source} · Поток {percent}%",
+ "SIMULATED · Roads: {source} · Flow {percent}%": "СИМУЛЯЦИЯ · Дороги: {source} · Поток {percent}%",
+ "Syncing flow · Roads: OpenStreetMap · Flow: TomTom · Unmatched: simulated": "Синхронизация потока · Дороги: OpenStreetMap · Поток: TomTom · Без совпадений: симуляция",
+ "LIVE · Roads: OpenStreetMap · Flow: TomTom · {percent}% cov · Unmatched: simulated": "ОНЛАЙН · Дороги: OpenStreetMap · Поток: TomTom · охват {percent}% · Без совпадений: симуляция",
+ "LIVE · Roads: OpenStreetMap · Flow: TomTom · {percent}% cov": "ОНЛАЙН · Дороги: OpenStreetMap · Поток: TomTom · охват {percent}%",
+ "SIMULATED · Roads: OpenStreetMap · Flow: TomTom (no matches)": "СИМУЛЯЦИЯ · Дороги: OpenStreetMap · Поток: TomTom (нет совпадений)",
+ "SIMULATED — traffic service unreachable": "СИМУЛЯЦИЯ — сервис трафика недоступен",
+ "SIMULATED — add TomTom key for live": "СИМУЛЯЦИЯ — добавьте ключ TomTom для режима онлайн",
+ "POS: LIVE": "ПОЗ: ОНЛАЙН",
+ "POS: {time}Z": "ПОЗ: {time}Z",
+ "AIS: {name}": "AIS: {name}",
+ "{type} SPD: {speed} HDG: {heading}": "{type} СКОР: {speed} КУРС: {heading}",
+ "VESSEL": "СУДНО",
+ "AIS: --": "AIS: --",
+ "awaiting first AIS position…": "ожидание первой позиции AIS…",
+ "awaiting usable AIS positions…": "ожидание пригодных позиций AIS…",
+ "awaiting first AIS message…": "ожидание первого сообщения AIS…",
+ "{label} unavailable: {hint}": "{label}: недоступно — {hint}",
+ "Needs {envVars} — add it in Provider Settings": "Нужен {envVars} — добавьте его в «Настройках провайдеров»",
+ "{label} is unavailable": "{label}: недоступно",
+ "This map stack": "Этот набор карт",
+ "Updated: {scene} / {shot}": "Обновлено: {scene} / {shot}",
+ "Camera unavailable — exit cockpit first": "Камера недоступна — сначала выйдите из кабины",
+ "No shots to run": "Нет кадров для воспроизведения",
+ "Error: {message}": "Ошибка: {message}",
+ "Project exported": "Проект экспортирован",
+ "Ready": "Готово",
+ "Could not exit {mode} — scene layers may be refused": "Не удалось выйти из режима {mode} — слои сцены могут быть отклонены",
+ "Loaded: {scene} / {shot}": "Загружено: {scene} / {shot}",
+ "Global Flights Radar": "Глобальный радар рейсов",
+ "Orbital Watch": "Орбитальный дозор",
+ "Thermal Threat Board": "Панель тепловых угроз",
+ "City Overload": "Перегрузка города",
+ "Omniscience Pullback": "Отъезд к всевидению",
+ "Cannot capture shot: camera not ready": "Не удалось сделать кадр: камера не готова",
+ "Shot {n}": "Кадр {n}",
+ "Captured: {scene} / {shot}": "Снято: {scene} / {shot}",
+ "Select a shot first": "Сначала выберите кадр",
+ "Running {index}/{total}: {scene} / {shot}": "Воспроизведение {index}/{total}: {scene} / {shot}",
+ "Scene run complete": "Воспроизведение сцены завершено",
+ "CCTV layer unavailable": "Слой CCTV недоступен",
+ "Link copied!": "Ссылка скопирована!",
+ "Copy failed": "Не удалось скопировать",
+ "VISUAL PRESETS": "ПРЕСЕТЫ",
+ "LOCATION": "МЕСТО",
+ "DISPLAY": "ЭКРАН",
+ "CONTACT": "КОНТАКТ",
+ "CONTACTS — nearest planes · vessels · sites": "КОНТАКТЫ — ближайшие самолёты · суда · объекты",
+ "SPACE MISSIONS — launches & orbital assets": "КОСМИЧЕСКИЕ МИССИИ — пуски и орбитальные аппараты",
+ "LIVE SIGNALS": "СИГНАЛЫ ОНЛАЙН",
+ "MAP SOURCE": "ИСТОЧНИК КАРТЫ",
+ "Map source": "Источник карты",
+ "CCTV calibration saved": "Калибровка CCTV сохранена",
+ "ADJUST ON": "НАСТРОЙКА ВКЛ",
+ "ADJUST": "НАСТРОЙКА",
+ "CCTV calibration reset": "Калибровка CCTV сброшена",
+ "FRAME · UNAVAILABLE": "КАДР · НЕДОСТУПЕН",
+ "SOURCE · UNKNOWN": "ИСТОЧНИК · НЕИЗВЕСТЕН",
+ "FRAME · LOADING": "КАДР · ЗАГРУЗКА",
+ "VIEWSHED ON": "ВИДИМОСТЬ ВКЛ",
+ "COVERAGE ON": "ОХВАТ ВКЛ",
+ "COVERAGE OFF": "ОХВАТ ВЫКЛ",
+ "RAW PRIOR": "ИСХОДНАЯ ОЦЕНКА",
+ "AUTO HOP ON": "АВТОСМЕНА ВКЛ",
+ "AUTO HOP OFF": "АВТОСМЕНА ВЫКЛ",
+ "PROJECTION ON": "ПРОЕКЦИЯ ВКЛ",
+ "PROJECTION OFF": "ПРОЕКЦИЯ ВЫКЛ",
+ "CAL · EDITED (UNSAVED)": "КАЛИБР. · ИЗМЕНЕНО (НЕ СОХР.)",
+ "CAL · {badge}": "КАЛИБР. · {badge}",
+ "MONITOR": "МОНИТОР",
+ "OFF": "ВЫКЛ",
+ "{city} · HDG {heading} · FOV {fov} · RANGE {range}m · {projection}{calBadge} · {provider}{status}": "{city} · КУРС {heading} · ОБЗОР {fov} · ДАЛЬН. {range} м · {projection}{calBadge} · {provider}{status}",
+ "{count} cameras loaded · click a camera to activate": {
+ "one": "Загружена {count} камера · щёлкните по камере, чтобы активировать",
+ "few": "Загружено {count} камеры · щёлкните по камере, чтобы активировать",
+ "many": "Загружено {count} камер · щёлкните по камере, чтобы активировать",
+ "other": "Загружено {count} камеры · щёлкните по камере, чтобы активировать"
+ },
+ "{count} cameras loaded · enable CCTV to activate": {
+ "one": "Загружена {count} камера · включите CCTV, чтобы активировать",
+ "few": "Загружено {count} камеры · включите CCTV, чтобы активировать",
+ "many": "Загружено {count} камер · включите CCTV, чтобы активировать",
+ "other": "Загружено {count} камеры · включите CCTV, чтобы активировать"
+ },
+ "Enable CCTV to load camera intersections": "Включите CCTV, чтобы загрузить камеры на перекрёстках",
+ "Enable CCTV to start camera-linked intelligence summaries.": "Включите CCTV, чтобы запускать сводки по камерам.",
+ "No summary available.": "Сводка недоступна.",
+ "loading frames": "загрузка кадров",
+ "camera grid ready": "сетка камер готова",
+ "CCTV ON": "CCTV ВКЛ",
+ "CCTV OFF": "CCTV ВЫКЛ",
+ "CALIBRATED": "ОТКАЛИБРОВАНО",
+ "CURATED": "ВЫВЕРЕНО",
+ "Clearing selected data layers": "Очистка выбранных слоёв данных",
+ "Clear selected data layers": "Очистить выбранные слои данных",
+ "CONDITIONS UNKNOWN": "УСЛОВИЯ НЕИЗВЕСТНЫ",
+ "CLEAR": "ЯСНО",
+ "PARTLY CLOUDY": "ПЕРЕМЕННАЯ ОБЛАЧНОСТЬ",
+ "OVERCAST": "ПАСМУРНО",
+ "ACQUIRING REGIONAL NEWS": "ЗАГРУЗКА РЕГИОНАЛЬНЫХ НОВОСТЕЙ",
+ "REGIONAL NEWS UNAVAILABLE": "РЕГИОНАЛЬНЫЕ НОВОСТИ НЕДОСТУПНЫ",
+ "RESOLVING REGION": "ОПРЕДЕЛЕНИЕ РЕГИОНА",
+ "REGION UNAVAILABLE": "РЕГИОН НЕДОСТУПЕН",
+ "FOG": "ТУМАН",
+ "NO RECENT LOCATION MATCHES": "НЕТ СВЕЖИХ СОВПАДЕНИЙ ПО МЕСТУ",
+ "DRIZZLE": "МОРОСЬ",
+ "RAIN": "ДОЖДЬ",
+ "{domain} · {age}": "{domain} · {age}",
+ "SOURCE": "ИСТОЧНИК",
+ "SNOW": "СНЕГ",
+ "RAIN SHOWERS": "ЛИВНИ",
+ "SNOW SHOWERS": "ЛИВНЕВЫЙ СНЕГ",
+ "THUNDERSTORM": "ГРОЗА",
+ "CLOUD {pct}%": "ОБЛАЧНОСТЬ {pct}%",
+ "CLOUD UNKNOWN": "ОБЛАЧНОСТЬ НЕИЗВЕСТНА",
+ "MIXED CONDITIONS": "СМЕШАННЫЕ УСЛОВИЯ",
+ "{source} · LOCATION QUERY": "{source} · ЗАПРОС ПО МЕСТУ",
+ "REGIONAL NEWS": "НОВОСТИ РЕГИОНА",
+ "CYCLE ON": "АВТО: ВКЛ",
+ "CYCLE OFF": "АВТО: ВЫКЛ",
+ "Stop automatic page cycling. Previous, Next, and the SIG/NEWS/LOCAL tabs stay available.": "Остановить автоматическое листание страниц. Кнопки ПРЕД./СЛЕД. и вкладки СИГН./НОВОСТИ/МЕСТН. остаются доступны.",
+ "Cycle briefing pages automatically every 9 seconds (Signals → News → Local). Pauses while you hover or focus the panel. Live signal data refreshes continuously either way.": "Автоматически листать страницы брифинга каждые 9 секунд (Сигналы → Новости → Местное). При наведении или фокусе на панели листание приостанавливается. Данные сигналов в реальном времени в любом случае обновляются непрерывно.",
+ "{cohort}, Unavailable": "{cohort}, недоступно",
+ "AHEAD": "ПО КУРСУ",
+ "{side} {angle}": "{side} {angle}",
+ "L": "Л",
+ "R": "П",
+ "{count} INPUTS UNKNOWN · NOT AN ALL-CLEAR": {
+ "one": "{count} ИСТОЧНИК ДАННЫХ НЕИЗВЕСТЕН · ОТСУТСТВИЕ УГРОЗ НЕ ПОДТВЕРЖДЕНО",
+ "few": "{count} ИСТОЧНИКА ДАННЫХ НЕИЗВЕСТНЫ · ОТСУТСТВИЕ УГРОЗ НЕ ПОДТВЕРЖДЕНО",
+ "many": "{count} ИСТОЧНИКОВ ДАННЫХ НЕИЗВЕСТНО · ОТСУТСТВИЕ УГРОЗ НЕ ПОДТВЕРЖДЕНО",
+ "other": "{count} ИСТОЧНИКА ДАННЫХ НЕИЗВЕСТНО · ОТСУТСТВИЕ УГРОЗ НЕ ПОДТВЕРЖДЕНО"
+ },
+ "AVAILABLE INPUTS CURRENT · NOT AN ALL-CLEAR": "ДОСТУПНЫЕ ДАННЫЕ АКТУАЛЬНЫ · ОТСУТСТВИЕ УГРОЗ НЕ ПОДТВЕРЖДЕНО",
+ "CONTEXT STANDBY": "КОНТЕКСТ В ОЖИДАНИИ",
+ "ENABLE GLOBAL CONTEXT FOR PROXIMITY PINGS": "ВКЛЮЧИТЕ ГЛОБАЛЬНЫЙ КОНТЕКСТ ДЛЯ ПИНГОВ ПОБЛИЗОСТИ",
+ "CONTACT LOST · LAST KNOWN READOUT · NOT AN ALL-CLEAR": "КОНТАКТ ПОТЕРЯН · ПОСЛЕДНИЕ ИЗВЕСТНЫЕ ДАННЫЕ · ОТСУТСТВИЕ УГРОЗ НЕ ПОДТВЕРЖДЕНО",
+ "CONTACT LOST · {subject}": "КОНТАКТ ПОТЕРЯН · {subject}",
+ "SUBJECT LEFT ITS FEED · READOUT HOLDING LAST KNOWN": "ОБЪЕКТ ВЫПАЛ ИЗ ПОТОКА · ПОКАЗАНЫ ПОСЛЕДНИЕ ДАННЫЕ",
+ "{cohort} · {contact}": "{cohort} · {contact}",
+ "NO AVAILABLE EXAMPLE": "НЕТ ДОСТУПНОГО ПРИМЕРА",
+ "ACQUIRING SURFACE": "ЗАХВАТ ПОВЕРХНОСТИ",
+ "SURFACE FALLBACK": "РЕЗЕРВНАЯ ПОВЕРХНОСТЬ",
+ "STALE FEED": "ПОТОК УСТАРЕЛ",
+ "LIVE TRACK": "ТРЕК ОНЛАЙН",
+ "{aircraftClass} · {feedState} · COURSE ALIGNED": "{aircraftClass} · {feedState} · КУРС СОВМЕЩЁН",
+ "COMMERCIAL": "ГРАЖДАНСКИЙ",
+ "UNKNOWN": "НЕИЗВЕСТНО",
+ "ARROW · ESTIMATED DIRECTION": "СТРЕЛКА · РАСЧЁТНОЕ НАПРАВЛЕНИЕ",
+ "ROUTE DATA UNAVAILABLE": "ДАННЫЕ МАРШРУТА НЕДОСТУПНЫ",
+ "DEST {bearing}": "НАЗН. {bearing}",
+ "Disable cockpit weather effects": "Выключить погодные эффекты кабины",
+ "Enable cockpit weather effects": "Включить погодные эффекты кабины",
+ "ON": "ВКЛ",
+ "Night vision": "Ночное видение",
+ "Thermal": "Тепловизор",
+ "Anime": "Аниме",
+ "Noir": "Нуар",
+ "Snow": "Снег",
+ "Current cockpit vision style: {style}. Activate for next style.": "Текущий стиль обзора кабины: {style}. Активируйте, чтобы переключить на следующий.",
+ "Current style: {style} — click for next": "Текущий стиль: {style} — нажмите для следующего",
+ "AIRCRAFT": "САМОЛЁТ",
+ "Expand Contact panel": "Развернуть панель контактов",
+ "Collapse Contact panel": "Свернуть панель контактов",
+ "Expand contact panel": "Развернуть панель контактов",
+ "Collapse contact panel": "Свернуть панель контактов",
+ "Collapse cockpit briefing panel": "Свернуть панель брифинга кабины",
+ "Expand cockpit briefing panel": "Развернуть панель брифинга кабины",
+ "Collapse briefing panel": "Свернуть панель брифинга",
+ "Expand briefing panel": "Развернуть панель брифинга",
+ "OBSERVED / MAPPED PINGS": "НАБЛЮДАЕМЫЕ / НАНЕСЁННЫЕ ПИНГИ",
+ "SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS": "СОБЫТИЯ ИЗ ИСТОЧНИКОВ · БЕЗ ВЫМЫСЛА",
+ "LATEST LOCATION-MATCHED REPORTING": "СВЕЖИЕ НОВОСТИ ПО МЕСТУ",
+ "LOCAL INFO": "МЕСТНЫЕ ДАННЫЕ",
+ "PLACE / CONDITIONS / POSITION": "МЕСТО / ПОГОДА / КООРД.",
+ "TIME UNKNOWN": "ВРЕМЯ НЕИЗВЕСТНО",
+ "{count}M AGO": "{count} МИН НАЗАД",
+ "{count}H AGO": "{count} Ч НАЗАД",
+ "{count}D AGO": "{count} ДН. НАЗАД",
+ "DIR UNKNOWN": "НАПР. НЕИЗВЕСТНО",
+ "{aircraftClass} · CURRENT": "{aircraftClass} · ТЕКУЩИЙ",
+ "MILITARY FLIGHT": "ВОЕННЫЙ РЕЙС",
+ "COMMERCIAL FLIGHT": "ГРАЖДАНСКИЙ РЕЙС",
+ "{aircraftClass} · {distance}": "{aircraftClass} · {distance}",
+ "DISTANCE UNKNOWN": "ДИСТАНЦИЯ НЕИЗВЕСТНА",
+ "{count} INPUTS UNKNOWN": {
+ "one": "{count} ИСТОЧНИК ДАННЫХ НЕИЗВЕСТЕН",
+ "few": "{count} ИСТОЧНИКА ДАННЫХ НЕИЗВЕСТНЫ",
+ "many": "{count} ИСТОЧНИКОВ ДАННЫХ НЕИЗВЕСТНО",
+ "other": "{count} ИСТОЧНИКА ДАННЫХ НЕИЗВЕСТНО"
+ },
+ "SOURCE STATUS UNAVAILABLE": "СТАТУС ИСТОЧНИКА НЕДОСТУПЕН",
+ "Select flight {title}": "Выбрать рейс {title}",
+ "TRACK ACQUIRED": "ЦЕЛЬ ЗАХВАЧЕНА",
+ "{label} · COURSE {heading}°": "{label} · КУРС {heading}°",
+ "Restore real aircraft": "Вернуть реальный самолёт",
+ "Reclassify as TR-3B": "Переклассифицировать как TR-3B",
+ "No selected data layers": "Нет выбранных слоёв данных",
+ "{count} data layers could not be cleared": {
+ "one": "Не удалось очистить {count} слой данных",
+ "few": "Не удалось очистить {count} слоя данных",
+ "many": "Не удалось очистить {count} слоёв данных",
+ "other": "Не удалось очистить {count} слоя данных"
+ },
+ "Cleared {count} data layers": {
+ "one": "Очищен {count} слой данных",
+ "few": "Очищено {count} слоя данных",
+ "many": "Очищено {count} слоёв данных",
+ "other": "Очищено {count} слоя данных"
+ },
+ "Selected data layers could not be cleared": "Не удалось очистить выбранные слои данных",
+ "Context could not restore every layer; try again": "Контекст: не удалось восстановить все слои; попробуйте снова",
+ "Nearby installations refreshed": "Ближайшие объекты обновлены",
+ "Nearby installations could not be refreshed; try again": "Не удалось обновить ближайшие объекты; попробуйте снова",
+ "Contacts could not complete the requested transition; try again": "Не удалось переключить режим «Контакты»; попробуйте снова",
+ "Space Missions could not complete the requested transition; try again": "Не удалось переключить режим «Космические миссии»; попробуйте снова",
+ "{layerId} could not {action} cleanly": "Не удалось корректно {action} слой {layerId}",
+ "start": "запустить",
+ "stop": "остановить",
+ "Space Missions cancellation could not restore the previous layer state": "Не удалось восстановить прежнее состояние слоёв после отмены космических миссий",
+ "That layer is unavailable in the current Context mode": "Этот слой недоступен в текущем режиме контекста",
+ "{mode} could not start because another layer did not stop cleanly": "Не удалось запустить режим «{mode}»: другой слой не остановился корректно",
+ "Space Missions": "Космические миссии",
+ "Context": "Контекст",
+ "LOADING": "ЗАГРУЗКА",
+ "DEGRADED": "ПЕРЕБОИ",
+ "PARTIAL": "ЧАСТИЧНО",
+ "FALLBACK": "РЕЗЕРВ",
+ "Live Flights": "Рейсы онлайн",
+ "Military Flights": "Военные рейсы",
+ "Earthquakes (24h)": "Землетрясения (24 ч)",
+ "Satellites": "Спутники",
+ "Space Missions (30d)": "Космические миссии (30 дн.)",
+ "Street Traffic": "Дорожный трафик",
+ "CCTV": "CCTV",
+ "Radio": "Радио",
+ "Bikeshare": "Велошеринг",
+ "Live AIS Vessels": "Суда AIS онлайн",
+ "Mapped Installations": "Объекты на карте",
+ "Global Context": "Глобальный контекст",
+ "Datacenters": "Дата-центры",
+ "Dams": "Плотины",
+ "Submarine Cables": "Подводные кабели",
+ "FIRMS Active Fires": "Активные пожары FIRMS",
+ "ENABLING": "ВКЛЮЧЕНИЕ",
+ "DISABLING": "ВЫКЛЮЧЕНИЕ",
+ "{state} · {source}": "{state} · {source}",
+ "UNCERTAIN · {source} · lifecycle state requires reconciliation": "НЕОПРЕД. · {source} · требуется сверка состояния",
+ "{state} · {source} · {detail} · retry {seconds}s": "{state} · {source} · {detail} · повтор через {seconds} с",
+ "{state} · {source} · {detail}": "{state} · {source} · {detail}",
+ "never": "не обновлялось",
+ "{source} · {loadingLabel}": "{source} · {loadingLabel}",
+ "{accepted} of {raw} records accepted": "принято записей: {accepted} из {raw}",
+ "incomplete snapshot": "неполный снимок",
+ "{state} · {source} · {detail} · {ago}": "{state} · {source} · {detail} · {ago}",
+ "{state} · {source} · {ago} · retrying in {seconds}s": "{state} · {source} · {ago} · повтор через {seconds} с",
+ "{state} · {source} · {ago}": "{state} · {source} · {ago}",
+ "{source} · {ago}": "{source} · {ago}",
+ "UNCERTAIN": "НЕОПРЕД.",
+ "Data source unavailable": "Источник данных недоступен",
+ "{name}: {state}": "{name}: {state}",
+ "{count}s ago": "{count} с назад",
+ "📍 Location: --": "📍 Место: --",
+ "Landmark: --": "Ориентир: --",
+ "Searched location": "Найденное место",
+ "ORBIT": "ОРБИТА",
+ "Fly to a POI first": "Сначала перелетите к точке интереса",
+ "Reset to full globe view": "Сбросить к виду всего глобуса",
+ "Reset cockpit to full globe view": "Сбросить кабину к виду всего глобуса",
+ "Resetting to full globe view": "Сброс к виду всего глобуса",
+ "Resetting cockpit to full globe view": "Сброс кабины к виду всего глобуса",
+ "Location not found": "Место не найдено",
+ "Search failed": "Не удалось выполнить поиск",
+ "MAP": "КАРТА",
+ "panel": "панель",
+ "Expand {name}": "Развернуть {name}",
+ "Collapse {name}": "Свернуть {name}",
+ "Expand Radio": "Развернуть радио",
+ "Collapse Radio": "Свернуть радио",
+ "Expand Radio section": "Развернуть раздел радио",
+ "Collapse Radio section": "Свернуть раздел радио",
+ "Panel layout updated — positions reset to new defaults": "Макет панелей обновлён — позиции сброшены к новым значениям по умолчанию",
+ "NO STATIONS": "НЕТ СТАНЦИЙ",
+ "NO STATION AVAILABLE": "НЕТ ДОСТУПНЫХ СТАНЦИЙ",
+ "{name}, station {index} of {total}": "{name}, станция {index} из {total}",
+ "No station available": "Нет доступной станции",
+ "OFF AIR": "НЕ В ЭФИРЕ",
+ "STATION UNAVAILABLE": "СТАНЦИЯ НЕДОСТУПНА",
+ "Radio could not {action} cleanly": "Не удалось корректно {action} радио",
+ "Collapse Cockpit display options": "Свернуть параметры экрана кабины",
+ "Expand Cockpit display options": "Развернуть параметры экрана кабины",
+ "Collapse Cockpit Radio controls": "Свернуть управление радио кабины",
+ "Expand Cockpit Radio controls": "Развернуть управление радио кабины",
+ "Close compact Radio controls": "Закрыть компактное управление радио",
+ "Open compact Radio controls": "Открыть компактное управление радио",
+ "DIRECTORY BAND": "ДИАПАЗОН КАТАЛОГА",
+ "{category} BAND": "ДИАПАЗОН {category}",
+ "NO STATION SELECTED": "СТАНЦИЯ НЕ ВЫБРАНА",
+ "Directory metadata only": "Только метаданные каталога",
+ "Loading station directory…": "Загрузка каталога станций…",
+ "Choose a globe marker or use next.": "Выберите маркер на глобусе или нажмите «След.».",
+ "TAGS · {tags}": "ТЕГИ · {tags}",
+ "Pause": "Приостановить",
+ "Resume": "Продолжить",
+ "Play": "Воспроизвести",
+ "selected": "выбранную",
+ "nearest": "ближайшую",
+ "{action} {target} radio station": "{action} {target} радиостанцию",
+ "RADIO STATE UNCERTAIN": "СОСТОЯНИЕ РАДИО НЕОПРЕДЕЛЁННО",
+ "SYNCING DIRECTORY": "СИНХРОНИЗАЦИЯ КАТАЛОГА",
+ "RADIO READY": "РАДИО ГОТОВО",
+ "SYNCING": "СИНХРОНИЗАЦИЯ",
+ "READY": "ГОТОВО",
+ "station": "станция",
+ " · stale/degraded directory": " · каталог устарел/с перебоями",
+ " · degraded directory": " · каталог с перебоями",
+ " · stale directory": " · каталог устарел",
+ " · outside current filter": " · вне текущего фильтра",
+ "Ready — playback starts only from your action": "Готово — воспроизведение начнётся только по вашей команде",
+ "Radio off": "Радио выключено",
+ "Connecting directly to broadcaster…": "Прямое подключение к вещателю…",
+ "Buffering broadcaster stream…": "Буферизация потока вещателя…",
+ "Playing {station}": "Играет {station}",
+ "Paused {station}": "{station} на паузе",
+ "Broadcaster stream unavailable": "Поток вещателя недоступен",
+ " · muted during voice interaction": " · приглушено во время голосовой сессии",
+ " · restoring volume after voice": " · восстановление громкости после голосовой сессии",
+ " · static indicates no broadcaster audio": " · шум означает отсутствие аудио вещателя",
+ " · tuning static until broadcaster starts": " · шум настройки, пока не начнётся вещание",
+ "Station unavailable after directory refresh — choose another channel": "Станция недоступна после обновления каталога — выберите другой канал",
+ "Radio is enabling…": "Радио включается…",
+ "Radio is disabling…": "Радио выключается…",
+ "Radio lifecycle is uncertain — use Enable or Disable to reconcile": "Состояние радио не определено — нажмите «Включить» или «Выключить» для сверки",
+ "SYNC": "СИНХР.",
+ "RECONCILE": "СВЕРИТЬ",
+ "DISABLE": "ВЫКЛЮЧИТЬ",
+ "ENABLE": "ВКЛЮЧИТЬ",
+ "Reconcile Radio — lifecycle uncertain": "Сверить радио — состояние не определено",
+ "Disable Radio": "Выключить радио",
+ "Enable Radio": "Включить радио",
+ "Scene action failed": "Не удалось выполнить действие со сценой",
+ "Delete shot \"{shot}\"?": "Удалить кадр «{shot}»?",
+ "ACQUIRING": "ЗАХВАТ",
+ "SHARED {subject}": "ПО ССЫЛКЕ: {subject}",
+ "entity": "объект",
+ "Shared {subject} follow expired": "Срок отслеживания {subject} по ссылке истёк",
+ "Shared {subject} could not be restored — feed unavailable": "Не удалось восстановить {subject} по ссылке — поток данных недоступен",
+ "Shared {subject} is unavailable": "{subject} по ссылке недоступен",
+ "LOADING LIVE DATA": "ЗАГРУЗКА ОНЛАЙН-ДАННЫХ",
+ "LOAD COMPLETE": "ЗАГРУЗКА ЗАВЕРШЕНА",
+ "LOAD CANCELLED": "ЗАГРУЗКА ОТМЕНЕНА",
+ "LOAD FAILED": "ОШИБКА ЗАГРУЗКИ",
+ "LIVE DATA OFF": "ОНЛАЙН-ДАННЫЕ ВЫКЛ.",
+ "MAPPED SITES LOADED": "ОБЪЕКТЫ ЗАГРУЖЕНЫ",
+ "RETRYING MAPPED SITES": "ПОВТОРНАЯ ЗАГРУЗКА ОБЪЕКТОВ",
+ "FETCHING MAPPED SITES": "ЗАГРУЗКА ОБЪЕКТОВ",
+ "TURNING OFF LIVE DATA": "ОТКЛЮЧЕНИЕ ОНЛАЙН-ДАННЫХ",
+ "REFRESHING LIVE DATA": "ОБНОВЛЕНИЕ ОНЛАЙН-ДАННЫХ",
+ "syncing road network": "синхронизация дорожной сети",
+ "retrying in {seconds}s": "повтор через {seconds} с",
+ "retry pending": "повтор ожидается",
+ "Contact cockpit summary": "Сводка по контакту в кабине",
+ "Cockpit briefing carousel": "Карусель брифингов кабины",
+ "Cockpit display and Radio controls": "Управление экраном и радио кабины",
+ "Previous cockpit vision style": "Предыдущий стиль обзора кабины",
+ "Previous vision style": "Предыдущий стиль обзора",
+ "Current cockpit vision style: NORMAL. Activate for next style.": "Текущий стиль обзора кабины: ОБЫЧНЫЙ. Активируйте для следующего стиля.",
+ "Current style: NORMAL — click for next": "Текущий стиль: ОБЫЧНЫЙ — нажмите для следующего",
+ "Next cockpit vision style": "Следующий стиль обзора кабины",
+ "Next vision style": "Следующий стиль обзора",
+ "Previous briefing page": "Предыдущая страница брифинга",
+ "Next briefing page": "Следующая страница брифинга",
+ "Show Live Signals": "Показать сигналы в реальном времени",
+ "Show Regional News": "Показать региональные новости",
+ "Show Local Info": "Показать местную информацию",
+ "Previous filtered radio station": "Предыдущая отфильтрованная радиостанция",
+ "Play selected radio station": "Воспроизвести выбранную радиостанцию",
+ "Next filtered radio station": "Следующая отфильтрованная радиостанция",
+ "Exit cockpit and return to full globe view": "Выйти из кабины и вернуться к виду всего глобуса",
+ "Exit cockpit view": "Выйти из кабины",
+ "Estimated destination direction": "Расчётное направление на пункт назначения",
+ "OPTICAL PLANE · 01": "ОПТИЧЕСКАЯ ПЛОСКОСТЬ · 01",
+ "VISOR LOCK · ACTIVE": "БЛОКИРОВКА ВИЗОРА · АКТИВНА",
+ "Cockpit vision style": "Стиль обзора кабины",
+ "Current aircraft heading": "Текущий курс самолёта",
+ "Nearby cohort counts": "Счётчики контактов поблизости",
+ "Cockpit display options": "Параметры экрана кабины",
+ "Cockpit compact Radio controls": "Компактное управление радио кабины",
+ "Cockpit Radio volume": "Громкость радио кабины",
+ "Contact navigation": "Навигация по контактам",
+ "Cockpit briefing controls": "Управление брифингом кабины",
+ "View switcher": "Переключатель вида",
+ "Aircraft cockpit view": "Вид кабины самолёта",
+ "Estimated flight plan": "Расчётный план полёта",
+ "Live signals": "Сигналы в реальном времени",
+ "Latest regional news": "Последние региональные новости",
+ "Location-based information": "Информация по текущему месту",
+ "LEVEL": "ГОРИЗОНТ",
+ "DEST ---°": "НАЗН. ---°",
+ "CURRENT": "ТЕКУЩИЙ",
+ "NEAREST OBSERVED / MAPPED": "БЛИЖАЙШИЕ НАБЛЮДАЕМЫЕ / НА КАРТЕ",
+ "GROUND SPEED · KTS": "ПУТЕВАЯ СКОРОСТЬ · УЗ",
+ "ALTITUDE · FT": "ВЫСОТА · ФТ",
+ "FIRST PERSON": "ОТ ПЕРВОГО ЛИЦА",
+ "LIVE TRACK · COURSE ALIGNED": "ТРЕК ОНЛАЙН · КУРС СОВМЕЩЁН",
+ "GROUND SPEED": "ПУТЕВАЯ СКОРОСТЬ",
+ "ALTITUDE": "ВЫСОТА",
+ "CONTEXT ONLY": "ТОЛЬКО КОНТЕКСТ",
+ "AVAILABLE INPUTS ONLY · NOT AN ALL-CLEAR": "ТОЛЬКО ДОСТУПНЫЕ ДАННЫЕ · ОТСУТСТВИЕ УГРОЗ НЕ ПОДТВЕРЖДЕНО",
+ "ESTIMATED FLIGHT PLAN": "РАСЧЁТНЫЙ ПЛАН ПОЛЁТА",
+ "FROM": "ОТКУДА",
+ "TO": "КУДА",
+ "TEMP": "ТЕМП.",
+ "WIND": "ВЕТЕР",
+ "SKY": "НЕБО",
+ "PRECIP": "ОСАДКИ",
+ "RADIO": "РАДИО",
+ "VOLUME": "ГРОМКОСТЬ",
+ "RESET": "СБРОС",
+ "EXIT COCKPIT": "ВЫЙТИ ИЗ КАБИНЫ",
+ "CONTACTS · 250 KM": "КОНТАКТЫ · 250 КМ",
+ "Expand Visual Presets": "Развернуть визуальные пресеты",
+ "Pin visual presets": "Закрепить визуальные пресеты",
+ "Keep visual presets open": "Держать визуальные пресеты открытыми",
+ "Show the globe without a visual filter.": "Показывает глобус без визуального фильтра.",
+ "Emulate a green phosphor CRT with scanlines and screen curvature.": "Имитирует CRT-экран с зелёным люминофором, строками развёртки и кривизной экрана.",
+ "Simulate night-vision goggles with green intensification and a tube vignette.": "Имитирует приборы ночного видения с зелёным усилением изображения и виньеткой трубки.",
+ "Simulate FLIR-style thermal contrast. Turn up Ironbow for color.": "Имитирует тепловой контраст в стиле FLIR. Для цвета увеличьте Ironbow.",
+ "Apply bright cel-shaded color and illustrated outlines.": "Применяет яркие cel-shading-цвета и рисованные контуры.",
+ "Apply high-contrast monochrome film-noir grading.": "Применяет высококонтрастную монохромную цветокоррекцию в стиле нуар.",
+ "Add a cold, snowy whiteout treatment to the scene.": "Добавляет в сцену холодный снежный эффект «белой мглы».",
+ "Expand LOCATION": "Развернуть панель «Место»",
+ "Collapse panel": "Свернуть панель",
+ "Pin location tray": "Закрепить панель места",
+ "Keep location tray open": "Держать панель места открытой",
+ "Search any location": "Поиск любого места",
+ "Navigation, voice, and visual preset controls": "Управление навигацией, голосом и визуальными пресетами",
+ "Language: {language}": "Язык: {language}",
+ "Change the interface language": "Сменить язык интерфейса",
+ "Interface language": "Язык интерфейса",
+ "Search languages": "Поиск языка",
+ "No matching languages": "Подходящих языков нет",
+ "Search location by name or coordinates": "Поиск места по названию или координатам",
+ "Search any location...": "Поиск любого места...",
+ "Normal": "Обычный",
+ "CRT": "CRT",
+ "NVG": "NVG",
+ "FLIR": "FLIR",
+ "Style": "Стиль",
+ "STATION SITE": "САЙТ СТАНЦИИ",
+ "Open detailed Radio controls": "Открыть подробное управление радио",
+ "Previous station": "Предыдущая станция",
+ "Next station": "Следующая станция",
+ "Expand panel": "Развернуть панель",
+ "CONTACTS": "КОНТАКТЫ",
+ "Cycles the nearest contacts of whatever type you select — planes, vessels, installations. Satellites track independently.": "Перебирает ближайшие контакты выбранного типа — самолёты, суда, объекты. Спутники отслеживаются отдельно.",
+ "SEARCH NEARBY SITES": "ПОИСК ОБЪЕКТОВ РЯДОМ",
+ "Reclassify tracked contact as TR-3B": "Переклассифицировать отслеживаемый контакт как TR-3B",
+ "Previous filtered station": "Предыдущая отфильтрованная станция",
+ "PLAY": "ПУСК",
+ "Play selected station": "Воспроизвести выбранную станцию",
+ "Next filtered station": "Следующая отфильтрованная станция",
+ "STOP": "СТОП",
+ "Stop radio playback": "Остановить воспроизведение радио",
+ "Compact Radio controls": "Компактное управление радио",
+ "Context mode": "Режим контекста",
+ "Contact Context actions": "Действия контекста контакта",
+ "Available Space Missions": "Доступные космические миссии",
+ "LOADING 30-DAY MISSION INDEX": "ЗАГРУЗКА ИНДЕКСА МИССИЙ ЗА 30 ДНЕЙ",
+ "Radio playback": "Воспроизведение радио",
+ "Compact Radio volume": "Громкость компактного радио",
+ "Radio volume": "Громкость радио",
+ "STATION TAG": "ТЕГ СТАНЦИИ",
+ "DRAG TO TUNE": "ТЯНИТЕ ДЛЯ НАСТРОЙКИ",
+ "TAB PREVIEWS · ENTER / SPACE SELECTS": "TAB — ПРОСМОТР · ENTER / SPACE — ВЫБОР",
+ "Audio connects directly to the broadcaster after you press play. Your IP is visible to that broadcaster.": "После нажатия «Пуск» звук идёт напрямую от вещателя, и ему виден ваш IP-адрес.",
+ "Internet radio and local SDR": "Интернет-радио и локальный SDR",
+ "Filter stations by station tag": "Фильтровать станции по тегу",
+ "CONTEXT": "КОНТЕКСТ",
+ "SPACE MISSIONS": "КОСМИЧЕСКИЕ МИССИИ",
+ "COCKPIT": "КАБИНА",
+ "SELECT CONTACTS TO LOAD OBSERVED / MAPPED PROXIMITY": "ВЫБЕРИТЕ КОНТАКТЫ, ЧТОБЫ ЗАГРУЗИТЬ НАБЛЮДАЕМОЕ / КАРТОГРАФИРОВАННОЕ ОКРУЖЕНИЕ",
+ "SELECT A MISSION TO INSPECT": "ВЫБЕРИТЕ МИССИЮ ДЛЯ ПРОСМОТРА",
+ "Enable Radio, then choose a globe marker or use next.": "Включите радио, затем выберите маркер на глобусе или переключите на следующую станцию.",
+ "ALL · DRAG THE NEEDLE": "ВСЕ · ТЯНИТЕ СТРЕЛКУ",
+ "SNAPS TO AVAILABLE STATIONS": "ПРИВЯЗКА К ДОСТУПНЫМ СТАНЦИЯМ",
+ "SELECT CONTEXT": "ВЫБЕРИТЕ КОНТЕКСТ",
+ "CONTACTS CONTEXT OFF": "КОНТЕКСТ КОНТАКТОВ ВЫКЛЮЧЕН",
+ "AVAILABLE MISSIONS": "ДОСТУПНЫЕ МИССИИ",
+ "Intelligence HUD (H)": "HUD разведки (H)",
+ "Detection Overlay (D)": "Слой детекции (D)",
+ "Detection overlay": "Слой детекции",
+ "Elastic": "Гибкое",
+ "Weighted": "Взвешенное",
+ "3D aircraft — flat icons zoomed out, 3D models up close": "3D-самолёты — издалека плоские иконки, вблизи 3D-модели",
+ "Proximity": "Вблизи",
+ "Scope — the circular viewport mask": "Прицел — круглая маска области просмотра",
+ "Hide UI chrome": "Скрыть элементы интерфейса",
+ "Bloom / Glow": "Bloom / свечение",
+ "Sharpening": "Повышение резкости",
+ "EXIT CLEAN VIEW": "ВЫЙТИ ИЗ ЧИСТОГО ВИДА",
+ "Return UI controls": "Вернуть управление интерфейсом",
+ "Detection label allocation": "Размещение меток детекции",
+ "3D model coverage": "Охват 3D-моделей",
+ "Detection label density": "Плотность меток детекции",
+ "Detection fade distance": "Дистанция затухания детекции",
+ "World-overlay fade distance outside the keyhole as a percentage of its radius": "Дистанция затухания мирового слоя за пределами маски в процентах от её радиуса",
+ "Detection opacity outside the keyhole": "Непрозрачность детекции за пределами маски",
+ "World-overlay label and card opacity beyond the fade distance": "Непрозрачность меток и карточек мирового слоя за пределами дистанции затухания",
+ "Scope edge feather": "Растушёвка края прицела",
+ "Scope edge feather as a percentage of the keyhole radius": "Растушёвка края прицела в процентах от радиуса маски",
+ "Bloom intensity": "Интенсивность bloom",
+ "Sharpen intensity": "Интенсивность резкости",
+ "Density": "Плотность",
+ "Fade": "Затухание",
+ "Outside": "Снаружи",
+ "Tactical": "Тактический",
+ "Operator": "Операторский",
+ "Minimal": "Минимальный",
+ "HUD layout": "Макет HUD",
+ "Layout": "Макет",
+ "Allocation": "Размещение",
+ "PARAMETERS": "ПАРАМЕТРЫ",
+ "Models": "Модели",
+ "Scope": "Прицел",
+ "Feather": "Растушёвка",
+ "Celestial": "Небо",
+ "Clean UI": "Чистый интерфейс",
+ "Bloom": "Свечение",
+ "Sharpen": "Резкость",
+ "Initializing photorealistic world...": "Инициализация фотореалистичного мира...",
+ "NEAREST": "БЛИЖАЙШАЯ",
+ "Drag the camera in the world: rings rotate, arrows move, handles set range/FOV": "Перетащите камеру в мире: кольца вращают, стрелки перемещают, маркеры задают дальность и угол обзора",
+ "Heading (compass °) — click to type": "Курс (° по компасу) — нажмите для ввода",
+ "Pitch (° up/down) — click to type": "Тангаж (° вверх/вниз) — нажмите для ввода",
+ "Horizontal FOV (°) — click to type": "Горизонтальный угол обзора (°) — нажмите для ввода",
+ "Range / monitor-plane distance (m) — click to type": "Дальность / расстояние до плоскости монитора (м) — нажмите для ввода",
+ "Mount height above ground (m) — click to type": "Высота крепления над землёй (м) — нажмите для ввода",
+ "North offset from catalog position (m) — click to type": "Смещение на север от позиции каталога (м) — нажмите для ввода",
+ "East offset from catalog position (m) — click to type": "Смещение на восток от позиции каталога (м) — нажмите для ввода",
+ "SAVE CAL": "СОХРАНИТЬ КАЛИБР.",
+ "RESET CAL": "СБРОСИТЬ КАЛИБР.",
+ "NEW": "НОВАЯ",
+ "DEL": "УДАЛ.",
+ "CAPTURE SHOT": "СДЕЛАТЬ КАДР",
+ "UPDATE SHOT": "ОБНОВИТЬ КАДР",
+ "START": "СТАРТ",
+ "EXPORT PRESETS": "ЭКСПОРТ ПРЕСЕТОВ",
+ "IMPORT": "ИМПОРТ",
+ "RUN LOG": "ЖУРНАЛ ЗАПУСКОВ",
+ "CALIBRATION": "КАЛИБРОВКА",
+ "Camera pose — click a value to type": "Поза камеры — щёлкните по значению, чтобы ввести",
+ "SCENE SUMMARY": "СВОДКА ПО СЦЕНЕ",
+ "CCTV camera": "Камера CCTV",
+ "Scene recipe": "Рецепт сцены",
+ "DATA LAYERS": "СЛОИ ДАННЫХ",
+ "SCENES": "СЦЕНЫ",
+ "Close key setup": "Закрыть настройку ключей",
+ "SAVE KEYS": "СОХРАНИТЬ КЛЮЧИ",
+ "Power up the globe": "Подключите потоки данных",
+ "The globe already flies keyless. Every key below switches on another real feed — paste one and it's saved into this app's local configuration, then the server restarts itself. Server-side keys stay on this machine; Google Maps and Cesium ion run in the browser and must be provider-restricted. Keys you configured elsewhere are shown but never touched.": "Глобус уже работает без ключей. Каждый ключ ниже включает ещё один поток данных в реальном времени — вставьте ключ, и он сохранится в локальной конфигурации приложения, после чего сервер перезапустится сам. Серверные ключи остаются на этом компьютере; Google Maps и Cesium ion работают в браузере, поэтому их ключи нужно ограничить на стороне провайдера. Ключи, настроенные в другом месте, видны здесь, но изменить их нельзя.",
+ "The Google Maps key buys the photorealistic planet — everything else stacks on top.": "Ключ Google Maps открывает фотореалистичную планету — остальное накладывается поверх.",
+ "POWER UP": "ЗАПУСК",
+ "GROUND STATION · PROVIDER SETTINGS": "НАЗЕМНАЯ СТАНЦИЯ · НАСТРОЙКИ ПРОВАЙДЕРОВ",
+ "ESC to close": "ESC — закрыть",
+ "Turn off all selected data layers": "Выключить все выбранные слои данных",
+ "Copy share link": "Скопировать ссылку",
+ "Reset camera and return to full globe view": "Сбросить камеру и вернуть полный вид глобуса",
+ "Visible map targets": "Видимые цели на карте",
+ "Globe actions": "Действия с глобусом",
+ "NO PLACE LEFT BEHIND": "НИ ОДНА ТОЧКА НЕ ОСТАНЕТСЯ ПОЗАДИ",
+ "ACTIVE STYLE": "АКТИВНЫЙ СТИЛЬ",
+ "Choose your first view": "Выберите первый вид",
+ "Tip: the GEV MIC button in the dock lets you talk to the map.": "Совет: кнопка «МИК» в доке позволяет говорить с картой.",
+ "Aircraft, vessels and nearby intelligence": "Самолёты, суда и разведданные поблизости",
+ "Launches, spacecraft and orbital context": "Пуски, космические аппараты и орбитальный контекст",
+ "Begin with a clean globe": "Начните с чистого глобуса",
+ "MISSION CONTROL · FIRST LAUNCH": "ЦЕНТР УПРАВЛЕНИЯ · ПЕРВЫЙ ЗАПУСК",
+ "Don't show this again": "Больше не показывать",
+ "ESC to dismiss": "ESC — скрыть",
+ "LIVE CONTACTS": "КОНТАКТЫ ОНЛАЙН",
+ "EXPLORE MANUALLY": "ИЗУЧИТЬ ВРУЧНУЮ",
+ "Celestial ring — reveal the full globe": "Небесное кольцо — показать весь глобус",
+ "Celestial ring — available in Normal style": "Небесное кольцо — доступно в стиле «Обычный»",
+ "Detection overlay: {mode}": "Слой детекции: {mode}",
+ "Detection overlay: off": "Слой детекции: выкл.",
+ "SPARSE": "РЕДКО",
+ "BALANCED": "УМЕРЕННО",
+ "DETECT": "ДЕТЕКЦИЯ",
+ "AI AGENT": "ИИ-АГЕНТ",
+ "Voice model tier — applies next session": "Уровень голосовой модели — вступит в силу со следующей сессии",
+ "Estimated session cost": "Оценочная стоимость сессии",
+ "Voice control — activate to toggle voice; hold Space to speak": "Голосовое управление — активируйте, чтобы включить или выключить голос; удерживайте Space, чтобы говорить",
+ "VOICE STANDBY": "ГОЛОС В ОЖИДАНИИ",
+ "VOICE CONTROL": "ГОЛОСОВОЕ УПРАВЛЕНИЕ",
+ "Hold Space to speak · tap Space to activate focused controls": "Удерживайте Space, чтобы говорить · нажатие Space активирует элемент в фокусе",
+ "VOICE SYSTEM ERROR": "ОШИБКА ГОЛОСОВОЙ СИСТЕМЫ",
+ "DISMISS": "СКРЫТЬ",
+ "Check microphone permission and network access, then try again.": "Проверьте разрешение на микрофон и доступ к сети, затем попробуйте снова.",
+ "Release Space to send": "Отпустите Space для отправки",
+ "Hold Space to talk": "Держите Space и говорите",
+ "Ask or command": "Спросите или дайте команду",
+ "WebRTC microphone support unavailable": "Поддержка микрофона WebRTC недоступна",
+ "Requesting microphone": "Запрос доступа к микрофону",
+ "Voice off": "Голос выключен",
+ "VOICE UNAVAILABLE": "ГОЛОС НЕДОСТУПЕН",
+ "VOICE ACTIVE": "ГОЛОС АКТИВЕН",
+ "Voice session could not be started.": "Не удалось запустить голосовую сессию.",
+ "CONNECTING": "ПОДКЛЮЧЕНИЕ",
+ "ERROR": "ОШИБКА",
+ "{tier} applies next session": "{tier} — со следующей сессии",
+ "Session ended — cost cap {cost}": "Сессия завершена — лимит стоимости {cost}",
+ "Next session: {pendingId} — this session stays on {modelId}": "Следующая сессия: {pendingId} — текущая остаётся на {modelId}",
+ "Voice model: {pendingId} — click to switch to {target}; applies next session": "Голосовая модель: {pendingId} — нажмите, чтобы переключиться на {target}; вступит в силу со следующей сессии",
+ "Estimated session cost on {modelId} — {responses} response(s). Warns at {warn}, ends the session at {cap}.": "Оценочная стоимость сессии на {modelId} — ответов: {responses}. Предупреждение при {warn}, завершение сессии при {cap}.",
+ "Radio did not start": "Не удалось запустить радио",
+ "Running command": "Выполнение команды",
+ "Saturation": "Насыщенность",
+ "Edge Thickness": "Толщина контуров",
+ "Contrast": "Контраст",
+ "Grain": "Зерно",
+ "Vignette": "Виньетка",
+ "Pixelation": "Пикселизация",
+ "Distortion": "Искажение",
+ "Instability": "Нестабильность",
+ "Wind": "Ветер",
+ "Gain": "Усиление",
+ "Scanlines": "Строки развёртки",
+ "Sensitivity": "Чувствительность",
+ "WHOT/BHOT": "WHOT/BHOT",
+ "Ironbow": "Ironbow",
+ "Pick a shape, then click the map.": "Выберите фигуру и щёлкните по карте.",
+ "Enter to place the pin, Esc to cancel.": "Enter — поставить метку, Esc — отменить.",
+ "Click where the pin goes.": "Щёлкните там, где нужно поставить метку.",
+ "Click {count} more points.": {
+ "one": "Отметьте ещё {count} точку.",
+ "few": "Отметьте ещё {count} точки.",
+ "many": "Отметьте ещё {count} точек.",
+ "other": "Отметьте ещё {count} точки."
+ },
+ "Those points are in a line — move one off it to enclose an area.": "Точки лежат на одной линии — сдвиньте одну из них, чтобы образовалась замкнутая область.",
+ "That line has no length — click somewhere further away.": "У линии нет длины — щёлкните дальше.",
+ " · {max}-point limit reached": " · достигнут лимит точек: {max}",
+ "{measure} · double-click or Enter to finish, Backspace undoes, Esc cancels.{full}": "{measure} · двойной щелчок или Enter — завершить, Backspace — отменить точку, Esc — отменить.{full}",
+ "That point is off the globe — click on the world.": "Эта точка вне глобуса — щёлкните по Земле.",
+ "That shape could not be placed.": "Не удалось разместить фигуру.",
+ "Board cleared.": "Доска очищена.",
+ "Draw on the world — click vertices, double-click or Enter to finish, Esc to cancel": "Рисовать на карте мира — щёлкайте по вершинам, двойной щелчок или Enter — завершить, Esc — отменить",
+ "Draw": "Рисование",
+ "Shape": "Фигура",
+ "Shape to draw": "Фигура для рисования",
+ "Area": "Зона",
+ "Line": "Линия",
+ "Pin": "Метка",
+ "Label (optional)": "Подпись (необязательно)",
+ "Label for the drawn shape": "Подпись нарисованной фигуры",
+ "Colour of the drawn shape": "Цвет нарисованной фигуры",
+ "Primary": "Основной",
+ "Amber": "Янтарный",
+ "Cyan": "Голубой",
+ "Green": "Зелёный",
+ "Red": "Красный",
+ "Clear": "Очистить",
+ "Remove every mark from the board": "Убрать все пометки с доски",
- "Point the camera at the globe for street-level coverage": "Наведите камеру на глобус, чтобы увидеть покрытие уличных снимков",
+ "No street-level imagery providers configured": "Источники уличных снимков не настроены",
- "Selected": "Выбрано",
+ "Live Vessels": "Суда онлайн",
+ "Bike Share": "Прокат велосипедов",
+ "Cameras": "Камеры",
+ "Street Level": "Уличные снимки",
+ "Mapped ALPR Cameras": "Камеры ALPR на карте",
+ "Data Centers": "Дата-центры",
+ "Active Fires": "Активные пожары",
+ "Street Level could not start": "Не удалось запустить «Уличные снимки»",
+ "Street Level toggle failed": "Не удалось переключить «Уличные снимки»",
- "Street-level image": "Уличный снимок",
+ "SHRINK": "СВЕРНУТЬ",
+ "EXPAND": "РАЗВЕРНУТЬ",
+ "Shrink": "Свернуть",
+ "Expand": "Развернуть",
+ "ANY DATE": "ЛЮБАЯ ДАТА",
+ "LAST 10 YEARS": "ЗА 10 ЛЕТ",
+ "LAST 5 YEARS": "ЗА 5 ЛЕТ",
+ "LAST 3 YEARS": "ЗА 3 ГОДА",
+ "LAST 2 YEARS": "ЗА 2 ГОДА",
+ "LAST YEAR": "ЗА ГОД",
+ "LAST 6 MONTHS": "ЗА 6 МЕСЯЦЕВ",
+ "LAST 3 MONTHS": "ЗА 3 МЕСЯЦА",
+ "LAST MONTH": "ЗА МЕСЯЦ",
+ "LAST {count} DAYS": {
+ "one": "ЗА {count} ДЕНЬ",
+ "few": "ЗА {count} ДНЯ",
+ "many": "ЗА {count} ДНЕЙ",
+ "other": "ЗА {count} ДНЯ"
+ },
+ "{window} · SINCE {date}": "{window} · С {date}",
+ "Turn Street Level off": "Выключить «Уличные снимки»",
+ "Turn Street Level on": "Включить «Уличные снимки»",
+ "KEY REJECTED": "КЛЮЧ ОТКЛОНЁН",
+ "{name} imagery on": "Снимки {name} включены",
+ "{name} imagery off": "Снимки {name} выключены",
+ "Image by {creator}": "Автор снимка: {creator}",
+ "zoom in to see KartaView coverage": "приблизьтесь, чтобы увидеть покрытие KartaView",
+ "no KartaView photos in view": "фотографий KartaView в зоне видимости нет",
+ "{names}: by upload date": "{names}: по дате загрузки",
+ "{n} streets in view · click a line for its nearest photo": {
+ "one": "{n} улица в кадре · щёлкните линию, чтобы открыть ближайшую фотографию",
+ "few": "{n} улицы в кадре · щёлкните линию, чтобы открыть ближайшую фотографию",
+ "many": "{n} улиц в кадре · щёлкните линию, чтобы открыть ближайшую фотографию",
+ "other": "{n} улицы в кадре · щёлкните линию, чтобы открыть ближайшую фотографию"
+ },
- "Camera follows view: move the globe camera wherever the street-level view looks": "Камера следует за видом: камера глобуса поворачивается туда, куда смотрит уличный снимок",
- "Camera follow needs the Google 3D map: choose Google 3D under MAP SOURCE": "Слежению камеры нужна карта Google 3D: выберите Google 3D в разделе «ИСТОЧНИК КАРТЫ»",
- "Switch a provider on to draw its coverage.": "Включите источник, чтобы показать его покрытие.",
+ "Loading this sequence…": "Загрузка последовательности…",
+ "{n} images in this sequence · Esc clears": {
+ "one": "{n} снимок в последовательности · Esc — сбросить",
+ "few": "{n} снимка в последовательности · Esc — сбросить",
+ "many": "{n} снимков в последовательности · Esc — сбросить",
+ "other": "{n} снимка в последовательности · Esc — сбросить"
+ },
+ "{n} sequences in view · click a line for its photos": {
+ "one": "{n} последовательность в кадре · щёлкните по линии, чтобы открыть снимки",
+ "few": "{n} последовательности в кадре · щёлкните по линии, чтобы открыть снимки",
+ "many": "{n} последовательностей в кадре · щёлкните по линии, чтобы открыть снимки",
+ "other": "{n} последовательности в кадре · щёлкните по линии, чтобы открыть снимки"
+ },
+ "STREET LEVEL": "УЛИЧНЫЕ СНИМКИ",
- "Expand the street-level view (Esc shrinks it)": "Развернуть уличный снимок (Esc сворачивает)",
+ "Image fit": "Масштаб снимка",
+ "FIT": "ВПИСАТЬ",
+ "Fit: show the whole photo, with dark bars where its shape differs from the frame": "Вписать: показать снимок целиком, с тёмными полосами там, где его форма не совпадает с рамкой",
+ "FILL": "ЗАПОЛНИТЬ",
+ "Fill: fill the frame edge to edge, cropping the photo": "Заполнить: заполнить рамку целиком, обрезав края снимка",
- "Camera follows view": "Камера следует за видом",
- "FOLLOW": "СЛЕДИТЬ",
+ "Close the image and deselect it on the map": "Закрыть снимок и снять выделение на карте",
+ "Close the street-level image": "Закрыть уличный снимок",
+ "Street-level viewer": "Просмотр уличных снимков",
+ "Open this image on the provider's site": "Открыть снимок на сайте источника",
+ "Imagery providers": "Источники снимков",
+ "PROVIDERS": "ИСТОЧНИКИ",
+ "Imagery filters": "Фильтры снимков",
+ "IMAGERY": "СНИМКИ",
+ "Panorama filter": "Фильтр панорам",
+ "ALL": "ВСЕ",
+ "FLAT": "ПЛОСКИЕ",
+ "SINCE": "С ДАТЫ",
- "Coverage colours": "Цвета покрытия",
+ "That shape already has {count} points — finish it or press Backspace.": "В этой фигуре уже точек: {count} — завершите её или нажмите Backspace.",
+ "Could not place the shape: {error}": "Не удалось разместить фигуру: {error}",
+ "{owner} is using the pointer — close it first.": "Указатель занят: «{owner}». Закройте его.",
+ "{label} · Detailed outline unavailable": "{label} · Подробный контур недоступен",
+ "Witness source": "Свидетельство очевидца",
+ "{provider} · EMBEDDED SOURCE": "{provider} · ВСТРОЕННЫЙ ИСТОЧНИК",
+ "OPEN ORIGINAL ↗": "ОТКРЫТЬ ОРИГИНАЛ ↗",
+ "{provider} media: {source}": "Медиа {provider}: {source}",
+ "{provider} · PROVIDER CONTROLS": "{provider} · ВСТРОЕННЫЙ ПЛЕЕР",
+ "YOUTUBE {state} · OPEN ORIGINAL": "YOUTUBE {state} · ОТКРЫТЬ ОРИГИНАЛ",
+ "Facebook player API did not initialize.": "API плеера Facebook не инициализировался.",
+ "Facebook player API could not load.": "Не удалось загрузить API плеера Facebook.",
+ "Facebook player API timed out.": "Истекло время ожидания API плеера Facebook.",
+ "X embed API did not initialize.": "API встраивания X не инициализировался.",
+ "X embed could not load.": "Не удалось загрузить встраивание X.",
+ "X embed timed out.": "Истекло время ожидания встраивания X.",
+ "TIMEOUT": "ТАЙМАУТ",
+ "BLOCKED": "ЗАБЛОКИРОВАНО",
+ "Facebook embed unavailable. The post may be private, removed, region-restricted, or blocked.": "Встраивание Facebook недоступно. Публикация может быть закрытой, удалённой, ограниченной по региону или заблокированной.",
+ "Preloading {provider} media": "Предзагрузка медиа {provider}",
+ "LOADING X POST…": "ЗАГРУЗКА ПОСТА X…",
+ "The X post is unavailable or cannot be embedded.": "Пост X недоступен или не может быть встроен.",
+ "X POST · PROVIDER CONTROLS": "ПОСТ X · ВСТРОЕННЫЙ ВИДЖЕТ",
+ "{reason} OPEN ORIGINAL.": "{reason} ОТКРОЙТЕ ОРИГИНАЛ.",
+ "X embed unavailable": "Встраивание X недоступно",
+ "FACEBOOK · PROVIDER CONTROLS": "FACEBOOK · ВСТРОЕННЫЙ ПЛЕЕР",
+ "Facebook embed unavailable": "Встраивание Facebook недоступно",
+ "AUTOPLAY BLOCKED · USE PROVIDER CONTROLS": "АВТОВОСПРОИЗВЕДЕНИЕ ЗАБЛОКИРОВАНО · ЗАПУСТИТЕ В ПЛЕЕРЕ",
+ "Embedded {provider} media for {source}": "Встроенное медиа {provider}: {source}",
+ "witness source": "свидетельство очевидца",
+ "Rasuwagadhi witness": "Очевидец в Rasuwagadhi",
+ "Open original source for {source}; capture time unverified": "Открыть оригинал: {source}; время съёмки не подтверждено",
+ "Historical reference and post-event image divider": "Разделитель исторического снимка и снимка после события",
+ "A historical reference {before} percent, B post-event {after} percent": "A — исторический снимок: {before}%, B — после события: {after}%",
+ "■ RELEASE CAMERA": "■ ОСВОБОДИТЬ КАМЕРУ",
+ "Seek Nepal scene clock": "Перемотка времени сцены в Непале",
+ "NEPAL SCENE CLOCK": "ВРЕМЯ СЦЕНЫ В НЕПАЛЕ",
+ "… PLAYING SHOT": "… ИДЁТ КАДР",
+ "▶ PLAY SHOT": "▶ ПУСК КАДРА",
+ "Ⅱ PAUSE": "Ⅱ ПАУЗА",
+ "↺ REPLAY CINEMATIC": "↺ ПОВТОРИТЬ КИНОРЕЖИМ",
+ "↺ REPLAY": "↺ ПОВТОРИТЬ",
+ "… PLAYING SCENE": "… ИДЁТ СЦЕНА",
+ "Continue {scene} from next shot": "Продолжить со следующего кадра: {scene}",
+ "current scene": "текущая сцена",
+ "Replay the full reconstruction": "Повторить всю реконструкцию",
+ "SCENE SHOT": "КАДР СЦЕНЫ",
+ "TIME UNVERIFIED": "ВРЕМЯ НЕ ПОДТВЕРЖДЕНО",
+ "{count} SOURCES": {
+ "one": "{count} ИСТОЧНИК",
+ "few": "{count} ИСТОЧНИКА",
+ "many": "{count} ИСТОЧНИКОВ",
+ "other": "{count} ИСТОЧНИКА"
+ },
+ "OUTSIDE IMAGERY SWIPE": "ВНЕ СРАВНЕНИЯ СНИМКОВ",
+ "{scene} / AUTHORED SHOT": "{scene} / АВТОРСКИЙ КАДР",
+ "NEPAL FLOOD INCIDENT": "НАВОДНЕНИЕ В НЕПАЛЕ",
+ "Play {shot}": "Воспроизвести: {shot}",
+ "current scene shot": "текущий кадр сцены",
+ "Play reconstruction": "Воспроизвести реконструкцию",
+ "Load previous scene shot": "Загрузить предыдущий кадр сцены",
+ "Load next scene shot": "Загрузить следующий кадр сцены",
+ "SCHEMATIC CORRIDOR, NOT MODELED ARRIVAL TIME.": "СХЕМАТИЧЕСКИЙ КОРИДОР, А НЕ МОДЕЛЬ ВРЕМЕНИ ДОБЕГАНИЯ ПАВОДКА.",
+ "Rasuwa · 26 Aug 2026": "Rasuwa · 26 авг. 2026",
+ "Event reconstruction": "Реконструкция события",
+ "INITIATION": "ЗАРОЖДЕНИЕ",
+ "DAMMING": "ЗАПРУДА",
+ "SECONDARY FAILURE": "ВТОРИЧНЫЙ ПРОРЫВ",
+ "BORDER ARRIVAL": "ДОСТИЖЕНИЕ ГРАНИЦЫ",
+ "PROPAGATION": "РАСПРОСТРАНЕНИЕ",
+ "DOWNSTREAM PASSAGE": "ПРОХОЖДЕНИЕ ВНИЗ ПО ТЕЧЕНИЮ",
+ "CONSEQUENCE": "ПОСЛЕДСТВИЯ",
+ "DOWNSTREAM CONSEQUENCE": "ПОСЛЕДСТВИЯ НИЖЕ ПО ТЕЧЕНИЮ",
+ "EVIDENCE": "СВИДЕТЕЛЬСТВА",
+ "{count} GEOLOCATED SOURCE-MAP PLACEMENTS": {
+ "one": "{count} ГЕОПРИВЯЗАННАЯ МЕТКА НА КАРТЕ ИСТОЧНИКОВ",
+ "few": "{count} ГЕОПРИВЯЗАННЫЕ МЕТКИ НА КАРТЕ ИСТОЧНИКОВ",
+ "many": "{count} ГЕОПРИВЯЗАННЫХ МЕТОК НА КАРТЕ ИСТОЧНИКОВ",
+ "other": "{count} ГЕОПРИВЯЗАННОЙ МЕТКИ НА КАРТЕ ИСТОЧНИКОВ"
+ },
+ "NO PREVIEW": "НЕТ ПРЕДПРОСМОТРА",
+ "SOURCE LINK": "ССЫЛКА НА ИСТОЧНИК",
+ "{publisher} / OPEN": "{publisher} / ОТКРЫТЬ",
+ "Bhote Koshi flood reconstruction controls": "Управление реконструкцией наводнения на Bhote Koshi",
+ "EVENT RECONSTRUCTION · 26 AUG 2026": "РЕКОНСТРУКЦИЯ СОБЫТИЯ · 26 АВГ. 2026",
+ "BHOTE KOSHI OUTBURST FLOOD": "ПРОРЫВНОЙ ПАВОДОК НА BHOTE KOSHI",
+ "Close event layer": "Закрыть слой события",
+ "OBSERVED IMAGERY": "ФАКТИЧЕСКИЕ СНИМКИ",
+ "SCHEMATIC CORRIDOR": "СХЕМАТИЧЕСКИЙ КОРИДОР",
+ "2021 HISTORICAL REFERENCE / 2026 POST-EVENT": "2021 ИСТОРИЧЕСКИЙ СНИМОК / 2026 ПОСЛЕ СОБЫТИЯ",
+ "Historical reference and post-event image split": "Сравнение исторического снимка и снимка после события",
+ "RECONSTRUCTION CLOCK": "ВРЕМЯ РЕКОНСТРУКЦИИ",
+ "Schematic downstream progression": "Схематическое продвижение вниз по течению",
+ "Story beat navigation": "Навигация по этапам сюжета",
+ "Previous story beat": "Предыдущий этап сюжета",
+ "CAUSE": "ПРИЧИНА",
+ "CAPTURE TIME UNVERIFIED": "ВРЕМЯ СЪЁМКИ НЕ ПОДТВЕРЖДЕНО",
+ "Next story beat": "Следующий этап сюжета",
+ "▶ PLAY": "▶ ПУСК",
+ "Play the next shot and continue through this scene": "Воспроизвести следующий кадр и продолжить эту сцену",
+ "▶ PLAY SCENE": "▶ ПУСК СЦЕНЫ",
+ "◉ CINEMATIC": "◉ КИНОРЕЖИМ",
+ "↺ FULL STORY": "↺ ВСЯ ИСТОРИЯ",
+ "↗ OPEN ORIGINAL": "↗ ОРИГИНАЛ",
+ "⌖ LOWER GORGE": "⌖ НИЖНЕЕ УЩЕЛЬЕ",
+ "FIELD REPORTS · {count}": "СООБЩЕНИЯ С МЕСТА · {count}",
+ "GEOLOCATIONS · {credit}": "ГЕОЛОКАЦИИ · {credit}",
+ "↗ OPEN PUBLIC MAP": "↗ ОТКРЫТЬ ПУБЛИЧНУЮ КАРТУ",
+ "Clouds are preserved from the source imagery.": "Облака оставлены такими, как на исходных снимках.",
+ "Show the Nepal context callout without a border or country fill": "Показать выноску с контекстом Непала без границы и заливки страны",
+ "Introduce Nepal, draw its border, then reveal the Bhote Koshi incident": "Представить Непал, нарисовать его границу, затем показать инцидент на Bhote Koshi",
+ "CITIES": "ГОРОДА",
+ "Keep the regional incident context and introduce nearby city labels": "Сохранить региональный контекст инцидента и добавить подписи ближайших городов",
+ "PLACES": "МЕСТА",
+ "Introduce the reconstruction scene key places from trigger to downstream": "Показать ключевые места сцены реконструкции — от источника события до низовья",
+ "PATH": "ПУТЬ",
+ "Animate the sourced cyan river-centerline route to Trishuli Bazaar": "Анимировать голубой маршрут по оси реки до Trishuli Bazaar по данным источников",
+ "OVERVIEW": "ОБЗОР",
+ "Keep the completed flood path and location labels visible": "Оставить на экране весь путь паводка и подписи мест",
+ "RECORD": "ЗАПИСЬ",
+ "Reveal the trigger record while making a slow camera approach": "Показать запись о первопричине при медленном приближении камеры",
+ "BHOTE KOSHI FLOOD INCIDENT": "НАВОДНЕНИЕ НА BHOTE KOSHI",
+ "NEPAL · 26 AUG 2026": "НЕПАЛ · 26 АВГ. 2026",
+ "USGS INITIAL REPORT": "ПЕРВИЧНОЕ СООБЩЕНИЕ USGS",
+ "26 AUG 2026 · 08:37 NPT": "26 АВГ. 2026 · 08:37 NPT",
+ "28.2710° N · 85.5150° E": "28,2710° С. Ш. · 85,5150° В. Д.",
+ "INITIAL M4.4 · RECLASSIFIED M5.2 LANDSLIDE": "ПЕРВОНАЧАЛЬНО M4,4 · ПЕРЕКЛАССИФИЦИРОВАНО: ОПОЛЗЕНЬ M5,2",
+ "USGS EVENT us7000tbwb · OPEN SOURCE": "СОБЫТИЕ USGS us7000tbwb · ОТКРЫТЬ ИСТОЧНИК",
+ "flight": "рейс",
+ "military flight": "военный рейс",
+ "satellite": "спутник",
+ "VOICE AUTH · CHATGPT OAUTH": "ГОЛОС: АВТОРИЗАЦИЯ · CHATGPT OAUTH",
+ "VOICE AUTH · API KEY": "ГОЛОС: КЛЮЧ API",
+ "USE API KEY": "ИСПОЛЬЗОВАТЬ КЛЮЧ API",
+ "USE CHATGPT OAUTH": "ИСПОЛЬЗОВАТЬ CHATGPT OAUTH",
+ "Use OPENAI_API_KEY for the next cloud voice session": "Использовать OPENAI_API_KEY для следующей облачной голосовой сессии",
+ "Use the signed-in local ChatGPT/Codex OAuth session for the next cloud voice session": "Использовать локальную OAuth-сессию ChatGPT/Codex, в которую выполнен вход, для следующей облачной голосовой сессии",
+ "Metered — a billing-enabled account": "Платный — нужен аккаунт с включённой оплатой",
+ "Free key — register, paste, done": "Бесплатный ключ — зарегистрируйтесь, вставьте, готово",
+ "browser-side": "в браузере",
+ "This key runs in the browser by design — restrict it at the provider (see SECURITY.md)": "Этот ключ по задумке работает в браузере — ограничьте его у провайдера (см. SECURITY.md)",
+ "configured externally": "задан извне",
+ "Supplied by your environment, Keychain, or launcher — change it where it was set": "Задан окружением, Keychain или лаунчером — меняйте его там, где он задан",
+ "MANAGE ↗": "УПРАВЛЯТЬ ↗",
+ "GET KEY ↗": "ПОЛУЧИТЬ КЛЮЧ ↗",
+ "{envVar} saved — paste to replace": "{envVar} сохранён — вставьте, чтобы заменить",
+ "paste {envVar}": "вставьте {envVar}",
+ "Project keys: {status}": "Ключи проекта: {status}",
+ "Mapped camera locations": "Расположение камер на карте",
+ "SHOW NEAREST": "ПОКАЗАТЬ БЛИЖАЙШУЮ",
+ "Stop following the current object before navigating to a camera": "Прекратите следовать за текущим объектом, прежде чем переходить к камере",
+ "Move to the nearest loaded camera and show its details": "Перейти к ближайшей загруженной камере и показать её данные",
+ "Camera badges": "Значки камер",
+ "Cyan cameras turn coral when selected. Wedges illustrate mapped direction, not measured coverage. Nearby cameras may be outside the screen.": "Голубые камеры при выборе становятся коралловыми. Секторы показывают направление по карте, а не измеренное покрытие. Ближайшие камеры могут быть за пределами экрана.",
+ "{count} nearby · {onScreen} on screen": {
+ "one": "{count} рядом · {onScreen} видно",
+ "few": "{count} рядом · {onScreen} видно",
+ "many": "{count} рядом · {onScreen} видно",
+ "other": "{count} рядом · {onScreen} видно"
+ },
+ "{count} nearby": {
+ "one": "рядом: {count}",
+ "few": "рядом: {count}",
+ "many": "рядом: {count}",
+ "other": "рядом: {count}"
+ },
+ "retrying mapped ALPR cameras": "повторная загрузка камер ALPR",
+ "loading mapped ALPR cameras": "загрузка камер ALPR",
+ "No ALPR data for this area — US and Canada only": "Нет данных ALPR для этой области — только США и Канада",
+ "Zoom in to load mapped cameras": "Приблизьте карту, чтобы загрузить камеры",
+ "Showing cached locations": "Показаны места из кэша",
+ "Coverage limited — zoom in": "Покрытие ограничено — приблизьте карту",
+ "No ALPR data for this area": "Нет данных ALPR для этой области",
+ "None on screen — nearby cameras are outside the view": "На экране нет — ближайшие камеры вне поля зрения",
+ "ALPR camera": "Камера ALPR",
+ "OpenStreetMap · community mapped": "OpenStreetMap · данные сообщества",
+ "Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Атлантика и восточная/центральная часть северного Тихого океана; покрытие циклонов не глобальное.",
+ "Potential tropical cyclone": "Потенциальный тропический циклон",
+ "Hurricane": "Ураган",
+ "Tropical storm": "Тропический шторм",
+ "Tropical depression": "Тропическая депрессия",
+ "Subtropical storm": "Субтропический шторм",
+ "Subtropical depression": "Субтропическая депрессия",
+ "Track and cone match this advisory": "Трек и конус соответствуют этой сводке",
+ "Track/cone awaiting advisory {number}": "Трек и конус появятся со сводкой № {number}",
+ "Track/cone unavailable": "Трек/конус недоступны",
+ "Cached advisory · stale source": "Сводка из кэша · источник устарел",
+ "Loading advisories…": "Загрузка сводок…",
+ "{count} active storms": {
+ "one": "{count} активный шторм",
+ "few": "{count} активных шторма",
+ "many": "{count} активных штормов",
+ "other": "{count} активного шторма"
+ },
+ "Position as of {time}": "Положение на {time}",
+ "Maximum sustained wind: {wind} · Pressure: {pressure}": "Макс. устойчивый ветер: {wind} · Давление: {pressure}",
+ "{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Сводка № {number} · выпущена {time}",
+ "No active NHC/CPHC systems": "Нет активных систем NHC/CPHC",
+ "Advisories unavailable": "Сводки недоступны",
+ "Cyclones · NHC / CPHC": "Циклоны · NHC / CPHC",
+ "Atlantic · E/C Pacific": "Атлантика · вост./центр. Тихий океан",
+ "{storms} · {name} selected": "{storms} · выбран {name}",
+ "Official advisory ↗": "Официальная сводка ↗",
+ "Active NHC and CPHC cyclone advisories": "Действующие сводки NHC и CPHC о циклонах",
+ "Wind unavailable": "Ветер: нет данных",
+ "Advisory center / forecast track": "Центр циклона по сводке / прогнозный трек",
+ "Center-track uncertainty cone": "Конус неопределённости трека центра",
+ "Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Выберите шторм на карте или в списке, чтобы выделить его и переместить к нему камеру. Щёлкните по пустому месту карты, чтобы снять выделение. Контекст сводок NOAA NHC/CPHC. Конус описывает неопределённость прогнозного трека центра, а не размер шторма или всю зону опасности. Подписи прогнозных точек — заблаговременность источника в часах, а не время, рассчитанное от выпуска сводки. Геометрия следует поверхности; высота не отражает высоту погодных явлений. Сверяйтесь с официальной сводкой.",
+ "Directions": "Маршруты",
+ "{mode} — reroute for {modeLower}": "{mode} — перестроить маршрут: {modeLower}",
+ "CLICK MAP": "ЩЁЛКНИТЕ ПО КАРТЕ",
+ "SET A": "ЗАДАТЬ A",
+ "Click a spot on the globe to place A (click again to cancel)": "Щёлкните по точке на глобусе, чтобы поставить A (повторный щелчок — отмена)",
+ "Then click the globe to place the start": "Затем щёлкните по глобусу, чтобы поставить начало",
+ "SET B": "ЗАДАТЬ B",
+ "Click a spot on the globe to place B (click again to cancel)": "Щёлкните по точке на глобусе, чтобы поставить B (повторный щелчок — отмена)",
+ "Then click the globe to place the destination": "Затем щёлкните по глобусу, чтобы поставить пункт назначения",
+ "Swap A and B": "Поменять A и B местами",
+ "FLY ···": "ПОЛЁТ ···",
+ "FLYING": "В ПОЛЁТЕ",
+ "FLY": "ПОЛЁТ",
+ "Fly the camera along the route": "Пролететь камерой по маршруту",
+ "Place A and B first": "Сначала поставьте A и B",
+ "Remove the route and both markers": "Удалить маршрут и обе метки",
+ "press Escape twice to leave Draw": "дважды нажмите Esc, чтобы выйти из режима «Рисование»",
+ "{name} is active — turn {name} off, then set {endpoint}": "Активно: {name} — выключите {name}, затем задайте {endpoint}",
+ "{name} is active — {leave}, then set {endpoint}": "Активно: {name} — {leave}, затем задайте {endpoint}",
+ "Only the first {count} turns of this route are shown": "Показаны только первые повороты маршрута: {count}",
+ "Turn-by-turn directions": "Пошаговые указания",
+ "OSM routing": "Маршрутизация OSM",
+ "DRIVE": "АВТО",
+ "Drive": "На машине",
+ "Another map tool is using clicks — close it, then SET A again": "Щелчки перехватывает другой инструмент карты — закройте его и снова нажмите «ЗАДАТЬ A»",
+ "WALK": "ПЕШКОМ",
+ "Walk": "Пешком",
+ "Routing…": "Построение маршрута…",
+ "BIKE": "ВЕЛО",
+ "Bike": "На велосипеде",
+ "No route found": "Маршрут не найден",
+ "{distance} · {duration} · {mode} · first {count} turns": "{distance} · {duration} · {mode} · первые повороты: {count}",
+ "{distance} · {duration} · {mode}": "{distance} · {duration} · {mode}",
+ "Click the globe to place {endpoint}": "Щёлкните по глобусу, чтобы поставить {endpoint}",
+ "SET B, then click the globe": "Нажмите «ЗАДАТЬ B», затем щёлкните по глобусу",
+ "SET A, then click the globe": "Нажмите «ЗАДАТЬ A», затем щёлкните по глобусу",
+ "Step {step} of {total} · then {leg}": "Шаг {step} из {total} · затем {leg}",
+ "Step {step} of {total}": "Шаг {step} из {total}",
+ "Then: {instruction}": "Затем: {instruction}",
+ "No route found between A and B": "Маршрут между A и B не найден",
+ "Routing failed: {error}": "Не удалось построить маршрут: {error}",
+ "Routing timed out": "Истекло время построения маршрута",
+ "Routing unavailable — no response from the routing service": "Построение маршрута недоступно — сервис маршрутизации не отвечает",
+ "Routing unavailable": "Построение маршрута недоступно",
+ "Fire · FRP {frp} MW": "Пожар · FRP {frp} МВт",
+ "Not contained or unknown": "Не локализован или неизвестно",
+ "Under 50% contained": "Локализован менее чем на 50%",
+ "50–99% contained": "Локализован на 50–99%",
+ "Fully contained": "Полностью локализован",
+ "Colour shows reported containment. Perimeters are simplified to about 100 m.": "Цвет показывает заявленную степень локализации. Контуры упрощены примерно до 100 м.",
+ "MORE DETAIL · 30 m": "БОЛЬШЕ ДЕТАЛЕЙ · 30 м",
+ "Sentinel-2 and Landsat via HLS, 30 m, every 2–6 days": "Sentinel‑2 и Landsat через HLS, 30 м, каждые 2–6 дней",
+ "DAILY OVERVIEW · 250 m": "ЕЖЕДНЕВНЫЙ ОБЗОР · 250 м",
+ "VIIRS daily mosaic, 250 m, follows broad changes; little detail under 25 km": "Ежедневная мозаика VIIRS, 250 м, показывает крупные изменения; мало деталей в масштабе менее 25 км",
+ "Catalog truncated · a newer clear day may exist": "Каталог усечён · возможно, есть более поздний ясный день",
+ "{label} catalog unavailable · {detail}": "Каталог {label} недоступен · {detail}",
+ "Daily overview for today may still be empty until the pass": "Ежедневный обзор за сегодня может оставаться пустым до пролёта спутника",
+ "Sentinel-2": "Sentinel‑2",
+ "Landsat 8/9": "Landsat 8/9",
+ "Daily overview": "Ежедневный обзор",
+ "No frame within {gap} min of {time}": "Нет кадра в пределах {gap} мин от {time}",
+ "No frame within {gap} h of {time}": "Нет кадра в пределах {gap} ч от {time}",
+ "{hours}h {minutes}m ago": "{hours} ч {minutes} мин назад",
+ "{minutes}m ago": "{minutes} мин назад",
+ "{state} · {time} · {lag}": "{state} · {time} · {lag}",
+ "Observed": "Наблюдение",
+ "History": "История",
+ "Observation unavailable": "Наблюдение недоступно",
+ "Waiting for observation": "Ожидание наблюдения",
+ "{detail} · synced": "{detail} · синхр.",
+ "{detail} · nearest": "{detail} · ближайший",
+ "RADAR REFLECTIVITY · dBZ": "РАДИОЛОК. ОТРАЖАЕМОСТЬ · dBZ",
+ "LIGHTNING DENSITY · 15 min accumulation": "ПЛОТНОСТЬ МОЛНИЙ · накопление за 15 мин",
+ "GLOBAL INFRARED · hourly": "ГЛОБАЛЬНЫЙ ИК · ежечасно",
+ "GOES INFRARED · ~5 min": "GOES ИК · ~5 мин",
+ "{state}: {time}": "{state}: {time}",
+ "Latest observation": "Последнее наблюдение",
+ "frame {index}/{total}": "кадр {index}/{total}",
+ "loading": "загрузка",
+ "Observation: unavailable": "Наблюдение: недоступно",
+ "Contiguous US · gaps ≠ no rain": "Континентальные США · пробелы ≠ нет дождя",
+ "Americas + Pacific · not individual strikes": "Америка + Тихий океан · не отдельные разряды",
+ "Color: strikes/km²/min ×10³": "Цвет: разрядов/км²/мин ×10³",
+ "60°S–60°N · typically 2–3 h delayed": "60° ю. ш.–60° с. ш. · обычно задержка 2–3 ч",
+ "North America · infrared imagery": "Северная Америка · ИК-снимки",
+ "Reduced motion · history playback unavailable": "Уменьшение движения · воспроизведение истории недоступно",
+ "Reduced motion · manual history available": "Уменьшение движения · историю можно листать вручную",
+ "Rain radar · US": "Радар осадков · США",
+ "Lightning density · 15 min": "Плотность молний · 15 мин",
+ "Satellite clouds": "Спутниковая облачность",
+ "Americas + Pacific": "Америка + Тихий океан",
+ "Global · 60°S–60°N": "Глобально · 60° ю. ш.–60° с. ш.",
+ "North America": "Северная Америка",
+ "Source observations delayed": "Наблюдения источника задерживаются",
+ "Stale source": "Источник устарел",
+ "Loading next frame…": "Загрузка следующего кадра…",
+ "Map center outside coverage": "Центр карты вне зоны покрытия",
+ "strikes/km²/min ×10³": "разрядов/км²/мин ×10³",
+ "N. America": "Сев. Америка",
+ "Global": "Глобально",
+ "Hourly global mosaic; usually 2–3 hours delayed": "Ежечасная глобальная мозаика; обычно с задержкой 2–3 ч",
+ "GOES regional clouds; approximately 5-minute updates": "Региональная облачность GOES; обновление примерно каждые 5 мин",
+ "Clouds only": "Только облака",
+ "Full": "Полный",
+ "Soft": "Мягко",
+ "Vivid": "Ярко",
+ "Image opacity; does not alter the observed values": "Непрозрачность изображения; не меняет наблюдаемые значения",
+ "View US radar": "Показать радар США",
+ "View Americas & Pacific": "Показать Америку и Тихий океан",
+ "View coverage": "Показать зону покрытия",
+ "{value} strikes/km²/min ×10³ (15-minute density)": "{value} разрядов/км²/мин ×10³ (плотность за 15 мин)",
+ "{value} dBZ radar reflectivity": "Радиолокационная отражаемость: {value} dBZ",
+ "STALE · cached source metadata": "УСТАРЕЛ · метаданные источника из кэша",
+ "Map center is outside source coverage": "Центр карты вне зоны покрытия источника",
+ "NOAA/NWS 15-minute lightning density derived from Vaisala NLDN/GLD360. Coverage 110°E across the Pacific/Americas to 0°, 25°S–80°N. Not a live strike count, global coverage or a safety warning.": "15-минутная плотность молний NOAA/NWS на основе Vaisala NLDN/GLD360. Покрытие — от 110° в. д. через Тихий океан и Америку до 0°, 25° ю. ш.–80° с. ш. Это не подсчёт разрядов в реальном времени, не глобальное покрытие и не предупреждение об опасности.",
+ "NOAA MRMS radar echoes indicate precipitation patterns, not rain rate, a storm warning or a future forecast. Native source approximately 1 km; display is limited to level 6. Frames use exact advertised observation times.": "Радиолокационные эхосигналы NOAA MRMS показывают картину осадков, а не их интенсивность, штормовое предупреждение или прогноз. Исходное разрешение около 1 км; отображение ограничено уровнем 6. Для кадров используется точное заявленное время наблюдений.",
+ "GOES-19/18 longwave infrared Band 14 regional; NESDIS global longwave mosaic. Clouds only dims everything but bright, cold cloud tops; a brightness filter, not a cloud mask. Coverage and freshness differ by region.": "Региональный длинноволновый ИК-канал 14 GOES-19/18; глобальная длинноволновая мозаика NESDIS. Режим «Только облака» затемняет всё, кроме ярких холодных вершин облаков; это фильтр яркости, а не маска облачности. Покрытие и актуальность различаются по регионам.",
+ "REGION": "РЕГИОН",
+ "IMAGE": "СНИМОК",
+ "OPACITY": "НЕПРОЗР.",
+ "Forecast · does not follow history": "Прогноз · не следует за историей",
+ "Wind motion": "Движение ветра",
+ "Wind speed": "Скорость ветра",
+ "Sea-level pressure": "Давление на уровне моря",
+ "Air temperature · 2 m": "Температура воздуха · 2 м",
+ "Global · 1° grid": "Глобально · сетка 1°",
+ "{model} forecast · {time}": "Прогноз {model} · {time}",
+ "Loading forecast": "Загрузка прогноза",
+ "Preparing flow": "Подготовка анимации ветра",
+ "Selected field unavailable": "Выбранное поле недоступно",
+ "Cached forecast · stale": "Прогноз из кэша · устарел",
+ "ECMWF IFS surface forecast": "Приземный прогноз ECMWF IFS",
+ "NOAA GFS surface forecast": "Приземный прогноз NOAA GFS",
+ "Reduced motion": "Уменьшение движения",
+ "Pause visual flow; forecast time does not advance with animation": "Приостановить визуальный поток; время прогноза не сдвигается с анимацией",
+ "None": "Нет",
+ "Speed": "Скорость",
+ "Pressure": "Давление",
+ "Temperature": "Температура",
+ "Wind trails with no field shading": "Следы ветра без заливки поля",
+ "How hard the surface wind is blowing": "Насколько сильно дует приземный ветер",
+ "Sea-level air pressure: broad highs and lows": "Давление на уровне моря: крупные области высокого и низкого давления",
+ "Air temperature two meters above the surface": "Температура воздуха в двух метрах над поверхностью",
+ "Wind speed units": "Единицы скорости ветра",
+ "Read wind at map center": "Узнать ветер в центре карты",
+ "Read the forecast at the center of the map without changing selection": "Получить прогноз в центре карты, не меняя выбор",
+ "{model} forecast · {field} ({unit})": "Прогноз {model} · {field} ({unit})",
+ "Valid: {time}": "Действует на: {time}",
+ "preparing": "подготовка",
+ "Issued: {time}": "Выпущен: {time}",
+ "Selected field unavailable · wind remains visible": "Выбранное поле недоступно · ветер остаётся видимым",
+ "{error} · wind remains visible": "{error} · ветер остаётся видимым",
+ "Surface wind at 10 m. Approximately 1° global grid. Curves follow the 10 m wind field, lifted 12 km for visibility; display height is not weather altitude. View lighting is for readability. Animation shows flow through one fixed forecast; it does not advance time. Color fields drape the globe basemap or the active photorealistic 3D Tiles.": "Приземный ветер на высоте 10 м. Глобальная сетка около 1°. Линии следуют полю ветра на 10 м и подняты на 12 км для наглядности; высота отображения не является высотой погодных явлений. Освещение вида — для удобства чтения. Анимация показывает поток в одном фиксированном прогнозе и не сдвигает время. Цветовые поля накладываются на подложку глобуса или на активные фотореалистичные 3D Tiles.",
+ "MODEL": "МОДЕЛЬ",
+ "FIELD": "ПОЛЕ",
+ "UNITS": "ЕДИНИЦЫ",
+ "MOTION": "ДВИЖЕНИЕ",
+ "Forecast": "Прогноз",
+ "Interpolated model forecast on an approximately 1° grid. Broad weather patterns, not a street-level measurement.": "Интерполированный модельный прогноз на сетке около 1°. Общая погодная обстановка, а не измерение на уровне улицы.",
+ "No surface reading": "Нет приземных данных",
+ "Aim the map center at Earth": "Наведите центр карты на Землю",
+ " · calm": " · штиль",
+ " from {direction}": " с {direction}",
+ "WIND AT {coordinates}": "ВЕТЕР В ТОЧКЕ {coordinates}",
+ "{model} · valid {time}": "{model} · на {time}",
+ "Focusing {label}": "Фокусировка: {label}",
+ "Source": "Источник",
+ "Could not leave scene: {scene}": "Не удалось выйти из сцены: {scene}",
+ "Seeked: {scene} / {shot}": "Перемотано: {scene} / {shot}",
+ "Scene transition limit reached — load a shot to reset": "Достигнут лимит переходов сцены — загрузите кадр, чтобы сбросить счётчик",
+ "Export failed: {error}": "Ошибка экспорта: {error}",
+ "Imported {file}": "Импортировано: {file}",
+ "Import failed: {error}": "Ошибка импорта: {error}",
+ "Import failed (could not read JSON file)": "Ошибка импорта (не удалось прочитать файл JSON)",
+ "Layers refused: {layers}": "Слои отклонены: {layers}",
+ "Scene {n}": "Сцена {n}",
+ "Cannot update {scene}: shot inventory changed": "Не удалось обновить {scene}: изменился состав кадров",
+ "Cannot update {scene}: evidence beats changed": "Не удалось обновить {scene}: изменились этапы свидетельств",
+ "Cannot update {scene}: shot bindings are incomplete": "Не удалось обновить {scene}: привязки кадров неполные",
+ "Updated {count} shots: {scene}": {
+ "one": "Обновлён {count} кадр: {scene}",
+ "few": "Обновлено {count} кадра: {scene}",
+ "many": "Обновлено {count} кадров: {scene}",
+ "other": "Обновлено {count} кадра: {scene}"
+ },
+ "Appended {count} shots: {scene}": {
+ "one": "Добавлен {count} кадр: {scene}",
+ "few": "Добавлено {count} кадра: {scene}",
+ "many": "Добавлено {count} кадров: {scene}",
+ "other": "Добавлено {count} кадра: {scene}"
+ },
+ "Select a feature or use Tab and Enter to choose an action.": "Выберите объект на карте или используйте Tab и Enter, чтобы выбрать действие.",
+ "Selected feature: {feature}. Choose an action.": "Выбран объект: {feature}. Выберите действие.",
+ "Action complete": "Действие выполнено",
+ "Action unavailable or cancelled": "Действие недоступно или отменено",
+ "Scene actions": "Действия сцены",
+ "Bhote Koshi Evidence Sequence": "Последовательность свидетельств: Bhote Koshi",
+ "Nepal Flood Incident": "Наводнение в Непале",
+ "{count} scenes": {
+ "one": "{count} сцена",
+ "few": "{count} сцены",
+ "many": "{count} сцен",
+ "other": "{count} сцены"
+ },
+ "{count} shots": {
+ "one": "{count} кадр",
+ "few": "{count} кадра",
+ "many": "{count} кадров",
+ "other": "{count} кадра"
+ },
+ "{count} data packs": {
+ "one": "{count} пакет данных",
+ "few": "{count} пакета данных",
+ "many": "{count} пакетов данных",
+ "other": "{count} пакета данных"
+ },
+ "{scene} / {pack}: {status}. File: {path}. {attribution} · {license}": "{scene} / {pack}: {status}. Файл: {path}. {attribution} · {license}",
+ "Unavailable layers: {layers}": "Недоступные слои: {layers}",
+ "{bytes} bundled bytes verified. Files stay in memory for this session. Reimport the bundle after reloading the app.": "Проверено байт в архиве: {bytes}. Файлы хранятся в памяти только в этом сеансе. После перезагрузки приложения импортируйте архив снова.",
+ "Review scene import": "Проверка импорта сцены",
+ "Nothing is loaded or changed until you apply this file.": "Ничего не загружается и не меняется, пока вы не примените этот файл.",
+ "Ready to import": "Готово к импорту",
+ "Apply replaces the current project. Export your current project first if you want to keep both.": "Применение заменит текущий проект. Чтобы не потерять его, сначала экспортируйте текущий проект.",
+ "Apply import": "Применить импорт",
+ "Import was not applied. The current project may have changed.": "Импорт не применён. Возможно, текущий проект изменился.",
+ "Select a scene and shot first": "Сначала выберите сцену и кадр",
+ "Edit scene details": "Изменить параметры сцены",
+ "Camera positions use degrees and meters above the ellipsoid. Drafts are validated before they replace your saved scene.": "Положения камеры задаются в градусах и метрах над эллипсоидом. Перед заменой сохранённой сцены черновик проверяется.",
+ "Anchors and data packs": "Якоря и пакеты данных",
+ "Shot camera, timing, packs and actions": "Камера кадра, тайминг, пакеты и действия",
+ "New anchor ID": "ID нового якоря",
+ "Capture camera as anchor": "Сохранить камеру как якорь",
+ "Anchor added to draft": "Якорь добавлен в черновик",
+ "Set move start to current camera": "Начало перелёта — текущая камера",
+ "Move added to draft; destination remains the shot camera": "Перелёт добавлен в черновик; конечной точкой остаётся камера кадра",
+ "Use ordinary flight": "Использовать обычный перелёт",
+ "Invalid shot JSON": "Некорректный JSON кадра",
+ "Apply details": "Применить параметры",
+ "Select a scene first": "Сначала выберите сцену",
+ "Share selected scene": "Поделиться выбранной сценой",
+ "Scene JSON preserves authored settings and attribution. It does not include asset files. Bundles include only pack files you choose here or previously imported bundle files.": "JSON сцены сохраняет авторские настройки и атрибуцию, но не содержит файлов ресурсов. Архив включает только файлы пакетов, выбранные здесь, или файлы ранее импортированных архивов.",
+ "Download scene JSON": "Скачать JSON сцены",
+ "Choose data-pack files": "Выберите файлы пакетов данных",
+ "Or choose a data-pack folder": "Или выберите папку пакета данных",
+ "Download asset bundle": "Скачать архив ресурсов",
+ "Asset bundle downloaded": "Архив ресурсов скачан",
+ "Could not complete this action. Check the file, references and selected assets.": "Не удалось выполнить действие. Проверьте файл, ссылки и выбранные ресурсы.",
+ "RTL-SDR sample stream stopped": "Поток выборок RTL-SDR остановлен",
+ "Switching to {mode}…": "Переключение на {mode}…",
+ "Browser audio is suspended; select FM again to resume it": "Звук в браузере приостановлен; выберите FM ещё раз, чтобы возобновить его",
+ "RTL-SDR gain change failed": "Не удалось изменить усиление RTL-SDR",
+ "Tuned to {mhz} MHz FM": "Настроено на FM {mhz} МГц",
+ "FM signal found at {mhz} MHz": "Найден FM-сигнал на {mhz} МГц",
+ "No FM signal found": "FM-сигнал не найден",
+ "Seek stopped": "Поиск остановлен",
+ "Browser location is unavailable": "Местоположение браузера недоступно",
+ "Receiver location was not granted": "Доступ к местоположению приёмника не предоставлен",
+ "RTL-SDR disconnected": "RTL-SDR отключён",
+ "No RTL-SDR device selected": "Устройство RTL-SDR не выбрано",
+ "WebUSB requires desktop Chrome or Edge on localhost/HTTPS": "Для WebUSB нужен настольный Chrome или Edge на localhost/HTTPS",
+ "RTL-SDR access failed; close other SDR apps and check USB permissions": "Нет доступа к RTL-SDR; закройте другие SDR-приложения и проверьте разрешения USB",
+ "RTL-SDR connection failed": "Не удалось подключить RTL-SDR",
+ "Receiving 1090 MHz ADS-B": "Приём ADS-B на 1090 МГц",
+ "Receiving broadcast FM": "Приём FM-вещания",
+ "Connect an RTL-SDR to begin.": "Подключите RTL-SDR, чтобы начать.",
+ "WebUSB is unavailable in this browser": "WebUSB недоступен в этом браузере",
+ "SDR decoder worker failed": "Сбой обработчика декодера SDR",
+ "WebUSB requires desktop Chrome or Edge": "Для WebUSB нужен настольный Chrome или Edge",
+ "Waiting for an RTL-SDR device…": "Ожидание устройства RTL-SDR…",
+ "Browser audio is suspended; press Connect again to resume it": "Звук в браузере приостановлен; нажмите «Подключить» ещё раз, чтобы возобновить его",
+ "Return map to straight-down view": "Вернуть карту к виду сверху",
+ "Tilt map to oblique view": "Наклонить карту в перспективный вид",
+ "Reset map to north up. Current heading {heading} degrees": "Повернуть карту севером вверх. Текущий курс: {heading}°",
+ "HDG": "КУРС",
+ "PITCH": "ТАНГАЖ",
+ "FOV": "ОБЗОР",
+ "RANGE": "ДАЛЬН.",
+ "HGT": "ВЫС.",
+ "{value} KM/H": "{value} КМ/Ч",
+ "NORMAL": "ОБЫЧНЫЙ",
+ "ANIME": "АНИМЕ",
+ "NOIR": "НУАР",
+ "Rendered globe frames per second · toggle with `": "Кадров глобуса в секунду · переключение клавишей `",
+ "Utilities": "Инструменты",
+ "Other layers": "Другие слои",
+ "Movement": "Движение",
+ "Infrastructure": "Инфраструктура",
+ "Events": "События",
+ "Weather": "Погода",
+ "LOCATED": "ОПРЕДЕЛЕНА",
+ "LOCATE": "ГЕОПОЗИЦИЯ",
+ "IDLE": "ОЖИДАНИЕ",
+ "TUNING": "НАСТРОЙКА",
+ "STREAMING": "ПРИЁМ",
+ "UNSUPPORTED": "НЕ ПОДДЕРЖ.",
+ "waiting for IQ": "ожидание IQ",
+ "{count} messages": {
+ "one": "{count} сообщение",
+ "few": "{count} сообщения",
+ "many": "{count} сообщений",
+ "other": "{count} сообщения"
+ },
+ "DSP {count} blocks": {
+ "one": "DSP {count} блок",
+ "few": "DSP {count} блока",
+ "many": "DSP {count} блоков",
+ "other": "DSP {count} блока"
+ },
+ "DSP waiting": "DSP ожидает",
+ "{level} dBFS audio": "аудио {level} dBFS",
+ "audio signal --": "аудиосигнал --",
+ "audio {state}": "аудио: {state}",
+ "{count} HEARD": {
+ "one": "СЛЫШНО: {count}",
+ "few": "СЛЫШНО: {count}",
+ "many": "СЛЫШНО: {count}",
+ "other": "СЛЫШНО: {count}"
+ },
+ "DISCONNECT": "ОТКЛЮЧИТЬ",
+ "CONNECT": "ПОДКЛЮЧИТЬ",
+ "LOCATING…": "ОПРЕДЕЛЯЮ…",
- "Drag to resize · double-click the header to snap back": "Перетащите, чтобы изменить размер · двойной щелчок по заголовку — вернуть на место",
+ "CH {index} / {total}": "КАН. {index} / {total}",
+ "Station unavailable after directory refresh": "Станция недоступна после обновления каталога",
+ "Clear reading": "Очистить показания",
+ "Earlier observation": "Более раннее наблюдение",
+ "Observed history": "История наблюдений",
+ "Later observation": "Более позднее наблюдение",
+ "Latest": "Последние",
+ "Newest frame per product": "Самый свежий кадр каждого продукта",
+ "Replay observed history": "Воспроизвести историю наблюдений",
+ "S on another day replaces it · × unpins": "S в другой день заменяет его · × открепляет",
+ "← → preview · S shows the focused day": "← → просмотр · S показывает выбранный день",
+ "Recent imagery": "Свежие снимки",
+ "ZOOM IN": "ПРИБЛИЗИТЬ",
+ "Fly in until the view fits the 1,000 km limit": "Приблизьтесь, пока вид не уложится в предел 1000 км",
+ "Imagery days, newest first · arrows move, S or A and B pin": "Дни со снимками, сначала новые · стрелки — перемещение, S или A и B — закрепить",
+ "On the map": "На карте",
+ "Mode": "Режим",
+ "Imagery on Esri · Google 3D returns when cleared": "Подложка: Esri · сброс вернёт Google 3D",
+ "Imagery opacity": "Непрозрачность снимков",
+ "SWAP": "ПОМЕНЯТЬ",
+ "VS BASEMAP": "С ПОДЛОЖКОЙ",
+ "Trade the two sides of the divider": "Поменять местами стороны разделителя",
+ "A / B": "A / B",
+ "Newest low-cloud day for this box · scene cloud, not box cloud": "Самый свежий малооблачный день для этой области · облачность всей сцены, а не области",
+ "Newest day covering this box · cloudier than 20%": "Самый свежий день с покрытием этой области · облачность выше 20%",
+ "SELECT BOX": "ВЫДЕЛИТЬ",
+ "Drag a box on the map (Esc cancels)": "Выделите область на карте (Esc — отмена)",
+ "Newest day with imagery for this box · partial coverage": "Самый свежий день со снимками этой области · частичное покрытие",
+ "USE VIEW": "ПО ВИДУ",
+ "Use the current view as the box": "Использовать текущий вид как область",
+ "Newest daily overview for this box": "Самый свежий ежедневный обзор для этой области",
+ "Forget the box and its images": "Сбросить область и её снимки",
+ "newest clear day": "самый свежий ясный день",
+ "newest day (cloudy)": "самый свежий день (облачно)",
+ "newest day (partial coverage)": "самый свежий день (частичное покрытие)",
+ "START HERE": "НАЧНИТЕ ЗДЕСЬ",
+ "newest overview": "самый свежий обзор",
+ "No imagery": "Нет снимков",
+ "Checking": "Проверка",
+ "Loading": "Загрузка",
+ "PREVIEW": "ПРОСМОТР",
+ "Newest day with imagery for this box": "Самый свежий день со снимками этой области",
+ "SHOW": "ПОКАЗАТЬ",
+ "Pin {day} as {slot}": "Закрепить {day} как {slot}",
+ "Show {day}": "Показать {day}",
+ "pinned {slot}": "закреплено как {slot}",
+ "shown": "показано",
+ "preview": "просмотр",
+ "start here": "начните здесь",
+ "No box": "Нет области",
+ "Searching": "Поиск",
+ "Every day is empty here": "Здесь все дни пустые",
+ "Sources off": "Источники выключены",
+ "VS": "СРАВН.",
+ "Not set": "Не задано",
+ "Basemap": "Подложка",
+ "Source off": "Источник выключен",
+ "Unpin {slot}": "Открепить {slot}",
+ "Unpin the image": "Открепить снимок",
+ "EXPORT {slot}": "ЭКСП. {slot}",
+ "EXPORT": "ЭКСПОРТ",
+ "Download {slot} as a PNG": "Скачать {slot} в PNG",
+ "Download the image as a PNG": "Скачать снимок в PNG",
+ "Box {width} × {height} km": "Область {width} × {height} км",
+ "no imagery": "нет снимков",
+ "Acquired {time}": "Снято {time}",
+ "cloud unknown": "облачность неизвестна",
+ "Coverage {coverage}": "Покрытие {coverage}",
+ "unknown": "неизвестно",
+ "START HERE · {reason}": "НАЧНИТЕ ЗДЕСЬ · {reason}",
+ "Daily overview shows little detail in a box this small": "В такой маленькой области ежедневный обзор почти не показывает деталей",
+ "{percent}% cloud": "облачность {percent}%",
+ "Imagery: NASA GIBS and Worldview · HLS (Sentinel-2, Landsat 8/9) and VIIRS": "Снимки: NASA GIBS и Worldview · HLS (Sentinel‑2, Landsat 8/9) и VIIRS",
+ "{min}–{max}% cloud": "облачность {min}–{max}%",
+ "Details": "Подробности",
+ "Times, coverage, sources": "Время, покрытие, источники",
+ "HIDE EMPTY DAYS": "СКРЫТЬ ПУСТЫЕ ДНИ",
+ "SHOW EMPTY DAYS · {count}": "ПОКАЗАТЬ ПУСТЫЕ ДНИ · {count}",
+ "Days the probe found empty in this box": "Дни, в которые проверка не нашла снимков в этой области",
+ "NO BOX": "НЕТ ОБЛАСТИ",
+ "image": "снимок",
+ "BASEMAP": "ПОДЛОЖКА",
+ "The basemap": "Подложка",
+ "basemap": "подложка",
+ "SEARCHING": "ПОИСК",
+ "{count} DAYS": {
+ "one": "{count} ДЕНЬ",
+ "few": "{count} ДНЯ",
+ "many": "{count} ДНЕЙ",
+ "other": "{count} ДНЯ"
+ },
+ "Recent imagery against the basemap divider": "Разделитель: свежие снимки и подложка",
+ "Recent imagery A and B divider": "Разделитель свежих снимков A и B",
+ "{before} {left} percent, {after} {right} percent": "{before}: {left}%, {after}: {right}%",
+ "Zoom in or draw a smaller box": "Приблизьте карту или выделите область поменьше",
+ "Select a box or use the view": "Выделите область или используйте текущий вид",
+ "Searching the last 30 days": "Поиск за последние 30 дней",
+ "No days to show for this box": "Для этой области нечего показать",
+ "Drag the divider · SWAP trades sides": "Тяните разделитель · «ПОМЕНЯТЬ» — смена сторон",
+ "Export failed · {error}": "Ошибка экспорта · {error}",
+ "← → preview · A or B pins the focused day": "← → просмотр · A или B закрепляет выбранный день",
+ "← → preview the other side · A or B pins it": "← → просмотр другой стороны · A или B закрепляет её",
+ "LOAD": "ЗАГРУЗИТЬ",
+ "No shots yet. Use CAPTURE SHOT to save current look.": "Кадров пока нет. Нажмите «СДЕЛАТЬ КАДР», чтобы сохранить текущий вид.",
+ "Double-click to rename": "Дважды щёлкните, чтобы переименовать",
+ "Shot name": "Название кадра",
+ "RETRYING ALPR CAMERAS": "ПОВТОРНАЯ ЗАГРУЗКА КАМЕР ALPR",
+ "FETCHING ALPR CAMERAS": "ЗАГРУЗКА КАМЕР ALPR",
+ "OVERPASS TEMPORARILY UNAVAILABLE": "OVERPASS ВРЕМЕННО НЕДОСТУПЕН",
+ "Weather data by Open-Meteo.com": "Данные о погоде: Open-Meteo.com",
+ "ESC EXIT": "ESC ВЫХОД",
+ "C TOGGLE": "C ПЕРЕКЛ.",
+ "SIG": "СИГН.",
+ "NEWS": "НОВОСТИ",
+ "LOCAL": "МЕСТН.",
+ "Cockpit briefing pages": "Страницы брифинга кабины",
+ "MM": "ММ",
+ "KTS": "УЗ",
+ "FT": "ФТ",
+ "FLT": "РЕЙСЫ",
+ "MIL": "ВОЕН.",
+ "SITE": "ОБЪЕКТЫ",
+ "WX": "ПОГОДА",
+ "DIRECTORY: RADIO BROWSER": "КАТАЛОГ: RADIO BROWSER",
+ "Use your location for faster ADS-B position decoding": "Использовать ваше местоположение для ускорения декодирования позиций ADS-B",
+ "CHANGE DEVICE": "СМЕНИТЬ",
+ "Choose a different RTL-SDR or receiver channel": "Выбрать другой RTL-SDR или канал приёмника",
+ "TUNE": "НАСТРОИТЬ",
+ "◀ SEEK": "◀ ПОИСК",
+ "SEEK ▶": "ПОИСК ▶",
+ "Local RTL-SDR receiver": "Локальный приёмник RTL-SDR",
+ "RTL-SDR receiver mode": "Режим приёмника RTL-SDR",
+ "Seek broadcast FM stations": "Поиск FM-радиостанций",
+ "Tune available internet radio stations": "Настройка на доступные интернет-радиостанции",
+ "Local SDR volume": "Громкость локального SDR",
+ "GAIN": "УСИЛЕНИЕ",
+ "FM MHZ": "FM МГЦ",
+ "AUTO": "АВТО",
+ "Chrome/Edge · WebUSB · one local tuner shared by FM and the Local ADS-B layer.": "Chrome/Edge · WebUSB · один локальный тюнер для FM и слоя «Локальный ADS-B».",
+ "RTL-SDR tuner gain for the current mode": "Усиление тюнера RTL-SDR для текущего режима",
+ "WEATHER": "ПОГОДА",
+ "Active weather products": "Активные погодные продукты",
+ "RECENT IMAGERY": "СВЕЖИЕ СНИМКИ",
+ "Imagery days in the box": "Дни со снимками в области",
+ "MSG/S": "СООБЩ./С",
+ "HEARD": "СЛЫШНО",
+ "POSITIONED": "С КООРД.",
+ "SDR VOL": "ГРОМК. SDR",
+ "LOCAL RTL-SDR": "ЛОКАЛЬНЫЙ RTL-SDR",
+ "Cyber sonar contact scanner": "Кибер-сонар: сканер контактов",
+ "Sonar ring count": "Число колец сонара",
+ "Sonar ring range": "Дальность колец сонара",
+ "Sonar intensity": "Интенсивность сонара",
+ "Cyber contact and label opacity": "Непрозрачность контактов и подписей в режиме «Кибер»",
+ "Minimum opacity for map dots, icons, models, brackets, and labels between sonar passes": "Минимальная непрозрачность точек, значков, моделей, рамок и подписей на карте между проходами сонара",
+ "Sonar sector width": "Ширина сектора сонара",
+ "Rings": "Кольца",
+ "Range": "Дальность",
+ "Power": "Мощность",
+ "Opacity": "Непрозрачность",
+ "Sector": "Сектор",
+ "Cyber": "Кибер",
+ "Sonar": "Сонар",
+ "Turn Street Level on or off": "Включить или выключить «Уличные снимки»",
+ "Toggle straight-down and tilted map views": "Переключить вид карты: сверху или с наклоном",
+ "Reset map to north up": "Повернуть карту севером вверх",
+ "Reset map bearing to north": "Сбросить азимут карты на север",
+ "Rain radar": "Радар осадков",
+ "Lightning density": "Плотность молний",
+ "LATEST · newest per product": "ПОСЛЕДНИЕ · самые свежие по каждому продукту",
+ "Forecast · valid {valid} · issued {issued}": "Прогноз · действует на {valid} · выпущен {issued}",
+ "{detail} · Does not follow history": "{detail} · не следует за историей",
+ "Forecast · valid {valid}": "Прогноз · действует на {valid}",
+ "{time} · {minutes} min ago": "{time} · {minutes} мин назад",
+ "Active weather": "Активные погодные слои",
+ "MINI": "МИНИ",
+ "STD": "СТД",
+ "standard": "стандартную",
+ "mini": "мини",
+ "COST UNKNOWN": "СТОИМОСТЬ НЕИЗВЕСТНА",
+ "ChatGPT OAuth session: {responses} response(s), {input} input and {output} output tokens, {captions} caption transcription(s) reported.": "Сессия ChatGPT OAuth: ответов — {responses}, входных токенов — {input}, выходных токенов — {output}, транскрипций субтитров — {captions}.",
+ "USD cost and the API spend cap are unavailable for this auth mode.": "Стоимость в USD и лимит расходов API недоступны в этом режиме авторизации.",
+ "Usage is incomplete because a response was still in flight when the session ended.": "Данные об использовании неполные: к моменту завершения сессии один из ответов ещё не был получен.",
+ "Toggle voice control": "Включить или выключить голосовое управление",
+ "Activate to toggle voice": "Активируйте, чтобы включить или выключить голос",
+ "Voice active": "Голос активен",
+ "Voice could not be started.": "Не удалось запустить голос.",
+ "degraded": "с перебоями",
+ "stale": "устарел",
+ "partial": "частично",
+ "fallback": "резерв",
+ "unavailable": "недоступен",
+ "{label} on": "{label}: вкл.",
+ "{label} off": "{label}: выкл.",
+ "Frame aircraft": "Показать самолёты в кадре",
+ "Frame military aircraft": "Показать военные самолёты в кадре",
+ "Frame ships": "Показать суда в кадре",
+ "Frame satellites": "Показать спутники в кадре",
+ "Frame contacts": "Показать контакты в кадре",
+ "{count} aircraft in frame": {
+ "one": "{count} самолёт в кадре",
+ "few": "{count} самолёта в кадре",
+ "many": "{count} самолётов в кадре",
+ "other": "{count} самолёта в кадре"
+ },
+ "{count} military aircraft in frame": {
+ "one": "{count} военный самолёт в кадре",
+ "few": "{count} военных самолёта в кадре",
+ "many": "{count} военных самолётов в кадре",
+ "other": "{count} военного самолёта в кадре"
+ },
+ "{count} ships in frame": {
+ "one": "{count} судно в кадре",
+ "few": "{count} судна в кадре",
+ "many": "{count} судов в кадре",
+ "other": "{count} судна в кадре"
+ },
+ "{count} satellites in frame": {
+ "one": "{count} спутник в кадре",
+ "few": "{count} спутника в кадре",
+ "many": "{count} спутников в кадре",
+ "other": "{count} спутника в кадре"
+ },
+ "{count} contacts in frame": {
+ "one": "{count} контакт в кадре",
+ "few": "{count} контакта в кадре",
+ "many": "{count} контактов в кадре",
+ "other": "{count} контакта в кадре"
+ },
+ "Nearest military aircraft": "Ближайшие военные самолёты",
+ "Nearest ships": "Ближайшие суда",
+ "Nearest satellites": "Ближайшие спутники",
+ "Nearest aircraft": "Ближайшие самолёты",
+ "{first} and {second}": "{first} и {second}",
+ "Camera range {range}": "Дальность камеры: {range}",
+ "Within {radius} of the view": "В радиусе {radius} от вида",
+ "Labels on": "Подписи включены",
+ "Framing uses the nearest 80 loaded contacts": "В кадр берутся 80 ближайших загруженных контактов",
+ "{distance} from {location}": "{location}: {distance}",
+ "Altitude {altitude}": "Высота {altitude}",
+ "{origin} to {destination}": "{origin} → {destination}",
+ "from {origin}": "откуда: {origin}",
+ "to {destination}": "куда: {destination}",
+ "Registration {registration}": "Регистрационный номер: {registration}",
+ "Route {route}": "Маршрут {route}",
+ "View state": "Состояние вида",
+ "Marked {count} places": {
+ "one": "Отмечено {count} место",
+ "few": "Отмечено {count} места",
+ "many": "Отмечено {count} мест",
+ "other": "Отмечено {count} места"
+ },
+ "Nothing marked": "Ничего не отмечено",
+ "Not found: {places}": "Не найдено: {places}",
+ "Tracing outlines": "Построение контуров",
+ "Mark the map": "Отметить на карте",
+ "Mark {targets} +{more}": "Отметить {targets} +{more}",
+ "Mark {targets}": "Отметить {targets}",
+ "Fly to {place}": "Перелёт: {place}",
+ "Nearest aircraft to {place}": "Ближайший самолёт: {place}",
+ "Read the view": "Осмотреть видимую область",
+ "Check view state": "Проверить состояние вида",
+ "Frame {target}": "Показать в кадре: {target}",
+ "Finding places": "Поиск мест",
+ "Tracing outline": "Построение контура",
+ "Looking up place": "Поиск места",
+ "Flying": "Перелёт",
+ "Turning on layer": "Включение слоя",
+ "Loading aircraft": "Загрузка самолётов",
+ "Picking nearest": "Выбор ближайших",
+ "Working": "Выполняется",
+ "{value} feet": "{value} фт",
+ "nominal": "в норме",
+ "Source: {label}": "Источник: {label}",
+ "N": "С",
+ "NNE": "ССВ",
+ "NE": "СВ",
+ "ENE": "ВСВ",
+ "E": "В",
+ "ESE": "ВЮВ",
+ "SE": "ЮВ",
+ "SSE": "ЮЮВ",
+ "S": "Ю",
+ "SSW": "ЮЮЗ",
+ "SW": "ЮЗ",
+ "WSW": "ЗЮЗ",
+ "W": "З",
+ "WNW": "ЗСЗ",
+ "NW": "СЗ",
+ "NNW": "ССЗ",
+ "Local ADS-B": "Локальный ADS-B",
+ "Transit": "Общественный транспорт",
+ "Recent Imagery": "Свежие снимки",
+ "Fire Perimeters": "Контуры пожаров",
+ "Cyclone advisories": "Сводки о циклонах",
+ "EDIT DETAILS": "ИЗМЕНИТЬ ПАРАМЕТРЫ",
+ "SHARE SCENE": "ПОДЕЛИТЬСЯ СЦЕНОЙ",
+ "ON/OFF": "ВКЛ/ВЫКЛ",
+ "Voice assistant": "Голосовой ассистент",
+ "VOICE": "ГОЛОС",
+ "Dismiss voice card": "Закрыть карточку голоса",
+ "YOU": "ВЫ",
+ "THIS": "ЭТО",
+ "HERE": "ЗДЕСЬ",
+ "Plan": "План",
+ "Referenced items": "Упомянутые объекты",
+ "NOTES & SOURCES": "ЗАМЕТКИ И ИСТОЧНИКИ",
+ "ΔN": "ΔС",
+ "ΔE": "ΔВ",
+ "action|CLEAR": "СБРОСИТЬ",
+ "ALPR Cameras": "Камеры ALPR",
+ "Military aircraft": "Военные самолёты",
+ "Vessels": "Суда",
+ "CCTV + Street View fallback": "CCTV + резерв: Просмотр улиц",
+ "OpenStreetMap + optional Google Maps Places": "OpenStreetMap + Google Maps Places (опц.)",
+ "GFS / ECMWF IFS · FORECAST": "GFS / ECMWF IFS · ПРОГНОЗ",
+ "NOAA nowCOAST · OBSERVED": "NOAA nowCOAST · НАБЛЮДЕНИЕ",
+ "NASA FIRMS · LIVE": "NASA FIRMS · ОНЛАЙН",
+ "data source|Local": "Локальные данные",
+ "overview": "обзор",
+ "{percent}% scene cloud": "облачность сцены {percent}%",
+ "{min}–{max}% scene cloud": "облачность сцены {min}–{max}%",
+ "Sentinel-2 via HLS": "Sentinel‑2 через HLS",
+ "Landsat 8/9 via HLS": "Landsat 8/9 через HLS",
+ "coverage|full": "полное",
+ "coverage|partial": "частичное",
+ "m": "м",
+ "km/h": "км/ч",
+ "m/s": "м/с",
+ "mph": "миль/ч",
+ "hPa": "гПа",
+ "kt": "уз",
+ "km": "км",
+ "h": "ч",
+ "min": "мин",
+ "s": "с",
+ "direction|left": "налево",
+ "direction|right": "направо",
+ "direction|slightly left": "плавно налево",
+ "direction|slightly right": "плавно направо",
+ "direction|sharply left": "резко налево",
+ "direction|sharply right": "резко направо",
+ "direction|straight": "прямо",
+ "direction|around": "в обратную сторону",
+ "ordinal|{number}st": "{number}-й",
+ "ordinal|{number}nd": "{number}-й",
+ "ordinal|{number}rd": "{number}-й",
+ "ordinal|{number}th": "{number}-й",
+ "Head out on {road}": "Начните движение по {road}",
+ "Head out": "Начните движение",
+ "Arrive at your destination": "Вы прибыли в пункт назначения",
+ "Arrive at your destination, on the left": "Пункт назначения слева",
+ "Arrive at your destination, on the right": "Пункт назначения справа",
+ "Make a U-turn": "Развернитесь",
+ "Make a U-turn onto {road}": "Развернитесь на {road}",
+ "Continue straight": "Продолжайте прямо",
+ "Continue straight onto {road}": "Продолжайте движение прямо по {road}",
+ "Turn {direction}": "Поверните {direction}",
+ "Turn {direction} onto {road}": "Поверните {direction} на {road}",
+ "maneuver|Turn": "Поверните",
+ "Turn onto {road}": "Поверните на {road}",
+ "Continue {direction}": "Продолжайте движение {direction}",
+ "Continue {direction} onto {road}": "Продолжайте движение {direction} по {road}",
+ "maneuver|Continue": "Продолжайте движение",
+ "Continue onto {road}": "Продолжайте движение по {road}",
+ "At the end of the road, turn {direction}": "В конце дороги поверните {direction}",
+ "At the end of the road, turn {direction} onto {road}": "В конце дороги поверните {direction} на {road}",
+ "At the end of the road, continue": "В конце дороги продолжайте движение",
+ "At the end of the road, continue onto {road}": "В конце дороги продолжайте движение по {road}",
+ "Keep {direction} at the fork": "На развилке держитесь {direction}",
+ "Keep {direction} at the fork onto {road}": "На развилке держитесь {direction}, чтобы выехать на {road}",
+ "Continue at the fork": "На развилке продолжайте движение",
+ "Continue at the fork onto {road}": "На развилке продолжайте движение по {road}",
+ "Merge {direction}": "Перестройтесь {direction}",
+ "Merge {direction} onto {road}": "Перестройтесь {direction} на {road}",
+ "maneuver|Merge": "Перестройтесь",
+ "Merge onto {road}": "Въезжайте на {road}",
+ "Take the ramp on the {direction}": "Въезжайте на съезд {direction}",
+ "Take the ramp on the {direction} onto {road}": "Въезжайте по съезду {direction} на {road}",
+ "Take the ramp": "Въезжайте на съезд",
+ "Take the ramp onto {road}": "Въезжайте по съезду на {road}",
+ "Take the exit on the {direction}": "Сверните на съезд {direction}",
+ "Take the exit on the {direction} onto {road}": "Сверните на съезд {direction} на {road}",
+ "Take the exit": "Сверните на съезд",
+ "Take the exit onto {road}": "Сверните на съезд на {road}",
+ "At the roundabout, take the {exit} exit": "На кольце сверните на {exit} съезд",
+ "At the roundabout, take the {exit} exit onto {road}": "На кольце сверните на {exit} съезд на {road}",
+ "Enter the roundabout": "Въезжайте на кольцо",
+ "Enter the roundabout onto {road}": "Въезжайте на кольцо, выезд на {road}",
+ "At the roundabout, turn {direction}": "На кольце поверните {direction}",
+ "At the roundabout, turn {direction} onto {road}": "На кольце поверните {direction} на {road}",
+ "At the roundabout, continue": "На кольце продолжайте движение",
+ "At the roundabout, continue onto {road}": "На кольце продолжайте движение по {road}",
+ "Exit the roundabout": "Съезжайте с кольца",
+ "Exit the roundabout onto {road}": "Съезжайте с кольца на {road}",
+ "Use the {direction} lane": "Займите {direction} полосу",
+ "Use the {direction} lane onto {road}": "Займите {direction} полосу, чтобы выехать на {road}",
+ "voice|OFF": "ВЫКЛ",
+ "voice|CONNECTING": "СВЯЗЬ…",
+ "voice|LISTENING": "СЛУШАЮ",
+ "voice|EXECUTING": "ДЕЛАЮ",
+ "voice|ERROR": "ОШИБКА",
+ "MIC": "МИК",
+ "WORKING": "В РАБОТЕ",
+ "DONE": "ГОТОВО",
+ "Outline traced": "Контур построен",
+ "Outline unavailable": "Контур недоступен",
+ "in progress": "выполняется",
+ "done": "готово",
+ "failed": "ошибка",
+ "cancelled": "отменено",
+ "view band|STREET": "УЛИЦА",
+ "view band|CITY": "ГОРОД",
+ "view band|METRO": "АГЛОМЕРАЦИЯ",
+ "view band|REGIONAL": "РЕГИОН",
+ "view band|GLOBAL": "ПЛАНЕТА",
+ "NEAR {poi} ({city}) {distance}": "РЯДОМ: {poi} ({city}) {distance}",
+ "SECTOR {lat} {lon}": "СЕКТОР {lat} {lon}",
+ "ARCTIC": "АРКТИКА",
+ "ANTARCTIC": "АНТАРКТИКА",
+ "NORTH AMERICA": "СЕВЕРНАЯ АМЕРИКА",
+ "SOUTH AMERICA": "ЮЖНАЯ АМЕРИКА",
+ "EUROPE": "ЕВРОПА",
+ "AFRICA": "АФРИКА",
+ "ASIA": "АЗИЯ",
+ "OCEANIA": "ОКЕАНИЯ",
+ "NORTHERN OCEANIC GRID": "СЕВЕРНАЯ ОКЕАНСКАЯ СЕТКА",
+ "SOUTHERN OCEANIC GRID": "ЮЖНАЯ ОКЕАНСКАЯ СЕТКА",
+ "N/A": "Н/Д",
+ "{label} · {radius} AIR/SEA WINDOW": "{label} · ОКНО ВОЗДУХ/МОРЕ {radius}",
+ "{scope} · INSTALLATIONS {coverage}": "{scope} · ОБЪЕКТЫ: {coverage}",
+ "{source} · LOCATION QUERY · RECENT": "{source} · ЗАПРОС ПО МЕСТУ · НЕДАВНИЕ",
+ "ft": "фт",
+ "kts": "уз",
+ "PAUSE": "ПАУЗА",
+ "RESUME": "ПРОДОЛЖ.",
+ "dB": "дБ",
+ "radio|NEWS": "НОВОСТИ",
+ "radio|TALK": "ТОК-РАДИО",
+ "radio|WEATHER": "ПОГОДА",
+ "radio|SAFETY": "БЕЗОПАСНОСТЬ",
+ "radio|AIR / SEA": "АВИА / МОРЕ",
+ "radio|TRANSIT": "ТРАНСПОРТ",
+ "radio|MUSIC": "МУЗЫКА",
+ "radio|OTHER": "ДРУГОЕ",
+ "SNAPSHOT": "СНИМОК",
+ "LIVE": "ОНЛАЙН",
+ "UPSTREAM": "ИСТОЧНИК",
+ "SYNTHETIC": "СИМУЛЯЦИЯ",
+ "CONFIGURED": "НАСТРОЕН",
+ "SEED": "КАТАЛОГ",
+ "Live HLS connected": "Поток HLS подключён",
+ "Live HLS unavailable": "Поток HLS недоступен",
+ "No stream URL configured": "URL потока не настроен",
+ "Live stream connected": "Прямой поток подключён",
+ "Snapshot feed connected": "Поток снимков подключён",
+ "Media fetch failed": "Не удалось получить медиа",
+ "Upstream snapshot active": "Снимок с источника активен",
+ "Fallback Street View frame": "Резервный кадр из Просмотра улиц",
+ "Upstream unavailable": "Источник недоступен",
+ "No source configured": "Источник не настроен",
+ "Upstream HTTP {status}": "Источник: HTTP {status}",
+ "Unexpected media type {type}": "Неожиданный тип медиа: {type}",
+ "Configured source": "Настроенный источник",
+ "Synthetic fallback": "Синтетический резерв",
+ "Cancel": "Отмена",
+ "Choose files": "Выбрать файлы",
+ "No file chosen": "Файлы не выбраны",
+ "{count} files selected": {
+ "one": "Выбрано файлов: {count}",
+ "few": "Выбрано файлов: {count}",
+ "many": "Выбрано файлов: {count}",
+ "other": "Выбрано файлов: {count}"
+ },
+ "Rasuwagadhi witness video": "Видео очевидца в Rasuwagadhi",
+ "Bhote Koshi valley footage": "Съёмка долины Bhote Koshi",
+ "Flood footage": "Съёмка паводка",
+ "Compilation and casualty claims": "Подборка видео и сообщения о жертвах",
+ "SOURCE GEOCONFIRMED · WORLD-PINNED": "МЕСТО СЪЁМКИ ПОДТВЕРЖДЕНО · ОТМЕЧЕНО НА КАРТЕ",
+ "SOURCE CREDITED · LOCATION UNRESOLVED": "АВТОР УКАЗАН · МЕСТО НЕ УСТАНОВЛЕНО",
+ "REFERENCE ONLY · CLAIMS UNVERIFIED": "ТОЛЬКО ДЛЯ СПРАВКИ · ЗАЯВЛЕНИЯ НЕ ПРОВЕРЕНЫ",
+ "SOURCE GEOCONFIRMED": "МЕСТО СЪЁМКИ ПОДТВЕРЖДЕНО",
+ "2021 historical reference versus 2026 post-event imagery; changes are cumulative and include the July 2025 Rasuwagadhi flood. Schematic downstream progression, not modeled arrival time; not an official hazard model.": "Исторический снимок 2021 года в сравнении со снимками 2026 года после события; изменения показаны суммарно за весь период и включают паводок в Rasuwagadhi в июле 2025 года. Схематическое продвижение вниз по течению, а не смоделированное время добегания паводка; не официальная модель опасности.",
+ "Immediate collapse viewpoint": "Точка обзора у места обрушения",
+ "Collapse viewpoint": "Вид на обрушение",
+ "Debris-dammed lake": "Озеро, запруженное обломками",
+ "Dammed lake": "Запрудное озеро",
+ "Second landslide": "Второй оползень",
+ "Gyirong border gate": "Погранпереход Gyirong",
+ "Border gate": "Погранпереход",
+ "Timure evidence cluster": "Группа свидетельств у Timure",
+ "Mailung / Upper Trishuli bridge": "Mailung / мост Upper Trishuli",
+ "Dandagaun viewpoint restaurant": "Ресторан со смотровой площадкой, Dandagaun",
+ "Dandagaun viewpoint": "Смотровая площадка Dandagaun",
+ "Bidur - Trishuli bridge": "Мост Bidur — Trishuli",
+ "Bidur bridge": "Мост Bidur",
+ "Devighat / Taadi Khola Bridge": "Devighat / мост Taadi Khola",
+ "Devighat bridge": "Мост Devighat",
+ "Global Incident Context": "Глобальный контекст инцидента",
+ "Nepal-Focused Globe Rotation": "Поворот глобуса к Непалу",
+ "Bhote Koshi Regional Approach": "Подлёт к региону Bhote Koshi",
+ "Bhote Koshi Nearby Cities": "Города рядом с Bhote Koshi",
+ "Bhote Koshi Incident Corridor": "Коридор инцидента на Bhote Koshi",
+ "Bhote Koshi Flood Path": "Путь паводка на Bhote Koshi",
+ "Bhote Koshi Corridor Overview": "Обзор коридора Bhote Koshi",
+ "Bhote Koshi Upper Valley": "Верхняя долина Bhote Koshi",
+ "Upper Valley Collapse": "Обрушение в верхней долине",
+ "Debris-Dammed Lake": "Озеро, запруженное обломками",
+ "Nepal-China Border Gate": "Погранпереход Непал — Китай",
+ "Timure Evidence Cluster": "Группа свидетельств у Timure",
+ "Syabru Besi Passage": "Прохождение через Syabru Besi",
+ "Bidur / Trishuli Consequence": "Последствия в Bidur / Trishuli",
+ "Final view": "Финальный вид",
+ "{year} HISTORICAL REFERENCE": "{year} ИСТОРИЧЕСКИЙ СНИМОК",
+ "{year} POST-EVENT": "{year} ПОСЛЕ СОБЫТИЯ",
+ "Esri map unavailable · no swipe": "Карта Esri недоступна · без сравнения",
+ "Swipe needs a globe map": "Для сравнения нужна карта-глобус",
+ "Imagery stays on Esri · CLEAR to use Google 3D": "Снимки остаются на Esri · «СБРОСИТЬ», чтобы вернуть Google 3D",
+ "Box and images cleared": "Область и снимки сброшены",
+ "Box is {size} wide · limit {limit}": "Область шириной {size} · предел {limit}",
+ "View is {size} wide · limit {limit}": "Вид шириной {size} · предел {limit}",
+ "Frame unavailable; previous observation retained": "Кадр недоступен; показано предыдущее наблюдение",
+ "Weather imagery unavailable": "Погодные снимки недоступны",
+ "Weather source unavailable; previous observation retained": "Источник погоды недоступен; показано предыдущее наблюдение",
+ "Weather unavailable": "Погода недоступна",
+ "Weather tiles unavailable · previous frame retained": "Погодные тайлы недоступны · показан предыдущий кадр",
+ "Some weather tiles unavailable": "Часть погодных тайлов недоступна",
+ "Hidden by this map source · choose a globe map": "Скрыто этим источником карты · выберите глобус",
+ "Wind source unavailable": "Источник ветра недоступен",
+ "Globe imagery unavailable": "Снимки глобуса недоступны",
+ "Globe field image unavailable": "Изображение поля на глобусе недоступно",
+ "status chip|UNAVAILABLE": "НЕДОСТ.",
+ "Uses registered content or linked media. Those external files are not included in a scene bundle. Their original notices still apply.": "Используется зарегистрированный контент или связанные медиафайлы. Эти внешние файлы не входят в архив сцены. Их исходные условия использования по-прежнему действуют.",
+ "{state} {layers}": "{state}: {layers}",
+ "Selected Space Mission": "Выбранная космическая миссия",
+ "{duration}s + {hold}s": "{duration} с + {hold} с",
+ "Configured Source": "Настроенный источник",
+ "subject": "объект",
+ "{value}m": "{value} м",
+ "Google 3D tiles unavailable — check the key's API restrictions, quota, or network": "Тайлы Google 3D недоступны — проверьте ограничения API ключа, квоту или сеть",
+ "Needs {envVars} — add it in Provider Settings — or a Cesium ion token for the ion-hosted route": "Нужен {envVars} — добавьте его в «Настройках провайдеров» — или токен Cesium ion для варианта через ion",
+ "Comparison in use by another scene": "Сравнение занято другой сценой",
+ "A location reading needs a loaded forecast and the Earth at the center of the view.": "Чтобы получить данные в точке, загрузите прогноз и поместите Землю в центр экрана.",
+ "{mode} {band} {locality} | {region} | ALT {alt} | WINDOW {window} | SUN {sun}° | ONA {ona}° | {zone}": "{mode} · {band} · {locality} | {region} | ALT {alt} | ОКНО {window} | SUN {sun}° | ONA {ona}° | {zone}",
+ "light {source} to use your {name} key": "включите {source}, чтобы использовать свой ключ {name}",
+ "light {source}": "включите {source}",
+ ", or ": ", или ",
+ "{requirement}, or {offer}": "{requirement}, или {offer}",
+ "The photorealistic 3D planet, place search + Street View": "Фотореалистичная 3D-планета, поиск мест + Просмотр улиц",
+ "{name} needs the Google 3D map: choose it under MAP SOURCE": "{name}: нужна карта Google 3D — выберите её в разделе «ИСТОЧНИК КАРТЫ»",
+ "zoom in to a street to open {name}": "приблизьтесь к улице, чтобы открыть {name}",
+ "Google Street View": "Google Просмотр улиц",
+ "GOOGLE STREET VIEW": "GOOGLE ПРОСМОТР УЛИЦ",
+ "Google refused GOOGLE_MAPS_API_KEY for Street View — check that the Maps JavaScript API is enabled for it and this site is an allowed referrer": "Google отклонил GOOGLE_MAPS_API_KEY для Просмотра улиц — проверьте, что для ключа включён Maps JavaScript API, а адрес этого сайта есть в списке разрешённых (HTTP referrer)",
+ "Street View did not answer — check the network, and that the Maps JavaScript API is enabled for GOOGLE_MAPS_API_KEY": "Просмотр улиц не ответил — проверьте сеть и что для GOOGLE_MAPS_API_KEY включён Maps JavaScript API",
+ "click a street to open Street View": "щёлкните по улице, чтобы открыть Просмотр улиц",
+ " or ": " или ",
+ "OPEN {labels}": "ОТКРЫТЬ {labels}",
+ "Open {names} at the centre of the view": "Открыть {names} в центре вида",
+ "Zoom in to a street to open {names} here": "Приблизьтесь к улице, чтобы открыть здесь {names}",
+ "radio tag|All": "Все",
+ "Alternative": "Альтернатива",
+ "Ambient": "Эмбиент",
+ "Blues": "Блюз",
+ "Classical": "Классика",
+ "Country": "Кантри",
+ "Dance": "Танцевальная",
+ "Electronic": "Электроника",
+ "Folk": "Фолк",
+ "Funk": "Фанк",
+ "Hip-Hop": "Хип-хоп",
+ "House": "Хаус",
+ "Indie": "Инди",
+ "Jazz": "Джаз",
+ "Latin": "Латиноамериканская",
+ "Metal": "Метал",
+ "Oldies": "Ретро",
+ "Pop": "Поп",
+ "Punk": "Панк",
+ "R&B": "R&B",
+ "Reggae": "Регги",
+ "Rock": "Рок",
+ "Soul": "Соул",
+ "Techno": "Техно",
+ "Trance": "Транс",
+ "World": "Музыка мира",
+ "{speed}KT": "{speed} УЗ",
+ "{heading}DEG": "{heading}°",
+ "At least {count}": "Не менее {count}",
+ "Named areas ({n})": "Именованные зоны ({n})",
+ "{distance} FLIGHT / VESSEL WINDOW": "РАДИУС РЕЙСОВ / СУДОВ {distance}",
+ "mapped matches within {km} km of the subject": "совпадения на карте в радиусе {km} км от объекта",
+ "none mapped within {km} km; not a complete 250 km survey": "на карте нет в радиусе {km} км; это не полный обзор 250 км",
+ "mapped matches from the loaded viewport": "совпадения на карте в загруженной области",
+ "viewport feed is not a complete 250 km survey": "данные видимой области — не полный обзор 250 км",
+ "fork direction|left": "левее",
+ "fork direction|right": "правее",
+ "fork direction|slightly left": "чуть левее",
+ "fork direction|slightly right": "чуть правее",
+ "fork direction|sharply left": "левее",
+ "fork direction|sharply right": "правее",
+ "fork direction|straight": "прямо",
+ "lane direction|left": "левую",
+ "lane direction|right": "правую",
+ "lane direction|slightly left": "левую",
+ "lane direction|slightly right": "правую",
+ "lane direction|sharply left": "крайнюю левую",
+ "lane direction|sharply right": "крайнюю правую",
+ "lane direction|straight": "среднюю",
+ "{value}°N": "{value}° с. ш.",
+ "{value}°S": "{value}° ю. ш.",
+ "{value}°E": "{value}° в. д.",
+ "{value}°W": "{value}° з. д.",
+ "installation class|AIRFIELD": "АЭРОДРОМ",
+ "installation class|NAVAL BASE": "ВОЕННО-МОРСКАЯ БАЗА",
+ "installation class|RANGE": "ПОЛИГОН",
+ "installation class|MILITARY LAND": "ВОЕННАЯ ТЕРРИТОРИЯ",
+ "installation class|BASE": "БАЗА",
+ "installation class|PLACES CANDIDATE": "ИЗ GOOGLE PLACES",
+ "installation class|INSTALLATION": "ОБЪЕКТ",
+ "fire confidence|high": "высокая",
+ "fire confidence|nominal": "средняя",
+ "fire confidence|low": "низкая",
+ "age|<1h": "<1 ч",
+ "age|{count}h": "{count} ч",
+ "age|{count}d": "{count} д",
+ "General emergency": "Общая авария",
+ "Unlawful interference": "Незаконное вмешательство",
+ "Radio failure": "Отказ радиосвязи",
+ "Downed aircraft": "Вынужденная посадка",
+ "Minimum fuel": "Минимум топлива",
+ "Lifeguard (medical priority)": "Санитарный рейс (медицинский приоритет)",
+ "That file is not valid JSON.": "Этот файл — некорректный JSON.",
+ "That JSON file is not GeoJSON.": "Этот файл JSON не является GeoJSON.",
+ "That FeatureCollection has no features list.": "В этой FeatureCollection нет списка features.",
+ "Every GeoJSON feature must have type Feature.": "У каждого объекта GeoJSON должен быть тип Feature.",
+ "That GeoJSON has invalid geometries.": "В этом GeoJSON некорректные геометрии.",
+ "That GeoJSON contains an unsupported geometry.": "В этом GeoJSON есть неподдерживаемая геометрия.",
+ "That GeoJSON has invalid coordinates.": "В этом GeoJSON некорректные координаты.",
+ "That file creates more than {limit} map objects (the limit).": "Файл создаёт больше объектов на карте, чем позволяет лимит: {limit}.",
+ "That file has more than {limit} style definitions and image links after cleanup (the limit).": "После очистки в файле больше стилей и ссылок на изображения, чем позволяет лимит: {limit}.",
+ "That file has more than {limit} features (the limit).": "В файле больше объектов, чем позволяет лимит: {limit}.",
+ "That file has more than {limit} points (the limit) across {features} features.": "В файле больше точек, чем позволяет лимит: {limit} (объектов: {features}).",
+ "That file has more than {limit} points (the limit).": "В файле больше точек, чем позволяет лимит: {limit}.",
+ "That KMZ unpacks to more than the import limit.": "После распаковки этот KMZ превышает лимит импорта.",
+ "That KMZ is damaged and could not be unpacked.": "Этот KMZ повреждён, распаковать его не удалось.",
+ "That KMZ is not a readable zip archive.": "Этот KMZ — не читаемый zip-архив.",
+ "That KMZ uses a zip format this import does not read.": "Этот KMZ использует формат zip, который импорт не читает.",
+ "That KMZ is encrypted.": "Этот KMZ зашифрован.",
+ "That KMZ uses a compression method this import does not read.": "Этот KMZ использует метод сжатия, который импорт не читает.",
+ "That KML has invalid geometry bounds.": "В этом KML некорректные границы геометрии.",
+ "That KML has invalid coordinates.": "В этом KML некорректные координаты.",
+ "That GPX file has no <gpx> document.": "В этом файле GPX нет документа <gpx>.",
+ "That {format} file is not valid XML.": "Этот файл {format} — некорректный XML.",
+ "That file has an unreadable image or exceeds the 16-megapixel image limit.": "В файле есть нечитаемое изображение или изображение больше лимита в 16 мегапикселей.",
+ "That KML could not be read.": "Не удалось прочитать этот KML.",
+ "That file has invalid point coordinates.": "В файле некорректные координаты точек.",
+ "Ground heights are not available for that file. Try again when the map has loaded.": "Высоты рельефа для этого файла недоступны. Попробуйте ещё раз, когда карта загрузится.",
+ "That file took too long to read.": "Файл читался слишком долго.",
+ "Nothing to import.": "Нечего импортировать.",
+ "That file is larger than {size} MiB.": "Файл больше {size} МиБ.",
+ "Only GeoJSON, KML, KMZ and GPX files can be imported.": "Импортировать можно только файлы GeoJSON, KML, KMZ и GPX.",
+ "That file has nothing to draw.": "В файле нечего показать на карте.",
+ "That KMZ holds no KML document.": "В этом KMZ нет документа KML.",
+ "That {format} file could not be read.": "Не удалось прочитать этот файл {format}.",
+ "That file has {count} map objects; the limit is {limit}.": "Объектов на карте в файле: {count}; лимит: {limit}.",
+ "Ground heights could not be read. Try that file again.": "Не удалось получить высоты рельефа. Попробуйте импортировать файл ещё раз.",
+ "That file has invalid point graphics.": "В файле некорректное оформление точек.",
+ "Low-accuracy score < 2%": "Доля неточных < 2%",
+ "Low-accuracy score 2–10%": "Доля неточных 2–10%",
+ "Low-accuracy score > 10%": "Доля неточных > 10%",
+ "GNSS integrity source unavailable": "Источник целостности GNSS недоступен",
+ "Regional sample · 250 nm radius · cells from visited views over 30 min": "Региональная выборка · радиус 250 мор. миль · ячейки из просмотренных видов за 30 мин",
+ "Retrying automatically at {time} UTC": "Автоматический повтор в {time} UTC",
+ "Retrying automatically after provider cooldown": "Автоматический повтор после паузы провайдера",
+ "Updates automatically after pan or zoom and once a minute. The public feed covers a 250-nautical-mile circle around the view centre; zooming out does not make it a worldwide snapshot. Blank cells are outside sampled coverage or have insufficient observations.": "Обновляется автоматически после сдвига или масштабирования карты и раз в минуту. Публичный поток данных охватывает круг радиусом 250 морских миль вокруг центра вида; при отдалении карта не становится снимком всего мира. Пустые ячейки — вне охвата выборки или с недостаточным числом наблюдений.",
+ "Low-accuracy score = 100 × max(0, bad − 1) / total: one aircraft is discounted, so this is not the raw share. Cells need {aircraft} aircraft over {minutes} minutes. Navigation-integrity anomalies are not a detection of jamming or spoofing.": "Доля неточных = 100 × max(0, неточные − 1) / всего: один самолёт не учитывается, поэтому это не прямая доля. Для ячейки нужно самолётов: {aircraft} за {minutes} мин. Аномалии целостности навигации — не обнаружение глушения или подмены сигнала.",
+ "SQUAWK {code} · {status}": "СКВОК {code} · {status}",
+ "ADS-B PRIORITY · {status}": "ADS-B ПРИОРИТЕТ · {status}",
+ "ADS-B EMERGENCY · {status}": "ADS-B АВАРИЯ · {status}",
+ "{aircraftClass} · {emergency} · {feedState}": "{aircraftClass} · {emergency} · {feedState}",
+ "Ground heights could not be refreshed. Try the file again when the map has loaded.": "Не удалось обновить высоты рельефа. Попробуйте импортировать файл ещё раз, когда карта загрузится.",
+ "{count} map objects": {
+ "one": "{count} объект на карте",
+ "few": "{count} объекта на карте",
+ "many": "{count} объектов на карте",
+ "other": "{count} объекта на карте"
+ },
+ ", drawn with its own styles": ", со своими стилями",
+ "Hide {name}": "Скрыть: {name}",
+ "Show {name}": "Показать: {name}",
+ "Fly to {name}": "Перелёт: {name}",
+ "Remove {name}": "Удалить: {name}",
+ "At most {count} files at once — remove one first.": "Не больше {count} файлов одновременно — сначала удалите один.",
+ "Reading {name}…": "Чтение: {name}…",
+ "That file could not be read.": "Не удалось прочитать этот файл.",
+ "Added {count} files.": {
+ "one": "Добавлен {count} файл.",
+ "few": "Добавлено {count} файла.",
+ "many": "Добавлено {count} файлов.",
+ "other": "Добавлено {count} файла."
+ },
+ "{count} files could not be added ({name}: {error})": {
+ "one": "Не удалось добавить {count} файл ({name}: {error})",
+ "few": "Не удалось добавить {count} файла ({name}: {error})",
+ "many": "Не удалось добавить {count} файлов ({name}: {error})",
+ "other": "Не удалось добавить {count} файла ({name}: {error})"
+ },
+ "Some KML content was left out.": "Часть содержимого KML пропущена.",
+ "GNSS Integrity": "Целостность GNSS",
+ "Show your own GeoJSON, KML, KMZ or GPX files on the globe (or drop them onto it). File bytes stay on this device; overlays can appear in map screenshots shared with voice.": "Показать на глобусе свои файлы GeoJSON, KML, KMZ или GPX (или перетащите их на глобус). Содержимое файлов остаётся на этом устройстве; наложения могут попасть в снимки карты, которые передаются голосовому ассистенту.",
+ "Import": "Импорт",
+ "Choose GeoJSON, KML, KMZ or GPX files": "Выберите файлы GeoJSON, KML, KMZ или GPX",
+ "Imported files": "Импортированные файлы",
+ "DOCKED · {name}": "СТЫКОВКА · {name}",
+ "DOCKED · {name} · +{extra}": "СТЫКОВКА · {name} · +{extra}",
+ "loading coverage...": "загрузка покрытия...",
+ "live feed unavailable": "поток в реальном времени недоступен",
+ "GBFS fetch error": "ошибка загрузки GBFS",
+ "Open the Street Level panel to view imagery": "Откройте панель «Уличные снимки», чтобы их посмотреть",
+ "Image could not be opened": "Не удалось открыть снимок",
+ "Mapillary rejected MAPILLARY_CLIENT_TOKEN — replace it in Provider Settings": "Mapillary отклонил MAPILLARY_CLIENT_TOKEN — замените его в «Настройках провайдеров»",
+ "Coverage requests are being rate-limited — they resume on their own": "Запросы покрытия ограничены по частоте — они возобновятся сами",
+ "No street-level imagery within {radius} m of that point": "В радиусе {radius} м от этой точки уличных снимков нет",
+ "No street-level imagery within {radius} m of the view centre": "В радиусе {radius} м от центра вида уличных снимков нет",
+ "Aim the middle of the view at a street to look for imagery there": "Наведите центр вида на улицу, чтобы поискать там снимки",
+ "Street View has no imagery for this place": "В Просмотре улиц нет снимков этого места",
+ "GOOGLE_MAPS_API_KEY is not set": "GOOGLE_MAPS_API_KEY не задан",
+ "The Google Maps JavaScript API could not load": "Не удалось загрузить Google Maps JavaScript API",
+ "Weather request timed out": "Истекло время ожидания запроса погоды",
+ "Malformed weather manifest": "Некорректный манифест погоды",
+ "Weather HTTP {status}": "Погода: HTTP {status}",
+ "Weather image HTTP {status}": "Снимок погоды: HTTP {status}",
+ "Weather prefetch unavailable": "Предзагрузка погоды недоступна",
+ "Infrared decode failed": "Не удалось декодировать инфракрасный снимок",
+ "rate limited": "превышен лимит запросов",
+ "routing service is rate limited": "сервис маршрутизации превысил лимит запросов",
+ "route leg too long": "участок маршрута слишком длинный",
+ "route too long": "маршрут слишком длинный",
+ "Routing is rate limited — try again in a moment": "Построение маршрута: превышен лимит запросов — попробуйте ещё раз чуть позже",
+ "{error} — try again in a moment": "{error} — попробуйте ещё раз чуть позже",
+ "Routing unavailable (HTTP {status})": "Построение маршрута недоступно (HTTP {status})",
+ "CelesTrak unreachable": "CelesTrak недоступен",
+ "KartaView is rate-limiting requests — they resume on their own": "KartaView ограничивает частоту запросов — они возобновятся сами",
+ "KartaView’s photos here are archived and cannot be shown": "Фотографии KartaView здесь в архиве, показать их нельзя",
+ "KartaView did not filter this area in time — move the map to ask again": "KartaView не успел отфильтровать эту область — сдвиньте карту, чтобы запросить снова",
+ "None of KartaView’s photos here pass the imagery filter": "Ни одна фотография KartaView здесь не проходит фильтр снимков",
+ "KartaView did not answer in time — try again": "KartaView не ответил вовремя — попробуйте снова",
+ "KartaView could not be reached — check the network": "Не удалось связаться с KartaView — проверьте сеть",
+ "KartaView sent an answer that could not be read": "KartaView прислал ответ, который не удалось прочитать",
+ "KartaView is rate-limiting requests": "KartaView ограничивает частоту запросов",
+ "KartaView is rate-limiting requests — try again in a moment": "KartaView ограничивает частоту запросов — попробуйте ещё раз чуть позже",
+ "KartaView sent too much data": "KartaView прислал слишком много данных",
+ "KartaView has no such photo": "У KartaView нет такой фотографии",
+ "The KartaView photo could not be loaded": "Не удалось загрузить фотографию KartaView",
+ "KartaView has no position for this photo": "У KartaView нет координат этой фотографии",
+ "Map tiles temporarily unavailable": "Тайлы карты временно недоступны",
+ "Mapped names temporarily unavailable": "Названия объектов временно недоступны",
+ "No mapped sites in view": "В кадре нет объектов",
+ "No mapped sites within {km} km of the contact": "Нет объектов в радиусе {km} км от контакта",
+ "{count} mapped sites in view": {
+ "one": "{count} объект в кадре",
+ "few": "{count} объекта в кадре",
+ "many": "{count} объектов в кадре",
+ "other": "{count} объекта в кадре"
+ },
+ "{count} mapped sites within {km} km of the contact": {
+ "one": "{count} объект в радиусе {km} км от контакта",
+ "few": "{count} объекта в радиусе {km} км от контакта",
+ "many": "{count} объектов в радиусе {km} км от контакта",
+ "other": "{count} объекта в радиусе {km} км от контакта"
+ },
+ "Too many mapped sites in view to list them all": "В кадре слишком много объектов, чтобы перечислить все",
+ "Installation context unavailable": "Контекст объектов недоступен",
+ "Focus vessel {name}, MMSI {mmsi}": "Фокус на судне {name}, MMSI {mmsi}",
+ "Open the USGS initial report for the 26 August 2026 Nepal landslide": "Открыть первичное сообщение USGS об оползне в Непале 26 августа 2026 года",
+ "YouTube source": "Источник YouTube",
+ "Facebook source": "Источник Facebook",
+ "Military airfield": "Военный аэродром",
+ "Naval base": "Военно-морская база",
+ "Firing range": "Стрельбище",
+ "Military land": "Военная территория",
+ "Mapped installation": "Объект на карте",
+ "Military area": "Военная зона",
+ "SIMULATED — {reason}": "СИМУЛЯЦИЯ — {reason}",
+ "TomTom key unavailable": "Ключ TomTom недоступен",
+ "TomTom daily budget reached": "Исчерпан дневной лимит TomTom",
+ "TomTom upstream unreachable": "Сервер TomTom не отвечает",
+ "TomTom flow unavailable": "Поток TomTom недоступен",
+ "API key rejected — check AISSTREAM_API_KEY": "Ключ API отклонён — проверьте AISSTREAM_API_KEY",
+ "feed silent {seconds}s — no AIS data": "нет данных AIS от потока {seconds} с",
+ "feed silent — no AIS data": "нет данных AIS от потока",
+ "feed down — retrying slowly (attempt {attempt})": "поток недоступен — повторяем реже (попытка {attempt})",
+ "feed down — retrying slowly": "поток недоступен — повторяем реже",
+ "reconnecting to feed… (attempt {attempt})": "переподключение к потоку… (попытка {attempt})",
+ "reconnecting to feed…": "переподключение к потоку…",
+ "AISSTREAM_API_KEY not set": "AISSTREAM_API_KEY не задан",
+ "live feed unsupported": "поток в реальном времени не поддерживается",
+ "connecting to feed…": "подключение к потоку…",
+ "feed disconnected": "поток отключён",
+ "feed down": "поток недоступен",
+ "feed idle": "поток простаивает",
+ "AIS live load failed": "Не удалось загрузить AIS в реальном времени",
+ "age|{count}m": "{count} мин",
+ "{acres} ac": {
+ "one": "{acres} акр",
+ "few": "{acres} акра",
+ "many": "{acres} акров",
+ "other": "{acres} акра"
+ },
+ "{percent}% contained": "локализован на {percent}%",
+ "containment unknown": "локализация неизвестна",
+ "{cause} cause": "причина: {cause}",
+ "{personnel} personnel": {
+ "one": "{personnel} человек",
+ "few": "{personnel} человека",
+ "many": "{personnel} человек",
+ "other": "{personnel} человека"
+ },
+ "{county} County": "округ {county}",
+ "{cost} to date": "{cost} на сегодня",
+ "discovered {age} ago": "обнаружен {age} назад",
+ "updated {age} ago": "обновлён {age} назад",
+ "part of {complex}": "входит в {complex}",
+ "InciWeb ↗ · click card to open": "InciWeb ↗ · нажмите на карточку, чтобы открыть",
+ "FIRE · {name}": "ПОЖАР · {name}",
+ "Unnamed incident": "Без названия",
+ "Open {title} on InciWeb": "Открыть {title} в InciWeb",
+ "Vehicle {vehicle}": "Борт {vehicle}",
+ "Bus": "Автобус",
+ "Tram": "Трамвай",
+ "Subway": "Метро",
+ "Train": "Поезд",
+ "Ferry": "Паром",
+ "Transit vehicle": "Общественный транспорт",
+ "No recent fix": "Нет свежих координат",
+ "Waiting for update": "Ожидание обновления",
+ "Moving": "В движении",
+ "reported {speed} km/h": "по отчёту {speed} км/ч",
+ "reported hdg {heading}°": "по отчёту курс {heading}°",
+ "Last report: stopped at stop {stop}": "Последний отчёт: стоит на остановке {stop}",
+ "Last report: arriving at stop {stop}": "Последний отчёт: прибывает на остановку {stop}",
+ "Last report: next stop {stop}": "Последний отчёт: следующая остановка {stop}",
+ "occupancy|empty": "пусто",
+ "occupancy|many seats available": "много свободных мест",
+ "occupancy|few seats available": "мало свободных мест",
+ "occupancy|standing room only": "только стоячие места",
+ "occupancy|crushed standing room only": "переполнен, только стоя",
+ "occupancy|full": "мест нет",
+ "occupancy|not accepting passengers": "посадки нет",
+ "occupancy|not boardable": "посадка невозможна",
+ "Shown at street level · depth not in the feed": "Показан на уровне улицы · глубины в потоке нет",
+ "Reported {seconds} s ago": "Отчёт {seconds} с назад",
+ "Reported {minutes} min ago": "Отчёт {minutes} мин назад",
+ "{reported} (feed time)": "{reported} (время потока)",
+ "shown {seconds} s behind": "показ отстаёт на {seconds} с",
+ "Available trail: {minutes} min": "Доступный след: {minutes} мин",
+ "Available trail: {minutes} min (limited)": "Доступный след: {minutes} мин (ограничен)",
+ "UNAVAILABLE · {source} · Roads unavailable": "НЕДОСТУПНО · {source} · Дороги недоступны",
+ "Roads: {source}": "Дороги: {source}",
+ "TomTom roads unavailable while the traffic service is unreachable": "Дороги TomTom недоступны, пока сервис трафика не отвечает",
+ "Hybrid unavailable while the traffic service is unreachable": "Гибридный режим недоступен, пока сервис трафика не отвечает",
+ "TomTom roads need a TomTom key": "Для дорог TomTom нужен ключ TomTom",
+ "Hybrid needs a TomTom key": "Для гибридного режима нужен ключ TomTom",
+ "Local surface still loading": "Поверхность под дорогами ещё загружается",
+ "Partial coverage": "Частичное покрытие",
+ "Detailed roads unavailable": "Нет детальных данных о дорогах",
+ "Reduced detail coverage": "Покрытие с меньшей детализацией",
+ "OpenFreeMap tiles rate-limited": "Тайлы OpenFreeMap: превышен лимит запросов",
+ "OpenFreeMap tiles timed out": "Тайлы OpenFreeMap: истекло время ожидания",
+ "OpenFreeMap tiles unavailable": "Тайлы OpenFreeMap недоступны",
+ "Heard by your receiver": "Принято вашим приёмником",
+ "browser SDR": "SDR в браузере",
+ "decoder feed": "поток декодера",
+ "Your RTL-SDR receiver and decoder feed": "Ваш приёмник RTL-SDR и поток декодера",
+ "Your decoder feed": "Ваш поток декодера",
+ "Your RTL-SDR receiver": "Ваш приёмник RTL-SDR",
+ "NO CALLSIGN": "БЕЗ ПОЗЫВНОГО",
+ "ALT {altitude} FT · GS {speed} KT · TRK {track}": "ВЫС. {altitude} ФТ · ПУТ. СКОР. {speed} УЗ · ПУТЬ {track}",
+ "V/S {rate}": "ВЕРТ. СКОР. {rate}",
+ "V/S {rate} FPM": "ВЕРТ. СКОР. {rate} ФТ/МИН",
+ "POSITION {age}": "ПОЗИЦИЯ {age}",
+ "POSITION {seconds} S AGO": "ПОЗИЦИЯ {seconds} С НАЗАД",
+ "{count} MSGS": {
+ "one": "{count} СООБЩЕНИЕ",
+ "few": "{count} СООБЩЕНИЯ",
+ "many": "{count} СООБЩЕНИЙ",
+ "other": "{count} СООБЩЕНИЯ"
+ },
+ "installation class|BARRACKS": "КАЗАРМЫ",
+ "installation class|TRAINING AREA": "УЧЕБНЫЙ ПОЛИГОН",
+ "Seeking up…": "Поиск вверх…",
+ "Seeking down…": "Поиск вниз…",
+ "Scanning {mhz} MHz…": "Сканирование {mhz} МГц…",
+ "Found {mhz} MHz · {snr} dB": "Найдено {mhz} МГц · {snr} дБ",
+ "Broadcaster stream is unavailable or blocked by the browser.": "Поток вещателя недоступен или заблокирован браузером.",
+ "Playback requires a direct click or tap.": "Чтобы начать воспроизведение, нажмите «Пуск».",
+ "Broadcaster stream could not be started.": "Не удалось запустить поток вещателя.",
+ "Directory refresh degraded; showing the previous station catalog.": "Обновление каталога прошло с перебоями; показан предыдущий каталог станций.",
+ "Radio directory coverage is degraded.": "Каталог радиостанций работает с перебоями.",
+ "Directory refresh failed; showing the previous station catalog.": "Не удалось обновить каталог; показан предыдущий каталог станций.",
+ "Radio directory is temporarily unavailable.": "Каталог радиостанций временно недоступен.",
+ "Decoder feeds: {feeds}": "Потоки декодера: {feeds}",
+ " · read while Local ADS-B is on": " · читаются при включённом слое «Локальный ADS-B»",
+ "idle": "ожидание",
+ "running": "работает",
+ "suspended": "приостановлено",
+ "closed": "закрыто",
+ "Local FM stopped: internet radio started": "Локальный FM остановлен: запущено интернет-радио",
+ "ALPR cameras": "камеры ALPR",
+ "OVERPASS RATE-LIMITED": "OVERPASS: ПРЕВЫШЕН ЛИМИТ ЗАПРОСОВ",
+ "OVERPASS TIMED OUT": "OVERPASS: ИСТЕКЛО ВРЕМЯ ОЖИДАНИЯ",
+ "OVERPASS COULD NOT COMPLETE THE QUERY": "OVERPASS: НЕ УДАЛОСЬ ЗАВЕРШИТЬ ЗАПРОС",
+ "MAP TILES TEMPORARILY UNAVAILABLE": "ТАЙЛЫ КАРТЫ ВРЕМЕННО НЕДОСТУПНЫ",
+ "MAPPED NAMES TEMPORARILY UNAVAILABLE": "НАЗВАНИЯ ОБЪЕКТОВ ВРЕМЕННО НЕДОСТУПНЫ",
+ "Shared flight follow expired": "Срок отслеживания рейса по ссылке истёк",
+ "Shared military flight follow expired": "Срок отслеживания военного рейса по ссылке истёк",
+ "Shared satellite follow expired": "Срок отслеживания спутника по ссылке истёк",
+ "Shared flight could not be restored — feed unavailable": "Не удалось восстановить рейс по ссылке — поток данных недоступен",
+ "Shared military flight could not be restored — feed unavailable": "Не удалось восстановить военный рейс по ссылке — поток данных недоступен",
+ "Shared satellite could not be restored — feed unavailable": "Не удалось восстановить спутник по ссылке — поток данных недоступен",
+ "Shared flight is unavailable": "Рейс по ссылке недоступен",
+ "Shared military flight is unavailable": "Военный рейс по ссылке недоступен",
+ "Shared satellite is unavailable": "Спутник по ссылке недоступен",
+ "Scene not saved — browser storage unavailable": "Сцена не сохранена — хранилище браузера недоступно",
+ "Scene not saved — existing saved project could not be read. Export edits or import a valid file.": "Сцена не сохранена — не удалось прочитать сохранённый проект. Экспортируйте правки или импортируйте корректный файл.",
+ "Saved project could not be read; storage preserved. Import a valid file to resume saving.": "Не удалось прочитать сохранённый проект; хранилище не тронуто. Импортируйте корректный файл, чтобы снова сохранять.",
+ "Scene not saved — {reason}": "Сцена не сохранена — {reason}",
+ "Stopped": "Остановлено",
+ "Stopped (Esc)": "Остановлено (Esc)",
+ "Camera ownership changed": "Управление камерой перехвачено",
+ "Scene layer turned off": "Слой сцены выключен",
+ "Seeking scene clock": "Перемотка сцены",
+ "Importing project": "Импорт проекта",
+ "Camera move interrupted": "Перелёт камеры прерван",
+ "Scene media timed out": "Истекло время ожидания медиа сцены",
+ "Space Missions isolates replay data. Exit the mode to enable {layer}.": "Режим «Космические миссии» изолирует данные воспроизведения. Выйдите из режима, чтобы включить слой «{layer}».",
+ "Tilted view": "Вид с наклоном",
+ "Straight-down view": "Вид сверху",
+ "North up": "Север вверху",
+ "Exit cockpit to fly to a camera": "Выйдите из кабины, чтобы перелететь к камере",
+ "Exit cockpit to fly to a location": "Выйдите из кабины, чтобы перелететь к месту",
+ "Exit cockpit to fly to a photo": "Выйдите из кабины, чтобы перелететь к фото",
+ "Exit cockpit to fly to a shared view": "Выйдите из кабины, чтобы перелететь к виду по ссылке",
+ "Exit cockpit to fly to a target": "Выйдите из кабины, чтобы перелететь к цели",
+ "Exit cockpit to fly to a vessel": "Выйдите из кабины, чтобы перелететь к судну",
+ "Exit cockpit to fly to a fire": "Выйдите из кабины, чтобы перелететь к пожару",
+ "Exit cockpit to fly to a route": "Выйдите из кабины, чтобы перелететь к маршруту",
+ "Exit cockpit to fly to a file": "Выйдите из кабины, чтобы перелететь к файлу",
+ "Exit cockpit to fly to a scene": "Выйдите из кабины, чтобы перелететь к сцене",
+ "Go to expanded Radio section": "Перейти к развёрнутому разделу радио",
+ "Expand Radio section in Context": "Развернуть раздел «Радио» в панели «Контекст»",
- "Double-click the header to snap the panel back": "Двойной щелчок по заголовку — вернуть панель на место",
+ "New scene name": "Название новой сцены",
+ "Delete scene \"{scene}\" and all shots?": "Удалить сцену «{scene}» и все кадры?",
+ "Detailed outline unavailable": "Подробный контур недоступен",
+ "Provider Settings does not answer proxied requests": "«Настройки провайдеров» не отвечают на запросы через прокси",
+ "Provider Settings is disabled while sharing is enabled": "«Настройки провайдеров» отключены, пока включён общий доступ",
+ "Provider Settings answers only the machine running the server": "«Настройки провайдеров» отвечают только компьютеру, на котором запущен сервер",
+ "Provider Settings answers only local hostnames": "«Настройки провайдеров» отвечают только на локальные имена хостов",
+ "Provider Settings requires an exact local Origin": "«Настройкам провайдеров» нужен точный локальный Origin",
+ "Unrecognized Origin refused": "Нераспознанный Origin отклонён",
+ "Cross-origin requests are refused": "Запросы с другого источника отклоняются",
+ "Content-Type must be application/json": "Content-Type должен быть application/json",
+ "Method not allowed": "Метод не разрешён",
+ "Request too large": "Слишком большой запрос",
+ "Invalid JSON": "Некорректный JSON",
+ "Body must be a JSON object of {ENV_VAR: value}": "Тело запроса должно быть JSON-объектом вида {ENV_VAR: value}",
+ "No keys provided": "Ключи не переданы",
+ "At most {limit} keys per save": "Ключей за одно сохранение — не больше {limit}",
+ "Unknown key: {name}": "Неизвестный ключ: {name}",
+ "{name} must be a string": "{name}: значение должно быть строкой",
+ "{name} is empty": "{name}: пустое значение",
+ "{name} is longer than any real key ({limit} max)": "{name}: значение длиннее любого настоящего ключа (максимум {limit})",
+ "{name} may only contain printable characters with no spaces": "{name}: допустимы только печатные символы без пробелов",
+ "{name} contains a character that is not valid in a key (#, quotes, $, \\, or backtick)": "{name}: недопустимый для ключа символ (#, кавычки, $, \\ или обратный апостроф)",
+ "{name} is configured outside Provider Settings and can only be changed where it was set": "{name}: задан вне «Настроек провайдеров», изменить его можно только там, где его задали",
+ "The key was not saved: could not restrict the credential file to your account; nothing was saved": "Ключ не сохранён: не удалось закрыть файл учётных данных от всех, кроме вашей учётной записи; ничего не сохранено",
+ "The key was not saved: the existing configuration could not be read, so nothing was changed": "Ключ не сохранён: не удалось прочитать текущую конфигурацию, поэтому ничего не изменено",
+ "Could not write the {store} store": "Не удалось записать хранилище {store}",
+ "Could not check ChatGPT sign-in. Try again.": "Не удалось проверить вход в ChatGPT. Попробуйте ещё раз.",
+ "Cloud voice will use OPENAI_API_KEY on the next session.": "Следующая облачная голосовая сессия будет использовать OPENAI_API_KEY.",
+ "Checking local ChatGPT OAuth sign-in…": "Проверка локального входа в ChatGPT через OAuth…",
+ "Could not check ChatGPT sign-in.": "Не удалось проверить вход в ChatGPT.",
+ "ChatGPT OAuth selected for cloud voice. Your API key stays saved and available.": "Для облачного голоса выбран ChatGPT OAuth. Ваш ключ API остаётся сохранённым и доступным.",
+ "ChatGPT sign-in expired. Opening sign-in again…": "Сеанс ChatGPT истёк. Открываем вход заново…",
+ "Opening ChatGPT sign-in in your browser…": "Открываем вход в ChatGPT в браузере…",
+ "Could not start ChatGPT sign-in on this machine.": "Не удалось начать вход в ChatGPT на этом компьютере.",
+ "Finish ChatGPT sign-in in the browser. Waiting for it to complete…": "Завершите вход в ChatGPT в браузере. Ожидание завершения…",
+ "ChatGPT sign-in timed out. Click {button} to try again.": "Время на вход в ChatGPT истекло. Нажмите «{button}», чтобы попробовать ещё раз.",
+ "ChatGPT sign-in complete. OAuth will be used for the next cloud voice session.": "Вход в ChatGPT выполнен. В следующей облачной голосовой сессии будет использоваться OAuth.",
+ "OAuth check failed: {detail}": "Не удалось проверить OAuth: {detail}",
+ "unsaved CCTV calibration": "несохранённая калибровка CCTV",
+ "the open cockpit": "открытая кабина",
+ "Switching language reloads the page. This will be lost: {items}. Switch anyway?": "Смена языка перезагрузит страницу. Будет потеряно: {items}. Всё равно сменить язык?",
+ "Wind upstream unavailable": "Источник данных о ветре недоступен",
+ "WebUSB needs desktop Chrome or Edge": "Для WebUSB нужен настольный Chrome или Edge",
+ "connect a receiver in Radio": "подключите приёмник в разделе «Радио»",
+ "receiver is in FM mode": "приёмник в режиме FM",
+ "Cyclone advisories unavailable": "Сводки о циклонах недоступны",
+ "Cyclone data unavailable": "Данные о циклонах недоступны",
+ "Drag to size the box": "Потяните, чтобы задать размер области",
+ "Press on the ground, not the sky": "Нажмите на землю, а не на небо",
+ "Point the camera at the ground to use the view": "Наведите камеру на землю, чтобы использовать вид",
+ "That point cannot anchor a box": "От этой точки нельзя построить область",
+ "Box edges must be finite": "Некорректные координаты области",
+ "Longitudes must be within ±180°": "Долгота должна быть в пределах ±180°",
+ "Select one side of the dateline": "Не пересекайте линию перемены дат",
+ "Box must enclose an area": "Область должна иметь площадь",
+ "Imagery stops at ±{limit}° latitude": "Снимки есть только до ±{limit}° широты",
+ "{owner} is using the pointer — close it first": "Указатель занят: «{owner}». Закройте его",
+ "OpenSky OAuth client missing/invalid": "Клиент OAuth OpenSky отсутствует или недействителен",
+ "OpenSky OAuth rejected credentials": "OpenSky OAuth отклонил учётные данные",
+ "OpenSky username/password rejected": "OpenSky отклонил имя пользователя или пароль",
+ "OpenSky auth missing": "Нет данных для входа в OpenSky",
+ "OpenSky auth required": "OpenSky требует входа",
+ "OpenSky auth invalid": "Неверные данные для входа в OpenSky",
+ "OpenSky auth failed": "Не удалось войти в OpenSky",
+ "Source snapshot {minutes} min old": "Возраст снимка источника: {minutes} мин",
+ "{source} rate limited (anonymous)": "{source}: лимит запросов (анонимно)",
+ "{source} rate limited": "{source}: лимит запросов",
+ "{source} HTTP {status}": "{source}: HTTP {status}",
+ "{source} network error": "{source}: ошибка сети",
+ "Malformed {source} aircraft rows": "{source}: некорректные записи о самолётах",
+ "Malformed {source} response": "{source}: некорректный ответ",
+ "Source snapshot time unavailable": "Время снимка источника неизвестно",
+ "Live data unavailable": "Данные в реальном времени недоступны",
+ "{n} aircraft": {
+ "one": "{n} самолёт",
+ "few": "{n} самолёта",
+ "many": "{n} самолётов",
+ "other": "{n} самолёта"
+ },
+ "{n} military aircraft": {
+ "one": "{n} военный самолёт",
+ "few": "{n} военных самолёта",
+ "many": "{n} военных самолётов",
+ "other": "{n} военного самолёта"
+ },
+ "{n} ships": {
+ "one": "{n} судно",
+ "few": "{n} судна",
+ "many": "{n} судов",
+ "other": "{n} судна"
+ },
+ "{n} satellites": {
+ "one": "{n} спутник",
+ "few": "{n} спутника",
+ "many": "{n} спутников",
+ "other": "{n} спутника"
+ },
+ "{n} launches": {
+ "one": "{n} пуск",
+ "few": "{n} пуска",
+ "many": "{n} пусков",
+ "other": "{n} пуска"
+ },
+ "{n} earthquakes": {
+ "one": "{n} землетрясение",
+ "few": "{n} землетрясения",
+ "many": "{n} землетрясений",
+ "other": "{n} землетрясения"
+ },
+ "{n} fires": {
+ "one": "{n} пожар",
+ "few": "{n} пожара",
+ "many": "{n} пожаров",
+ "other": "{n} пожара"
+ },
+ "{n} fire perimeters": {
+ "one": "{n} контур пожара",
+ "few": "{n} контура пожаров",
+ "many": "{n} контуров пожаров",
+ "other": "{n} контура пожаров"
+ },
+ "{n} cyclones": {
+ "one": "{n} циклон",
+ "few": "{n} циклона",
+ "many": "{n} циклонов",
+ "other": "{n} циклона"
+ },
+ "{n} buses": {
+ "one": "{n} автобус",
+ "few": "{n} автобуса",
+ "many": "{n} автобусов",
+ "other": "{n} автобуса"
+ },
+ "{n} bike share": {
+ "one": "{n} станция проката велосипедов",
+ "few": "{n} станции проката велосипедов",
+ "many": "{n} станций проката велосипедов",
+ "other": "{n} станции проката велосипедов"
+ },
+ "{n} flock cameras": {
+ "one": "{n} камера ALPR",
+ "few": "{n} камеры ALPR",
+ "many": "{n} камер ALPR",
+ "other": "{n} камеры ALPR"
+ },
+ "{n} military bases": {
+ "one": "{n} военная база",
+ "few": "{n} военные базы",
+ "many": "{n} военных баз",
+ "other": "{n} военной базы"
+ },
+ "{n} datacenters": {
+ "one": "{n} дата-центр",
+ "few": "{n} дата-центра",
+ "many": "{n} дата-центров",
+ "other": "{n} дата-центра"
+ },
+ "{n} dams": {
+ "one": "{n} плотина",
+ "few": "{n} плотины",
+ "many": "{n} плотин",
+ "other": "{n} плотины"
+ },
+ "{n} results": {
+ "one": "{n} результат",
+ "few": "{n} результата",
+ "many": "{n} результатов",
+ "other": "{n} результата"
+ },
+ "anywhere in the loaded data": "во всех загруженных данных",
+ "in view": "в кадре",
+ "within {radius} of the view centre": "в радиусе {radius} от центра вида",
+ "within {radius} of {place} (Contacts window)": "в радиусе {radius} — {place} (окно «Контактов»)",
+ "within {radius} of {place}": "в радиусе {radius} — {place}",
+ "within {radius}": "в радиусе {radius}",
+ "over {region}": "в регионе {region}",
+ "At least {items}": "{items} или больше",
+ "{items} {scope}": "{items} {scope}",
+ "last 24 h": "за последние 24 ч",
+ "past 30 d and upcoming": "за последние 30 дн. и предстоящие",
+ "the flights layer loads by viewport": "слой рейсов загружается по области вида",
+ "distance is ground distance, not overhead": "расстояние — по поверхности земли до подспутниковой точки, а не до самого аппарата",
+ "the count is a lower bound because at least one layer reached its retained limit.": "это нижняя граница: хотя бы один слой достиг предела хранимых записей.",
+ "{label} loading": "{label}: загрузка",
+ "{label} error": "{label}: ошибка",
+ "counted the first {returned} loaded records": "учтены только первые загруженные записи: {returned}",
+ "counted {returned} of {total} loaded records": "учтено загруженных записей: {returned} из {total}",
+ "{layers} just turned on — still loading, counts will rise": "{layers}: только что включено — данные ещё загружаются, значения вырастут",
+ "Contacts panel snapshot at {time} — the same retained cohort supplies the card, speech, and follow-up memory": "Снимок панели «Контакты» ({time}) — та же сохранённая выборка используется для карточки, речи и памяти уточняющих вопросов",
+ "Contacts panel snapshot — the same retained cohort supplies the card, speech, and follow-up memory": "Снимок панели «Контакты» — та же сохранённая выборка используется для карточки, речи и памяти уточняющих вопросов",
+ "Not answered: {layers}": "Нет ответа: {layers}",
+ "The flights layer is not enabled": "Слой рейсов не включён",
+ "The military layer is not enabled": "Слой военных рейсов не включён",
+ "The satellites layer is not enabled": "Слой спутников не включён",
+ "The ais-live-vessels layer is not enabled": "Слой судов AIS не включён",
+ "Could not enable the requested layer": "Не удалось включить запрошенный слой",
+ "Could not disable the requested layer": "Не удалось выключить запрошенный слой",
+ "Radio layer unavailable": "Слой радио недоступен",
+ "Camera navigation is unavailable in the current view": "Управление камерой недоступно в текущем виде",
+ "Camera navigation policy unavailable": "Правила навигации камеры недоступны",
+ "Nearest-aircraft selection supports Flights or Military Flights only": "Выбор ближайшего самолёта работает только для рейсов и военных рейсов",
+ "Nearest-aircraft selection needs a preset, place name, or latitude and longitude": "Для выбора ближайшего самолёта нужен пресет, название места или широта и долгота",
+ "Could not arrive at the requested place": "Не удалось долететь до запрошенного места",
+ "The nearest airborne aircraft could not be selected": "Не удалось выбрать ближайший самолёт в воздухе",
+ "No flights within {radius} of the current view": "В радиусе {radius} от текущего вида нет рейсов",
+ "No military within {radius} of the current view": "В радиусе {radius} от текущего вида нет военных рейсов",
+ "No satellites within {radius} of the current view": "В радиусе {radius} от текущего вида нет спутников",
+ "No vessels within {radius} of the current view": "В радиусе {radius} от текущего вида нет судов",
+ "{layer} is enabled on the {source} feed, but no airborne aircraft is loaded in the {place} view yet": "{layer}: включено (поток {source}), но в виде «{place}» пока не загружено ни одного самолёта в воздухе",
+ "{layer} is enabled, but no airborne aircraft is loaded in the {place} view yet": "{layer}: включено, но в виде «{place}» пока не загружено ни одного самолёта в воздухе",
+ "{layer} is enabled, but its aircraft feed is unavailable": "{layer}: включено, но поток данных о самолётах недоступен",
+ "{layer} is enabled, but its destination refresh did not complete": "{layer}: включено, но обновление в точке назначения не завершилось",
+ "{layer} is enabled, but {source} is unavailable": "{layer}: включено, но источник {source} недоступен",
+ "Could not arrive at {place}": "Не удалось долететь: {place}",
+ "{name} is no longer loaded": "{name}: объект больше не загружен",
+ "Unknown target layer: {target}": "Неизвестный слой цели: {target}",
+ "Layer": "Слой",
+ "there": "там",
+ "Frame flights": "Показать самолёты в кадре",
+ "Frame military": "Показать военные самолёты в кадре",
+ "Frame vessels": "Показать суда в кадре",
+ "Fly to Location": "Перелёт к месту",
+ "Nearest aircraft to Here": "Ближайший самолёт здесь",
+ "Estimate is incomplete — a response was still in flight when the session ended, so its usage was never reported.": "Оценка неполная: к моменту завершения сессии один из ответов ещё не был получен, поэтому его использование не учтено.",
+ "STANDARD": "СТАНДАРТ",
+ "vehicle motion|Stopped": "Стоит",
+ "ACQUIRING FRAME": "ПОЛУЧЕНИЕ КАДРА",
+ "Camera source temporarily unavailable": "Источник камер временно недоступен",
+ "Perimeter source unavailable": "Источник контуров пожаров недоступен",
+ "Imagery catalog unavailable": "Каталог снимков недоступен",
+ "Earthquake source unavailable": "Источник данных о землетрясениях недоступен",
+ "TeleGeography load failed": "Не удалось загрузить данные TeleGeography",
+ "Wind request timed out": "Истекло время ожидания запроса ветра",
+ "Malformed wind manifest": "Некорректный манифест ветра",
+ "Malformed wind grid": "Некорректная сетка ветра",
+ "Unknown wind model": "Неизвестная модель ветра",
+ "Unknown weather overlay": "Неизвестный погодный слой",
+ "Temperature field unavailable": "Поле температуры недоступно",
+ "Mean sea level pressure field unavailable": "Поле давления на уровне моря недоступно",
+ "KartaView answered HTTP {status}": "KartaView ответил: HTTP {status}",
+ "KartaView refused the request (code {code})": "KartaView отклонил запрос (код {code})",
+ "Stopped by voice": "Остановлено голосовой командой",
+ "drawings on the map": "рисунки на карте",
+ "imported map files": "импортированные файлы на карте",
+ "the active voice session": "активная голосовая сессия",
+ "Light aircraft": "Лёгкий самолёт",
+ "Glider": "Планёр",
+ "Turboprop": "Турбовинтовой самолёт",
+ "Airliner": "Авиалайнер",
+ "Widebody": "Широкофюзеляжный самолёт",
+ "Four-engine jet": "Четырёхмоторный реактивный самолёт",
+ "Helicopter": "Вертолёт",
+ "Fast jet": "Высокоманёвренный самолёт",
+ "Business jet": "Бизнес-джет",
+ "Drone": "Беспилотник",
+ "fire cause|Human": "деятельность человека",
+ "fire cause|Natural": "природная",
+ "fire cause|Undetermined": "не установлена",
+ "fire cause|Unknown": "неизвестна",
+ "fire behavior|Minimal": "минимальная активность",
+ "fire behavior|Moderate": "умеренная активность",
+ "fire behavior|Active": "высокая активность",
+ "fire behavior|Extreme": "экстремальная активность",
+ "Type {level} Incident": "инцидент {level}-го типа",
+ "${amount}K": "{amount} тыс. $",
+ "${amount}M": "{amount} млн $",
+ "${amount}B": "{amount} млрд $",
+ "{speed} kn": "{speed} уз",
+ "1090 MHz": "1090 МГц",
+ "978 MHz UAT": "978 МГц UAT",
+ "feed status|live": "онлайн",
+ "feed status|stale": "устарел",
+ "feed status|unreachable": "недоступен",
+ "feed status|invalid": "некорректный",
+ "Vector tile metadata unavailable": "Метаданные векторных тайлов недоступны",
+ "Vector tiles unavailable": "Векторные тайлы недоступны",
+ "Vector tiles unavailable (HTTP {status})": "Векторные тайлы недоступны (HTTP {status})",
+ "Vector tile request timed out": "Векторные тайлы: истекло время ожидания",
+ "Zoom in for vector tile coverage": "Приблизьте карту, чтобы загрузить векторные тайлы",
+ "Camera coverage unavailable": "Покрытие камер недоступно",
+ "Hybrid": "Гибрид",
+ "TomTom roads only, each with its live flow": "Только дороги TomTom, у каждой — свой поток онлайн",
+ "TomTom roads only, each with its live flow (needs a TomTom key)": "Только дороги TomTom, у каждой — свой поток онлайн (нужен ключ TomTom)",
+ "OpenStreetMap roads, with TomTom flow matched when available": "Дороги OpenStreetMap; поток TomTom сопоставляется, где он есть",
+ "TomTom roads first; OpenStreetMap fills the rest, simulated": "Сначала дороги TomTom; остальное дополняет OpenStreetMap с симуляцией потока",
+ "TomTom roads first; OpenStreetMap fills the rest, simulated (needs a TomTom key)": "Сначала дороги TomTom; остальное дополняет OpenStreetMap с симуляцией потока (нужен ключ TomTom)",
+ "Austin": "Остин",
+ "San Francisco": "Сан-Франциско",
+ "New York": "Нью-Йорк",
+ "Tokyo": "Токио",
+ "London": "Лондон",
+ "Paris": "Париж",
+ "Dubai": "Дубай",
+ "Washington DC": "Вашингтон",
+ "Tallinn": "Таллин",
+ "Los Angeles": "Лос-Анджелес",
+ "Data attribution": "Источники данных",
+ "Data provided by:": "Данные предоставлены:",
+ "Exit cockpit to view weather coverage": "Выйдите из кабины, чтобы показать зону покрытия погодного слоя",
+ "Exit cockpit to fly to a cyclone": "Выйдите из кабины, чтобы перелететь к циклону",
+ "the title of scene {scene} is empty or longer than {max} characters": "название сцены {scene} пустое или длиннее {max} символов",
+ "the title of shot {shot} in scene {scene} is empty or longer than {max} characters": "название кадра {shot} в сцене {scene} пустое или длиннее {max} символов",
+ "the project is larger than 5 MiB": "проект больше 5 МиБ",
+ "the project has too many shots": "в проекте слишком много кадров",
+ "the scene data failed validation": "данные сцены не прошли проверку",
+ "Layer on": "Слой: вкл.",
+ "Layer off": "Слой: выкл.",
+ "Zoom in": "Приблизить",
+ "Zoom out": "Отдалить",
+ "Zoom out to globe": "Отдалить до глобуса",
+ "Open data layers": "Открыть слои данных",
+ "Open or close a panel": "Открыть или закрыть панель",
+ "Change context mode": "Сменить режим контекста",
+ "Control cockpit": "Управлять кабиной",
+ "Change visual style": "Сменить визуальный стиль",
+ "Adjust HUD": "Настроить HUD",
+ "Adjust cyber sonar": "Настроить кибер-сонар",
+ "Adjust detection overlay": "Настроить слой детекции",
+ "Change map stack": "Сменить набор карт",
+ "Adjust post-processing": "Настроить постобработку",
+ "Control scene": "Управлять сценой",
+ "Control CCTV": "Управлять камерами CCTV",
+ "Control radio": "Управлять радио",
+ "Track contact": "Отслеживать контакт",
+ "Stop tracking": "Остановить отслеживание",
+ "Clear marks": "Убрать отметки",
+ "Move camera": "Переместить камеру",
+ "Fly route": "Пролететь по маршруту",
+ "Analyst query": "Аналитический запрос",
+ "Next ISS pass": "Следующий пролёт МКС",
+ "Next satellite pass": "Следующий пролёт спутника",
+ "Action": "Действие",
+ "The photo could not be loaded": "Не удалось загрузить фотографию",
+ "{name} photo. ← and → step along the sequence. On a 360° photo, drag or use Shift+← →, ↑ ↓ to look around, and + − to zoom": "Фотография {name}. ← и → листают съёмку. На 360°-фотографии перетаскивайте или используйте Shift+← →, ↑ ↓ для обзора, + − для масштаба",
+ "{name} street-level photo": "Уличная фотография {name}",
+ "Previous photo in this sequence (←)": "Предыдущая фотография съёмки (←)",
+ "Next photo in this sequence (→)": "Следующая фотография съёмки (→)",
+ "The Panoramax photo could not be loaded": "Не удалось загрузить фотографию Panoramax",
+ "Panoramax is busy — coverage resumes on its own": "Panoramax перегружен — покрытие загрузится само",
+ "no Panoramax photos in view": "фотографий Panoramax в зоне видимости нет",
+ "no Panoramax photos here match the filters": "здесь нет фотографий Panoramax, подходящих под фильтры",
+ "Panoramax sent a map tile that could not be read": "Panoramax прислал тайл карты, который не удалось прочитать",
+ "This Panoramax photo is no longer available": "Эта фотография Panoramax больше недоступна",
+ "zoom in to see Panoramax coverage": "приблизьтесь, чтобы увидеть покрытие Panoramax",
+ "Panoramax did not answer in time — try again": "Panoramax не ответил вовремя — попробуйте снова",
+ "Panoramax could not be reached — check the connection": "Не удалось связаться с Panoramax — проверьте подключение",
+ "Panoramax sent too much data": "Panoramax прислал слишком много данных",
+ "Panoramax is busy": "Panoramax перегружен",
+ "Panoramax sent an unreadable answer": "Panoramax прислал ответ, который не удалось прочитать",
+ "Apply the full cloud brightness key; 100% filter strength": "Применить полный фильтр яркости облаков; сила фильтра 100%",
+ "Show the complete infrared image; 0% filter strength": "Показать полное ИК-изображение; сила фильтра 0%",
+ "FILTER": "ФИЛЬТР",
+ "Cloud filter strength": "Сила фильтра облаков",
+ "Panoramax answered HTTP {status}": "Panoramax ответил: HTTP {status}",
+ "Highest air-quality readings in view": "Наивысшие показатели качества воздуха в поле зрения",
+ "Low": "Низкий",
+ "Moderate": "Умеренный",
+ "High": "Высокий",
+ "Very High": "Очень высокий",
+ "Air quality": "Качество воздуха",
+ "{n} sequences in view · click a line for its nearest photo": {
+ "one": "{n} съёмка в кадре · щёлкните линию, чтобы открыть ближайшую фотографию",
+ "few": "{n} съёмки в кадре · щёлкните линию, чтобы открыть ближайшую фотографию",
+ "many": "{n} съёмок в кадре · щёлкните линию, чтобы открыть ближайшую фотографию",
+ "other": "{n} съёмки в кадре · щёлкните линию, чтобы открыть ближайшую фотографию"
+ },
+ "FOV {value}° (DATASHEET)": "ОБЗОР {value}° (ПО ПАСПОРТУ)",
+ "SPEC FOV {span}° (CAPABILITY)": "ОБЗОР ПО ПАСПОРТУ {span}° (ВОЗМОЖНОСТИ)",
+ "{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · ХАРАКТЕРИСТИКИ: CCTV-DATABASE.COM",
+ "Canada only · ECCC AQHI network": "Только Канада · сеть AQHI ECCC",
+ "{count} stations reporting": {
+ "one": "{count} станция передаёт данные",
+ "few": "{count} станции передают данные",
+ "many": "{count} станций передают данные",
+ "other": "{count} станции передают данные"
+ },
+ "No readings available": "Нет доступных показаний",
+ "No current readings": "Нет актуальных показаний",
+ "Low health risk": "Низкий риск для здоровья",
+ "Moderate health risk": "Умеренный риск для здоровья",
+ "High health risk": "Высокий риск для здоровья",
+ "Very High health risk": "Очень высокий риск для здоровья",
+ "Air quality request failed": "Не удалось запросить данные о качестве воздуха",
+ "ECCC request timed out": "Истекло время ожидания запроса к ECCC",
+ "Malformed AQHI station response": "Некорректный ответ со станциями AQHI",
+ "Malformed AQHI observation response": "Некорректный ответ с наблюдениями AQHI",
+ "No AQHI stations available": "Нет доступных станций AQHI",
+ "{n} air quality": {
+ "one": "{n} станция качества воздуха",
+ "few": "{n} станции качества воздуха",
+ "many": "{n} станций качества воздуха",
+ "other": "{n} станции качества воздуха"
+ },
+ "GNSS feed rate limited (HTTP 429)": "Поток GNSS: превышен лимит запросов (HTTP 429)",
+ "GNSS feed unavailable (HTTP {status})": "Поток GNSS недоступен (HTTP {status})",
+ "GNSS snapshot needs a view anchor": "Для снимка GNSS нужна опорная точка вида",
+ "Malformed GNSS integrity snapshot": "Некорректный снимок целостности GNSS",
+ "GNSS integrity snapshot has no observation time": "В снимке целостности GNSS нет времени наблюдения",
+ "{feed} feed unavailable": "Поток {feed} недоступен",
+ "Loading {feeds}": "Загрузка: {feeds}",
+ "{count} CelesTrak groups unavailable": {
+ "one": "{count} группа CelesTrak недоступна",
+ "few": "{count} группы CelesTrak недоступны",
+ "many": "{count} групп CelesTrak недоступны",
+ "other": "{count} группы CelesTrak недоступны"
+ },
+ "Malformed launch snapshot": "Некорректный снимок запусков",
+ "Malformed perimeter snapshot": "Некорректный снимок периметров",
+ "Overpass returned an incomplete camera response": "Overpass вернул неполный ответ о камерах",
+ "Fly below {km} km to a covered region": "Опуститесь ниже {km} км над регионом с покрытием",
+ "No feed here yet · {n} regions available": {
+ "one": "Здесь пока нет потока данных · доступен {n} регион",
+ "few": "Здесь пока нет потока данных · доступно {n} региона",
+ "many": "Здесь пока нет потока данных · доступно {n} регионов",
+ "other": "Здесь пока нет потока данных · доступно {n} региона"
+ },
+ "Wind speed field unavailable": "Поле скорости ветра недоступно",
+ "Decoder feeds": "Потоки декодера",
+ "WebUSB + decoder feeds": "WebUSB + потоки декодера",
+ "opening receiver": "открытие приёмника",
+ "checking decoder feeds": "проверка потоков декодера",
+ "listening": "приём",
+ "USB error": "ошибка USB",
+ "{count} heard": {
+ "one": "слышно бортов: {count}",
+ "few": "слышно бортов: {count}",
+ "many": "слышно бортов: {count}",
+ "other": "слышно бортов: {count}"
+ },
+ "{rate} msg/s": "{rate} сообщ./с",
+ "USB {rate} msg/s": "USB {rate} сообщ./с",
+ "{count} feeds live": {
+ "one": "{count} поток онлайн",
+ "few": "{count} потока онлайн",
+ "many": "{count} потоков онлайн",
+ "other": "{count} потока онлайн"
+ },
+ "feeds {names} stale": {
+ "one": "поток {names} устарел",
+ "few": "потоки {names} устарели",
+ "many": "потоки {names} устарели",
+ "other": "потоки {names} устарели"
+ },
+ "feeds {names} unreachable": {
+ "one": "поток {names} недоступен",
+ "few": "потоки {names} недоступны",
+ "many": "потоки {names} недоступны",
+ "other": "потоки {names} недоступны"
+ },
+ "feeds {names} invalid": {
+ "one": "поток {names} некорректен",
+ "few": "потоки {names} некорректны",
+ "many": "потоки {names} некорректны",
+ "other": "потоки {names} некорректны"
+ },
+ "unsaved provider keys": "несохранённые ключи провайдеров",
+ "Exit cockpit to fly to an aircraft": "Выйдите из кабины, чтобы перелететь к самолёту",
+ "Exit cockpit to fly to a satellite": "Выйдите из кабины, чтобы перелететь к спутнику",
+ "Exit cockpit to frame contacts": "Выйдите из кабины, чтобы показать контакты в кадре",
+ "{feed} {count} ({seconds}s old)": "{feed} {count} ({seconds} с назад)",
+ "entry {n}": "№ {n}",
+ "Upstream response too large": "Слишком большой ответ источника",
+ "Included in bundle": "Входит в архив",
+ "Missing bundle file — reimport its bundle": "Файла нет в архиве — импортируйте этот архив снова",
+ "Source configured; file checked when loaded": "Источник настроен; файл будет проверен при загрузке",
+ "Source unavailable": "Источник недоступен",
+ "Coverage tile failed": "Не удалось загрузить тайл покрытия",
+ "Unknown": "Неизвестно",
+ "USB work abandoned after a stalled transfer": "Работа с USB прервана: передача данных зависла",
+ "SDR decoder did not start; receiver stopped": "Декодер SDR не запустился; приёмник остановлен",
+ "SDR decoder stopped responding; receiver stopped": "Декодер SDR перестал отвечать; приёмник остановлен",
- "SDR decoder fell behind; receiver stopped": "Декодер SDR не успевает; приёмник остановлен"
++ "SDR decoder fell behind; receiver stopped": "Декодер SDR не успевает; приёмник остановлен",
++ "Zoom in to see street-level coverage": "Приблизьтесь, чтобы увидеть покрытие уличных снимков",
++ "Point the camera at the ground for street-level coverage": "Направьте камеру на землю, чтобы увидеть покрытие уличных снимков",
++ "Sequence images unavailable": "Снимки последовательности недоступны",
++ "Switch Street Level on to draw its coverage.": "Включите Street Level, чтобы показать покрытие.",
++ "Every provider is switched off: light a chip to draw its coverage.": "Все источники выключены: включите один, чтобы показать его покрытие.",
++ "No sequences in view match the filter": "Ни одна последовательность в кадре не подходит под фильтр",
++ "No coverage in view": "В кадре нет покрытия",
++ "Show the street-level view full screen (Esc shrinks it)": "Показать уличный снимок на весь экран (Esc сворачивает)"
+ }
diff --cc src/layers/streetLevel/glyphs.js
index 7410c3291,233a7bdde..803e4b548
--- a/src/layers/streetLevel/glyphs.js
+++ b/src/layers/streetLevel/glyphs.js
@@@ -1,10 -1,16 +1,10 @@@
- /** Billboard glyphs as SVG data URLs: the image cone, the 360° ring and the position marker. */
-/** Canvas billboard glyphs (image cone, pano ring, position marker); no Cesium needed. */
++/** Billboard glyphs as SVG data URLs: the image cone, the 360° ring and the position markers. */
-const _cache = new Map();
+const px = (n) => Number(n.toFixed(2));
-/** A square canvas glyph drawn once per key, centred at (c, c). */
-function cachedGlyph(key, size, draw) {
- if (_cache.has(key)) return _cache.get(key);
- const element = document.createElement('canvas');
- element.width = size;
- element.height = size;
- draw(element.getContext('2d'), size / 2);
- _cache.set(key, element);
- return element;
+function svg(size, body) {
+ const markup = `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">${body}</svg>`;
+ return `data:image/svg+xml;utf8,${encodeURIComponent(markup)}`;
}
/** A filled wedge from the centre, pointing "up", `halfAngle` radians wide. */
@@@ -30,28 -51,34 +30,38 @@@ export function imageConeGlyph(
color = '#e8eaed',
pano = false,
} = {}) {
- return cachedGlyph(`cone:${size}:${color}:${pano}`, size, (ctx, c) => {
- if (pano) ring(ctx, c, size * 0.4, color, Math.max(1.5, size * 0.09), 0.5);
- else wedge(ctx, c, size * 0.46, 0.62, color, 0.42);
- dot(
- ctx,
- c,
- size * 0.16,
- color,
- 'rgba(10,10,15,0.85)',
- Math.max(1, size * 0.05),
- );
- });
+ const shape = pano
+ ? ring(size, size * 0.4, color, Math.max(1.5, size * 0.09), 0.5)
+ : wedge(size, size * 0.46, 0.62, color, 0.42);
+ return svg(
+ size,
+ shape +
+ dot(
+ size,
+ size * 0.16,
+ color,
+ 'rgba(10,10,15,0.85)',
+ Math.max(1, size * 0.05),
+ ),
+ );
}
+ /** Street View-style marker: a field-of-view cone from a white-ringed dot. */
+ export function viewConeMarkerGlyph({ size = 56, color = '#4285f4' } = {}) {
- return cachedGlyph(`view-cone:${size}:${color}`, size, (ctx, c) => {
- wedge(ctx, c, size * 0.48, 0.62, color, 0.38);
- wedge(ctx, c, size * 0.3, 0.62, color, 0.3);
- dot(ctx, c, size * 0.13, color, '#ffffff', Math.max(2, size * 0.05));
- });
++ return svg(
++ size,
++ wedge(size, size * 0.48, 0.62, color, 0.38) +
++ wedge(size, size * 0.3, 0.62, color, 0.3) +
++ dot(size, size * 0.13, color, '#ffffff', Math.max(2, size * 0.05)),
++ );
+ }
+
/** Marker for the image the viewer currently shows. */
export function positionMarkerGlyph({ size = 44, color = '#ffb300' } = {}) {
- return cachedGlyph(`pos:${size}:${color}`, size, (ctx, c) => {
- wedge(ctx, c, size * 0.48, 0.55, color, 0.55);
- dot(ctx, c, size * 0.2, color, '#0a0a0f', 2);
- ring(ctx, c, size * 0.3, color, 1.5, 0.8);
- });
+ return svg(
+ size,
+ wedge(size, size * 0.48, 0.55, color, 0.55) +
+ dot(size, size * 0.2, color, '#0a0a0f', 2) +
+ ring(size, size * 0.3, color, 1.5, 0.8),
+ );
}
diff --cc src/layers/streetLevel/groundClick.js
index 000000000,fef6ddb47..d33791b8a
mode 000000,100644..100644
--- a/src/layers/streetLevel/groundClick.js
+++ b/src/layers/streetLevel/groundClick.js
@@@ -1,0 -1,56 +1,46 @@@
+ import * as Cesium from 'cesium';
+ import { GROUND_CLICK_MAX_HEIGHT_M } from './policy.js';
+ import { cameraHeightAboveGround } from './view.js';
+
+ /** Whether the camera is low enough for a click on the ground to mean a street. */
-export function groundClickHeightOk(viewer, groundAt) {
++export function groundClickHeightOk(viewer) {
+ if (!viewer?.camera?.positionCartographic) return false;
- return (
- cameraHeightAboveGround(viewer, { groundAt }) <= GROUND_CLICK_MAX_HEIGHT_M
- );
++ return cameraHeightAboveGround(viewer) <= GROUND_CLICK_MAX_HEIGHT_M;
+ }
+
+ /**
+ * A click on the map itself at street zoom opens the nearest image of the
+ * active `groundClick` providers, without moving the camera. The height is
+ * measured at the click, not read from the cached flag.
- * @param {{state: object, openNearest: Function, isAvailable: (entry: object) => boolean, groundAt?: Function}} options
++ * @param {{state: object, openNearest: Function, isAvailable: (entry: object) => boolean}} options
+ * @returns {(screenPosition: {x: number, y: number}, picked?: object) => Promise<boolean>|false}
+ */
-export function createGroundClick({
- state,
- openNearest,
- isAvailable,
- groundAt = null,
-}) {
++export function createGroundClick({ state, openNearest, isAvailable }) {
+ return function openAtGround(screenPosition, picked) {
+ const scenePick = state.services.scenePick;
+ if (!state.enabled || !state.viewer || !scenePick?.pickGroundPosition)
+ return false;
- if (
- !scenePick.isSurfacePick(picked) ||
- !groundClickHeightOk(state.viewer, groundAt)
- )
++ if (!scenePick.isSurfacePick(picked) || !groundClickHeightOk(state.viewer))
+ return false;
+ const providerIds = [...state.providers.values()]
+ .filter(
+ (entry) =>
+ entry.on &&
+ entry.def.groundClick &&
+ entry.status?.configured &&
+ isAvailable(entry),
+ )
+ .map((entry) => entry.def.id);
+ if (!providerIds.length) return false;
+ const position = scenePick.pickGroundPosition(state.viewer, screenPosition);
+ const carto = position && Cesium.Cartographic.fromCartesian(position);
+ if (!carto) return false;
+ return openNearest(
+ {
+ lon: Cesium.Math.toDegrees(carto.longitude),
+ lat: Cesium.Math.toDegrees(carto.latitude),
+ },
+ { providerIds, frame: false },
+ );
+ };
+ }
diff --cc src/layers/streetLevel/index.js
index c5a0d3d5c,6e8b9e2d7..9eff511dd
--- a/src/layers/streetLevel/index.js
+++ b/src/layers/streetLevel/index.js
@@@ -1,30 -1,40 +1,41 @@@
+ import * as Cesium from 'cesium';
import { createState } from './state.js';
import { createMarker } from './marker.js';
-import { createCameraFollow } from './cameraFollow.js';
+import { createCameraFraming } from './cameraFraming.js';
import { createCredits } from './credits.js';
import { createPickRouter } from './pickRouter.js';
import { createSelection } from './selection.js';
import { createViewerHost } from './viewerHost.js';
- import { requiresKeyIdFor, validateProviders } from './registry.js';
+ import { filtersOf, requiresKeyIdFor, validateProviders } from './registry.js';
import { normalizeFilter, resolveFilter, sameFilter } from './filter.js';
import { decodeParams, encodeParams } from './params.js';
- import { composeUIState, summarizeCoverage } from './uiState.js';
import {
+ composeUIState,
+ keyAlternatives,
+ summarizeCoverage,
+ } from './uiState.js';
-import { cameraHeightAboveGround, viewCentre, whenIdle } from './view.js';
++import { viewCentre } from './view.js';
+ import { createGroundClick, groundClickHeightOk } from './groundClick.js';
-import { createGroundCaster, nextSurfaceMode } from './groundCast.js';
-import { createMeshSampler } from './meshSampler.js';
+ import { msg, t, translateKnown } from '../../i18n/index.js';
-
-/** Above this camera height the ground under the camera is not worth fetching. */
-const SURFACE_WARM_BELOW_M = 6000;
+ import {
+ AIM_AT_GROUND_MESSAGE,
- FOLLOW_MAP_STACK_ID,
+ keyStatusLabel,
+ NEAREST_RADIUS_M,
POSITION_PICK_ID,
STREET_LEVEL_LAYER_ID,
} from './policy.js';
export { STREET_LEVEL_LAYER_ID } from './policy.js';
+/** Longest wait for a provider's key status; past it, the provider decides. */
+const KEY_STATUS_TIMEOUT_MS = 10_000;
+
/**
* The Street Level layer over imagery providers (contract in registry.js).
- * The core owns what they share; providers own coverage, sequences, viewer.
+ * The core owns what they share: the filter and switches, the photo viewer
- * host, the position marker and the click handler. Providers own coverage,
- * sequences and their viewer.
++ * host, the position marker, the click handler and nearest-image lookups.
++ * Providers own coverage, sequences and their viewer. One source is lit at
++ * a time.
* @param {{providers: Array<import('./registry.js').StreetLevelProvider>, services?: object}} options
*/
export function createStreetLevelLayer({
@@@ -51,6 -74,12 +62,11 @@@
entry.instance.clearSequence?.();
};
parts.selection = createSelection(context);
+ parts.openAtGround = createGroundClick({
+ state,
+ openNearest: (point, options) => layer.openNearest(point, options),
+ isAvailable: (entry) => providerAvailable(entry),
- groundAt: parts.groundCaster?.groundAt ?? null,
+ });
let notifyQueued = false;
function notify() {
@@@ -73,30 -102,169 +89,98 @@@
function providerContext(entry) {
return Object.freeze({
services: state.services,
+ /** Resolved against now, so "since N days" keeps up with the clock. */
getFilter: () => resolveFilter(state.filter),
+ /** The layer and this provider's switch are both on. */
isActive: () => state.enabled && entry.on,
- groundCaster: parts.groundCaster,
- meshSampler: parts.meshSampler,
- getSurface: () => state.surface,
notify,
actions: {
- openImage: (imageId) => openImage(entry.def.id, imageId),
+ /** `{frame: false}` opens it without moving the camera. */
+ openImage: (imageId, options) =>
+ openImage(entry.def.id, imageId, options),
+ /** This provider's image nearest a point the user picked on the map. */
+ openNearest: (point) =>
+ layer.openNearest(point, {
+ providerIds: [entry.def.id],
+ frame: false,
+ }),
+ /**
+ * Show a provider error, or withdraw it (null). A withdrawal clears
+ * only this provider's own error, never a newer one from elsewhere.
+ */
+ reportError: (message) => {
+ if (message) {
+ state.street.error = entry.reportedError = message;
+ } else {
+ if (!entry.reportedError) return;
+ if (state.street.error === entry.reportedError)
+ state.street.error = null;
+ entry.reportedError = null;
+ }
+ notify();
+ },
},
});
}
+ // One source at a time: the first provider that defaults on.
- const startsOn = definitionsFrozen.find((def) => def.defaultOn !== false);
- for (const def of definitionsFrozen) {
++ const startsOn = defs.find((def) => def.defaultOn !== false);
+ for (const def of defs) {
const entry = {
def,
instance: null,
- on: true,
+ on: def === startsOn,
status: null,
+ /** The status request in flight; overlapping checks share it. */
+ statusCheck: null,
+ /** The error this provider last reported, until it withdraws it. */
+ reportedError: null,
};
entry.instance = def.create(providerContext(entry));
state.providers.set(def.id, entry);
}
+ let mapStack = null;
+ let unsubscribeMapStack = null;
+
- /** Follow is offered only on the Google 3D stack; leaving it stops following. */
- function syncFollowAvailability() {
- const available = mapStack?.getActiveId?.() === FOLLOW_MAP_STACK_ID;
- if (available === state.street.followAvailable) return;
- state.street.followAvailable = available;
- if (!available && state.street.follow) parts.follow.setFollow(false);
- notify();
- }
-
+ /** Usable only on its map stack (Google's terms: Street View on Google 3D only). */
+ function providerAvailable(entry) {
+ const required = entry.def.requiresMapStack;
+ return !required || mapStack?.getActiveId?.() === required;
+ }
+
+ /** Leaving a provider's map stack closes its image, viewer and credit. */
+ function syncProviderAvailability() {
+ const owner = state.providers.get(state.street.providerId);
+ if (state.street.open && owner && !providerAvailable(owner))
+ layer.closeViewer();
+ for (const entry of state.providers.values()) {
+ if (!entry.def.requiresMapStack) continue;
+ if (state.enabled && entry.on && providerAvailable(entry))
+ parts.credits.show(state.viewer, entry.def);
+ else {
+ parts.credits.hide(state.viewer, entry.def);
+ parts.viewerHost.unmount(entry.def.id);
+ }
+ }
+ notify();
+ }
+
+ /** Whether a ground click can open an image: the camera is at street zoom. */
+ function syncGroundClickReady() {
- const ready =
- state.enabled &&
- groundClickHeightOk(state.viewer, parts.groundCaster?.groundAt);
++ const ready = state.enabled && groundClickHeightOk(state.viewer);
+ if (ready === state.groundClickReady) return;
+ state.groundClickReady = ready;
+ notify();
+ }
+
- /**
- * Camera height above bare earth, for the surface mode. A cold grid cell is
- * fetched once and the mode rechecked when it lands.
- */
- function cameraHeightForSurface() {
- const carto = state.viewer?.camera?.positionCartographic;
- if (!carto) return null;
- const caster = parts.groundCaster;
- const height = cameraHeightAboveGround(state.viewer, {
- groundAt: caster.groundAt,
- });
- const lon = (carto.longitude * 180) / Math.PI;
- const lat = (carto.latitude * 180) / Math.PI;
- if (caster.groundAt(lon, lat) === null && height < SURFACE_WARM_BELOW_M)
- caster.prepare([[lon, lat]]).then((ready) => {
- if (ready) scheduleSurfaceSync();
- });
- return height;
- }
-
- /** Cast overlays to bare earth on Google 3D at street zoom; drape them elsewhere. */
- function syncSurface() {
- syncGroundClickReady();
- const available = Boolean(parts.groundCaster) && state.enabled;
- const photoreal = mapStack?.getActiveId?.() === FOLLOW_MAP_STACK_ID;
- const mode = nextSurfaceMode(state.surface, {
- available,
- photoreal,
- heightM: available && photoreal ? cameraHeightForSurface() : null,
- });
- if (mode === state.surface) return;
- state.surface = mode;
- parts.meshSampler?.setEnabled(mode === 'terrain');
- parts.marker.setSurface(mode);
- for (const entry of state.providers.values())
- entry.instance.setSurface?.(mode);
- notify();
- }
-
- let surfaceTimer = null;
- function scheduleSurfaceSync() {
- clearTimeout(surfaceTimer);
- surfaceTimer = setTimeout(syncSurface, 150);
- }
-
- let removeSurfaceListeners = null;
- function watchSurface(viewer) {
- removeSurfaceListeners?.();
- const camera = viewer?.camera;
- if (!camera?.changed || !camera?.moveEnd) {
- removeSurfaceListeners = null;
- return;
- }
- const removeChanged = camera.changed.addEventListener(scheduleSurfaceSync);
- const removeEnd = camera.moveEnd.addEventListener(scheduleSurfaceSync);
- removeSurfaceListeners = () => {
- removeChanged();
- removeEnd();
- };
- }
-
- function unwatchSurface() {
- removeSurfaceListeners?.();
- removeSurfaceListeners = null;
- clearTimeout(surfaceTimer);
- surfaceTimer = null;
++ let removeCameraListener = null;
++ function watchCamera(viewer) {
++ removeCameraListener?.();
++ removeCameraListener =
++ viewer?.camera?.moveEnd?.addEventListener(syncGroundClickReady) || null;
+ }
+
const activeEntries = () =>
[...state.providers.values()].filter((entry) => entry.on);
@@@ -120,10 -280,13 +204,10 @@@
function activate(entry) {
if (!state.viewer) return;
entry.instance.activate(state.viewer);
- if (!entry.status) refreshStatus(entry);
- if (!providerAvailable(entry)) return;
-- parts.credits.show(state.viewer, entry.def);
- // The map may have changed by then.
- whenIdle(() => {
- if (providerAvailable(entry)) parts.viewerHost.prewarm([entry]);
- }, 1500);
+ // Without a known key, a switch-on asks again: the server may be back,
+ // or have a key now.
+ if (entry.status?.configured !== true) checkStatus(entry);
++ if (providerAvailable(entry)) parts.credits.show(state.viewer, entry.def);
}
function deactivate(entry) {
@@@ -175,9 -438,14 +359,13 @@@
requiresKeyId: entry.def.requiresKeyId || null,
loading: stats.loading === true,
count: stats.count || 0,
- hint: stats.hint || '',
+ hint: hintFor(entry, stats),
error: stats.error || null,
color: entry.def.colors.coverage,
+ coverageLabel: entry.def.coverageLabel || null,
- highlightsSequence: entry.def.highlightsSequence !== false,
+ sinceBasis: entry.def.sinceBasis === 'upload' ? 'upload' : 'capture',
+ groundClick: entry.def.groundClick === true,
+ filters: [...filtersOf(entry.def)],
};
});
}
@@@ -216,21 -478,40 +405,37 @@@
providers: providerSnapshots(),
street,
sequence: sequenceSnapshot(),
- surface: state.surface,
});
+ // The lit source cannot run on this map: say so, not a blank panel.
+ const stranded = [...state.providers.values()].find(
+ (entry) => entry.on && !providerAvailable(entry),
+ );
+ if (stranded && !ui.providers.some((p) => p.on))
+ ui.coverage.hint = unavailableReason(stranded);
+ return ui;
}
const layer = {
id: STREET_LEVEL_LAYER_ID,
name: 'Street Level',
icon: '📷',
- source: defs.map((def) => def.name).join(' · '),
+ /** The sources usable on this map (Street View only on Google 3D). */
+ get source() {
+ return listedEntries()
+ .map((entry) => entry.def.name)
+ .join(' · ');
+ },
updateInterval: 0,
statsRefreshInterval: 1000,
- requiresKeyId: requiresKeyIdFor(defs),
+ /** The key the switched-on providers share (or null), for the layer row. */
+ get requiresKeyId() {
- const on = [...state.providers.values()].filter((entry) => entry.on);
- return requiresKeyIdFor(
- on.length ? on.map((entry) => entry.def) : definitionsFrozen,
- );
++ const on = activeEntries();
++ return requiresKeyIdFor(on.length ? on.map((entry) => entry.def) : defs);
+ },
/** Registered providers, in chip order. */
- providerIds: definitionsFrozen.map((def) => def.id),
+ providerIds: defs.map((def) => def.id),
getSourceAvailability() {
- const available = definitionsFrozen.length > 0;
+ const available = defs.length > 0;
return {
available,
source: STREET_LEVEL_LAYER_ID,
@@@ -257,13 -541,18 +462,19 @@@
parts.marker.setVisible(true);
parts.selection.install(viewer);
for (const entry of activeEntries()) activate(entry);
- watchSurface(viewer);
- syncSurface();
++ watchCamera(viewer);
++ syncGroundClickReady();
notify();
},
disable() {
state.enabled = false;
+ abortNearest();
- unwatchSurface();
++ removeCameraListener?.();
++ removeCameraListener = null;
parts.viewerHost.unmount();
for (const entry of state.providers.values()) entry.instance.deactivate();
- syncSurface();
++ syncGroundClickReady();
parts.credits.hideAll(state.viewer);
parts.selection.uninstall();
parts.marker.setVisible(false);
@@@ -279,34 -568,70 +490,54 @@@
for (const entry of state.providers.values())
entry.instance.destroy(viewer);
parts.marker.destroy(viewer);
- parts.meshSampler?.destroy();
- parts.follow.destroy();
+ parts.framing.attachNavigation(null);
+ unsubscribeMapStack?.();
+ unsubscribeMapStack = null;
+ mapStack = null;
state.listeners.clear();
state.viewer = null;
- state.initialized = false;
- state.destroyed = true;
},
getStats() {
// The lifecycle polls this every second: summarise, don't snapshot.
- const coverage = summarizeCoverage(providerSnapshots());
++ // English data: the layer panel translates these through translateKnown.
+ const snapshots = providerSnapshots();
+ const coverage = summarizeCoverage(snapshots);
- // English data: the layer panel translates these through translateKnown.
+ const keyLabel = keyStatusLabel(coverage);
let loadingLabel = '';
- const keyLabel = coverage.keyRejected
- ? msg('KEY REJECTED')
- : msg('KEY REQUIRED');
- if (coverage.keyRequired) loadingLabel = keyLabel;
+ if (keyLabel) loadingLabel = keyLabel;
- else if (coverage.loading) loadingLabel = 'loading coverage...';
+ else if (coverage.loading) loadingLabel = msg('loading coverage...');
else if (coverage.hint && state.enabled) loadingLabel = coverage.hint;
return {
+ source: layer.source,
count: coverage.count,
loading: coverage.loading,
keyRequired: coverage.keyRequired,
+ keyAlternatives: keyAlternatives(snapshots),
- error: coverage.keyRequired
+ // A rejected key's message names the fix; a missing one says so.
- error: keyLabel && !coverage.keyRejected ? keyLabel : coverage.error,
++ error: keyLabel
+ ? coverage.keyRejected
+ ? coverage.error || keyLabel
+ : keyLabel
+ : coverage.error,
loadingLabel,
};
},
- /**
- * The application's camera authority: `run(noun, move)`, the deferred
- * `begin(noun)` / `reassert(generation)` pair and
- * `subscribeHandoff(listener)`. FOLLOW claims the camera with `run`; a
- * photo claims it when opening starts and frames only if it still owns
- * it once loaded. FOLLOW stops when another feature takes the camera.
- */
+ /** A photo frames itself only if it still owns the camera once loaded. */
attachNavigation(navigation) {
- parts.follow.attachNavigation(navigation);
+ parts.framing.attachNavigation(navigation);
},
- /** The application map stack; FOLLOW is available only on Google 3D. */
++ /** The application map stack; Street View is usable only on Google 3D. */
+ attachMapStackController(controller) {
+ unsubscribeMapStack?.();
+ mapStack = controller || null;
+ unsubscribeMapStack =
- mapStack?.subscribe?.(() => {
- syncFollowAvailability();
- syncProviderAvailability();
- syncSurface();
- }) || null;
- syncFollowAvailability();
++ mapStack?.subscribe?.(syncProviderAvailability) || null;
+ syncProviderAvailability();
- syncSurface();
+ },
+
/** Share-link and stored state: provider switches plus the filter. */
getParams() {
return encodeParams({
@@@ -336,11 -666,102 +573,92 @@@
/** The DOM element provider viewers render into. */
attachViewerHost(element) {
parts.viewerHost.attach(element);
- if (element && state.enabled)
- whenIdle(
- () =>
- parts.viewerHost.prewarm(
- activeEntries().filter((entry) => providerAvailable(entry)),
- ),
- 1500,
- );
},
setProviderEnabled,
- /** Imagery filter for coverage, cones and nearest-image lookups. */
- setCoverageFilter,
openImage,
+ /**
+ * Open the nearest image of the active providers (or `providerIds`) near
+ * a point, else the view centre, or with `aim: 'screen-centre'` the ground
- * under the screen centre (sky: nothing).
++ * under the screen centre (sky: nothing). Providers without
++ * `nearestImage` are skipped.
+ */
+ async openNearest(
+ point,
+ { providerIds = null, frame = true, aim = 'view' } = {},
+ ) {
+ let view = point;
+ if (!view && aim === 'screen-centre') {
+ view = screenCentreGround();
+ if (view === null) {
+ abortNearest();
+ state.street.loading = false;
+ state.street.error = AIM_AT_GROUND_MESSAGE;
+ notify();
+ return false;
+ }
+ }
+ view ||= viewCentre(state.viewer);
+ if (!Number.isFinite(view?.lat) || !Number.isFinite(view?.lon))
+ return false;
+ abortNearest();
+ const lookup = new AbortController();
+ nearestLookup = lookup;
+ const { signal } = lookup;
+ state.street.loading = true;
+ state.street.error = null;
+ notify();
+ let lastError = null;
+ const asked = (entry) =>
+ (!providerIds || providerIds.includes(entry.def.id)) &&
++ typeof entry.instance.nearestImage === 'function' &&
+ providerAvailable(entry);
+ const entries = activeEntries().filter(asked);
+ for (const entry of entries) {
+ let imageId = null;
+ try {
+ imageId = await entry.instance.nearestImage(
+ { lat: view.lat, lon: view.lon },
+ { signal },
+ );
+ } catch (error) {
+ // Overtaken: whatever replaced it owns the panel, errors included.
+ if (signal.aborted) return false;
+ // One provider failing (no key, offline) must not hide the others.
+ lastError = error;
+ continue;
+ }
+ if (signal.aborted) return false;
+ if (!state.enabled) break;
+ // Switched off, or its map left, while it looked: try the next.
+ if (!imageId || !entry.on || !providerAvailable(entry)) continue;
+ nearestLookup = null;
+ return openImage(entry.def.id, imageId, { frame });
+ }
+ if (nearestLookup === lookup) nearestLookup = null;
+ // Switched off while it looked: nothing to open, nothing to report.
+ const stillOn = entries.some(
+ (entry) => entry.on && providerAvailable(entry),
+ );
+ // A provider's own refusal is English data that the panel translates;
+ // the core's refusal is built here, for the panel only, in the language.
+ if (state.enabled && stillOn)
+ state.street.error =
+ lastError?.message ||
+ (point
+ ? t('No street-level imagery within {radius} m of that point', {
+ radius: NEAREST_RADIUS_M,
+ })
+ : t(
+ 'No street-level imagery within {radius} m of the view centre',
- {
- radius: NEAREST_RADIUS_M,
- },
++ { radius: NEAREST_RADIUS_M },
+ ));
+ state.street.loading = false;
+ notify();
+ return false;
+ },
- /** Close the image and deselect it everywhere on the map. */
+ /** Close the image and deselect its sequence on the map. */
closeViewer() {
+ abortNearest();
parts.viewerHost.close();
parts.clearSequences();
},
diff --cc src/layers/streetLevel/index.test.mjs
index 20c1a5303,d52570c94..cee8a200b
--- a/src/layers/streetLevel/index.test.mjs
+++ b/src/layers/streetLevel/index.test.mjs
@@@ -2,300 -2,963 +2,1059 @@@ import assert from 'node:assert/strict'
import test from 'node:test';
import * as Cesium from 'cesium';
import { createStreetLevelLayer } from './index.js';
- import { createMapillaryProvider } from './mapillaryProvider.js';
- import { MAPILLARY_CREDIT_HTML } from './policy.js';
+ import { MAPILLARY_CREDIT_HTML } from './providers/mapillary/policy.js';
+ import { createMapillaryProvider } from './providers/mapillary/index.js';
+ import { createKartaViewProvider } from './providers/kartaview/index.js';
-import { fakeStreetLevelProvider as fakeProvider } from '../../testSupport/streetLevelFakes.mjs';
+import {
+ fakeCesiumViewer,
+ fakeMapillarySource,
+ fakePhotoViewer,
++ fakeStreetLevelProvider as fakeProvider,
+} from '../../testSupport/streetLevelFakes.mjs';
+ import { setLocale } from '../../i18n/index.js';
+/**
+ * A layer over `source` and `photoViewer`, initialised on a stand-in viewer
+ * and (unless `enable` is false) enabled.
+ */
+async function startLayer(
+ t,
+ {
+ source = fakeMapillarySource(),
+ photoViewer = fakePhotoViewer(),
+ providers = [createMapillaryProvider({ source, photoViewer })],
+ view = false,
+ enable = true,
+ } = {},
+) {
+ const saved = globalThis.document;
+ // The click handler listens for Esc on the document.
+ globalThis.document = new EventTarget();
+ // Skip Cesium's one-time terrain table download for draped lines.
+ t.mock.method(
+ Cesium.GroundPolylinePrimitive,
+ 'initializeTerrainHeights',
+ async () => {},
+ );
+ const viewer = fakeCesiumViewer({ view });
+ const layer = createStreetLevelLayer({ providers });
+ layer.init(viewer);
+ if (enable) layer.enable(viewer);
+ t.after(() => {
+ layer.destroy();
+ globalThis.document = saved;
+ });
+ await settle();
+ return { layer, viewer, source, photoViewer };
+}
+
+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+function deferred() {
+ let resolve;
+ let reject;
+ const promise = new Promise((done, fail) => {
+ resolve = done;
+ reject = fail;
+ });
+ return { promise, resolve, reject };
+}
+
+/** A photo viewer reporting a pose for every image it opens. */
+const posingViewer = () =>
+ fakePhotoViewer({ pose: { position: { lon: -121.49, lat: 38.58 } } });
+
+test('the CC BY-SA credit shows while Mapillary is on and goes with it', async (t) => {
+ const { layer, viewer } = await startLayer(t);
+ const shown = () => viewer.credits.map((credit) => credit.html);
+ assert.deepEqual(shown(), [MAPILLARY_CREDIT_HTML], 'shown on enable');
+ assert.match(shown()[0], /CC BY-SA 4\.0/);
+ layer.setParams({ mapillary: false });
+ assert.deepEqual(shown(), [], 'hidden with the switch');
+ layer.setParams({ mapillary: true });
+ assert.deepEqual(shown(), [MAPILLARY_CREDIT_HTML]);
+ layer.disable();
+ assert.deepEqual(shown(), [], 'the credit goes with the layer');
+});
+
+test('coverage asks for no tiles before the key status is known, and none without a key', async (t) => {
+ for (const configured of [false, true]) {
+ const status = deferred();
+ const source = fakeMapillarySource({ getStatus: () => status.promise });
+ const { layer } = await startLayer(t, { source, view: true });
+ assert.equal(source.calls.tiles.length, 0, 'nothing before the status');
+ status.resolve({ configured });
+ await settle();
+ if (configured) assert.ok(source.calls.tiles.length > 0, 'then coverage');
+ else {
+ assert.equal(
+ source.calls.tiles.length,
+ 0,
+ 'a key-less install never asks',
+ );
+ assert.deepEqual(
+ [layer.getStats().loadingLabel, layer.getStats().error],
+ ['KEY REQUIRED', 'KEY REQUIRED'],
+ );
+ assert.equal(layer.getUIState().keyRequired, true);
+ assert.equal(layer.getUIState().keyRejected, false);
+ }
+ layer.destroy();
+ }
+});
+
+test('a key status that failed is asked again on the next switch-on', async (t) => {
+ let up = false;
+ let asked = 0;
+ const source = fakeMapillarySource({
+ hasToken: () => false,
+ getStatus: async () => {
+ asked++;
+ if (!up) throw new TypeError('fetch failed');
+ return { configured: true };
+ },
+ });
+ const { layer, viewer } = await startLayer(t, { source, view: true });
+ assert.equal(asked, 1, 'one check for init and the first switch-on');
+ assert.equal(layer.getUIState().keyRequired, true);
+ up = true; // the server is reachable again
+ layer.disable();
+ layer.enable(viewer);
+ await settle();
+ assert.equal(asked, 2);
+ assert.equal(layer.getUIState().keyRequired, false);
+ assert.ok(source.calls.tiles.length > 0, 'coverage loads');
+ // A known key is not asked again.
+ layer.disable();
+ layer.enable(viewer);
+ await settle();
+ assert.equal(asked, 2);
+});
+
+test('a key status that never answers gives up, so the next switch-on asks again', async (t) => {
+ // The check's timeout, fired when the test says.
+ const timeouts = [];
+ t.mock.method(AbortSignal, 'timeout', (ms) => {
+ const controller = new AbortController();
+ timeouts.push({ ms, fire: () => controller.abort(new Error('timed out')) });
+ return controller.signal;
+ });
+ let asked = 0;
+ const source = fakeMapillarySource({
+ hasToken: () => false,
+ getStatus: ({ signal } = {}) =>
+ new Promise((_, reject) => {
+ asked++;
+ signal?.addEventListener('abort', () => reject(signal.reason));
+ }),
+ });
+ const { layer, viewer } = await startLayer(t, { source, view: true });
+ assert.equal(asked, 1);
+ assert.equal(timeouts[0].ms, 10_000, 'the check can be cut short');
+ assert.equal(layer.getUIState().coverage.loading, true, 'LOADING meanwhile');
+ timeouts[0].fire();
+ await settle();
+ assert.equal(layer.getUIState().coverage.loading, false);
+ assert.equal(layer.getUIState().keyRequired, true, 'no token: KEY REQUIRED');
+ layer.disable();
+ layer.enable(viewer);
+ assert.equal(asked, 2, 'asked again, not stuck on the first');
+});
+
+test('a rejected key gates the layer as KEY REJECTED until it goes off', async (t) => {
+ const rejected = Object.assign(new Error('Mapillary rejected the token'), {
+ keyRejected: true,
+ });
+ const source = fakeMapillarySource({
+ getTile: async () => {
+ throw rejected;
+ },
+ });
+ const { layer, viewer } = await startLayer(t, { source, view: true });
+ await settle();
+ const stats = layer.getStats();
+ assert.equal(stats.keyRequired, true);
+ assert.equal(stats.loadingLabel, 'KEY REJECTED');
+ assert.match(stats.error, /rejected MAPILLARY_CLIENT_TOKEN/);
+ const ui = layer.getUIState();
+ assert.deepEqual([ui.keyRequired, ui.keyRejected], [true, true]);
+ layer.disable();
+ layer.enable(viewer);
+ assert.equal(layer.getUIState().keyRejected, false, 'asked again once on');
+});
+
+test('switching Mapillary off clears coverage and closes the image it shows', async (t) => {
+ const { layer, photoViewer } = await startLayer(t);
+ layer.attachViewerHost({});
+ assert.equal(await layer.openImage('mapillary', 'img1'), true);
+ assert.deepEqual(photoViewer.calls.open, ['img1']);
+ assert.equal(layer.getUIState().street.open, true);
+ layer.setParams({ mapillary: false });
+ assert.equal(photoViewer.calls.unmount, 1, 'its viewer is released');
+ assert.equal(layer.getUIState().street.open, false);
+ assert.equal(layer.getUIState().providers[0].on, false);
+});
+
+test('a sequence that fails to load reports it apart from the photo, and the error goes with it', async (t) => {
+ const source = fakeMapillarySource({
+ getSequenceImages: async () => {
+ throw new Error('Sequence images unavailable');
+ },
+ });
+ // The photo's pose names its sequence, which opening selects.
+ const photoViewer = fakePhotoViewer({
+ pose: { position: { lon: -121.49, lat: 38.58 }, sequenceId: 'seq-1' },
+ });
+ const { layer } = await startLayer(t, { source, photoViewer });
+ layer.attachViewerHost({});
+ assert.equal(await layer.openImage('mapillary', 'img1'), true);
+ await settle();
+ let ui = layer.getUIState();
+ assert.equal(ui.sequence.error, 'Sequence images unavailable');
+ assert.equal(ui.street.error, null, 'the photo itself is fine');
+ layer.closeViewer();
+ ui = layer.getUIState();
+ assert.equal(ui.sequence.error, null, 'withdrawn with the sequence');
+});
+
+test('closing the photo, switching the layer off or destroying it stops the framing flight', async (t) => {
+ const { layer, viewer } = await startLayer(t, {
+ photoViewer: posingViewer(),
+ });
+ layer.attachViewerHost({});
+ assert.equal(await layer.openImage('mapillary', 'img1'), true);
+ assert.equal(viewer.flights.started, 1, 'the photo is framed');
+ layer.closeViewer();
+ assert.equal(viewer.flights.cancelled, 1, 'closed');
+
+ await layer.openImage('mapillary', 'img2');
+ layer.disable();
+ assert.equal(viewer.flights.cancelled, 2, 'layer off');
+
+ layer.enable(viewer);
+ await layer.openImage('mapillary', 'img3');
+ layer.destroy();
+ assert.equal(viewer.flights.cancelled, 3, 'destroyed');
+});
+
+test('setParams takes "any date" (0 days) and the switch over the current values (share-link defaults)', async (t) => {
+ const { layer } = await startLayer(t);
+ assert.deepEqual(layer.getParams(), {
+ mapillary: true,
+ pano: 'all',
+ sinceDays: 0,
+ });
+ layer.setParams({ pano: 'flat', sinceDays: 365 });
+ assert.equal(layer.getParams().sinceDays, 365);
+ layer.setParams({ sinceDays: 0 });
+ assert.deepEqual(layer.getParams(), {
+ mapillary: true,
+ pano: 'flat',
+ sinceDays: 0,
+ });
+ layer.setParams({ mapillary: false });
+ assert.equal(layer.getParams().mapillary, false);
+});
+
+test('setParams ignores unknown keys and malformed values', async (t) => {
+ const { layer } = await startLayer(t);
+ layer.setParams({ pano: 'pano', sinceDays: 730 });
+ layer.setParams({ mapillary: '0', kartaview: true, pano: 'weird', x: 1 });
+ layer.setParams({ sinceDays: -3 });
+ layer.setParams(null);
+ assert.deepEqual(layer.getParams(), {
+ mapillary: true,
+ pano: 'pano',
+ sinceDays: 730,
+ });
+});
+
+test('switching Mapillary on while the layer is off draws nothing', async (t) => {
+ const { layer, viewer, source, photoViewer } = await startLayer(t, {
+ view: true,
+ enable: false,
+ });
+ layer.attachViewerHost({});
+ layer.setParams({ mapillary: false });
+ layer.setParams({ mapillary: true });
+ await settle();
+ assert.equal(source.calls.tiles.length, 0, 'no coverage drawn');
+ assert.deepEqual(viewer.credits, [], 'no credit shown');
+ assert.equal(photoViewer.calls.mount, 0, 'no viewer stood up');
+ assert.equal(layer.getUIState().providers[0].on, true, 'the switch is kept');
+ // Enabling the layer is what draws it.
+ layer.enable(viewer);
+ await settle();
+ assert.ok(source.calls.tiles.length > 0);
+ assert.equal(viewer.credits.length, 1);
+});
+
+test('an empty provider composition enables and tears down without acquiring imagery', async (t) => {
+ const { layer, viewer } = await startLayer(t, { providers: [] });
+ assert.deepEqual(layer.providerIds, []);
+ assert.deepEqual(layer.getUIState().providers, []);
+ assert.equal(layer.getUIState().keyRequired, false);
+ assert.match(
+ layer.getUIState().coverage.hint,
+ /No street-level imagery providers/,
+ );
+ layer.disable();
+ layer.enable(viewer);
+ assert.deepEqual(layer.getUIState().providers, []);
+});
++
++// ── Several providers: one source at a time, Google 3D, nearest lookups ──
++
+ /**
+ * A stand-in Cesium viewer the layer can be enabled on: a canvas for the
+ * click handler, camera events, a primitive list and a credit display.
+ */
+ function fakeViewer() {
+ const credits = [];
+ /** Cesium's flight bookkeeping: a new flight cancels the current one. */
+ let flight = null;
+ const flights = { started: 0, cancelled: 0 };
+ const stopFlight = () => {
+ const current = flight;
+ flight = null;
+ current?.cancel?.();
+ return Boolean(current);
+ };
+ const canvas = Object.assign(new EventTarget(), {
+ style: {},
+ // Keep Cesium's handler on the canvas; there is no real document here.
+ disableRootEvents: true,
+ onwheel: null,
+ });
+ return {
+ credits,
+ flights,
+ scene: {
+ canvas,
+ primitives: { add: (p) => p, remove() {} },
+ // Enough of a scene for the position marker to clamp to the ground.
+ frameState: { mode: Cesium.SceneMode.SCENE3D },
+ updateHeight: () => () => {},
+ getHeight: () => undefined,
+ },
+ camera: {
+ changed: new Cesium.Event(),
+ moveStart: new Cesium.Event(),
+ moveEnd: new Cesium.Event(),
+ flyToBoundingSphere(sphere, options = {}) {
+ stopFlight();
+ flight = options;
+ flights.started++;
+ },
+ cancelFlight() {
+ if (stopFlight()) flights.cancelled++;
+ },
+ },
+ creditDisplay: {
+ addStaticCredit: (credit) => credits.push(credit),
+ removeStaticCredit: (credit) =>
+ credits.splice(credits.indexOf(credit), 1),
+ },
+ };
+ }
+
+ /** A layer over `providers`, initialised and enabled on a stand-in viewer. */
+ async function enabledLayer(t, providers = [fakeProvider()]) {
+ const saved = globalThis.document;
+ // A pose moves the position marker, whose glyph is drawn on a canvas.
+ const drawing = new Proxy({}, { get: () => () => ({ addColorStop() {} }) });
+ globalThis.document = Object.assign(new EventTarget(), {
+ createElement: () => ({ getContext: () => drawing }),
+ });
+ const viewer = fakeViewer();
+ const layer = createStreetLevelLayer({ providers });
+ layer.init(viewer);
+ layer.enable(viewer);
+ t.after(() => {
+ layer.destroy();
+ globalThis.document = saved;
+ });
+ await settle();
+ return { layer, viewer };
+ }
+
-const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
-
-function deferred() {
- let resolve;
- let reject;
- const promise = new Promise((done, fail) => {
- resolve = done;
- reject = fail;
- });
- return { promise, resolve, reject };
-}
-
-/** A provider whose viewer reports a pose for every image it opens. */
+ function posingProvider(options) {
+ const provider = fakeProvider(options);
+ const create = provider.create;
+ provider.create = (context) => {
+ const instance = create(context);
+ let emit = null;
+ instance.viewer.onPose = (listener) => {
+ emit = listener;
+ return () => {
+ emit = null;
+ };
+ };
+ instance.viewer.open = async (imageId) => {
+ provider.calls.open.push(imageId);
+ emit?.({
+ providerId: 'mapillary',
+ imageId,
+ position: { lon: -121.49, lat: 38.58 },
+ bearing: 90,
+ });
+ };
+ return instance;
+ };
+ return provider;
+ }
+
+ /** nearestImage lookups that answer when the test says, with their signals. */
+ function slowLookups() {
+ const lookups = [];
+ const nearestImage = (point, { signal } = {}) => {
+ const answer = deferred();
+ lookups.push({ point, signal, answer });
+ return answer.promise;
+ };
+ return { lookups, nearestImage };
+ }
+
+ /** A map stack controller that can be switched between stacks. */
+ function fakeMapStack(initial) {
+ let active = initial;
+ const listeners = new Set();
+ return {
+ getActiveId: () => active,
+ subscribe(listener) {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ switchTo(id) {
+ active = id;
+ for (const listener of listeners) listener();
+ },
+ listenerCount: () => listeners.size,
+ };
+ }
-
-test('FOLLOW is available only while the Google 3D map stack is active', () => {
- const layer = createStreetLevelLayer({ providers: [fakeProvider()] });
- assert.equal(
- layer.getUIState().street.followAvailable,
- false,
- 'unknown stack: off',
- );
-
- const stack = fakeMapStack('esri-imagery');
- layer.attachMapStackController(stack);
- assert.equal(layer.getUIState().street.followAvailable, false);
- layer.setFollow(true);
- assert.equal(layer.getUIState().street.follow, false, 'refused on Esri');
-
- stack.switchTo('photoreal');
- assert.equal(layer.getUIState().street.followAvailable, true);
- layer.setFollow(true);
- assert.equal(layer.getUIState().street.follow, true);
-
- stack.switchTo('osm');
- assert.equal(layer.getUIState().street.followAvailable, false);
- assert.equal(
- layer.getUIState().street.follow,
- false,
- 'leaving Google 3D stops following',
- );
-});
-
+ test('the layer lets go of the map stack when destroyed or re-attached', () => {
+ const layer = createStreetLevelLayer({ providers: [fakeProvider()] });
+ const first = fakeMapStack('photoreal');
+ layer.attachMapStackController(first);
+ assert.equal(first.listenerCount(), 1);
+ const second = fakeMapStack('photoreal');
+ layer.attachMapStackController(second);
+ assert.equal(first.listenerCount(), 0);
+ assert.equal(second.listenerCount(), 1);
+ layer.destroy();
+ assert.equal(second.listenerCount(), 0);
+ });
+
-test('the CC BY-SA credit shows while a provider is on and goes with it', async (t) => {
- const { layer, viewer } = await enabledLayer(t);
- const shown = () => viewer.credits.map((credit) => credit.html);
- assert.deepEqual(shown(), [MAPILLARY_CREDIT_HTML], 'shown on activate');
- assert.match(shown()[0], /CC BY-SA 4\.0/);
- layer.setProviderEnabled('mapillary', false);
- assert.deepEqual(shown(), [], 'hidden with the provider');
- layer.setProviderEnabled('mapillary', true);
- assert.deepEqual(shown(), [MAPILLARY_CREDIT_HTML]);
- layer.disable();
- assert.deepEqual(shown(), [], 'every credit goes with the layer');
-});
-
-test('getStats tells a rejected key from a missing one', async (t) => {
- const provider = fakeProvider();
- const { layer } = await enabledLayer(t, [provider]);
- provider.stats.loading = true;
- assert.equal(layer.getStats().loadingLabel, 'loading coverage...');
- assert.equal(layer.getStats().keyRequired, false);
-
- provider.stats.keyRequired = true;
- assert.deepEqual(
- [layer.getStats().loadingLabel, layer.getStats().error],
- ['KEY REQUIRED', 'KEY REQUIRED'],
- );
-
- // A rejected key gates the provider exactly like a missing one.
- provider.stats.keyRequired = false;
- provider.stats.keyRejected = true;
- provider.stats.error = 'Mapillary rejected MAPILLARY_CLIENT_TOKEN';
- const stats = layer.getStats();
- assert.equal(stats.keyRequired, true);
- assert.equal(stats.loadingLabel, 'KEY REJECTED');
- assert.equal(stats.error, 'Mapillary rejected MAPILLARY_CLIENT_TOKEN');
- const ui = layer.getUIState();
- assert.equal(ui.keyRequired, true);
- assert.equal(ui.keyRejected, true);
- assert.equal(ui.providers[0].keyRequired, true);
-});
-
-test('switching a provider off deactivates it and closes the image it shows', async (t) => {
- const provider = fakeProvider();
- const { layer } = await enabledLayer(t, [provider]);
- layer.attachViewerHost({});
- assert.equal(await layer.openImage('mapillary', 'img1'), true);
- assert.deepEqual(provider.calls.open, ['img1']);
- assert.equal(layer.getUIState().street.open, true);
- layer.setProviderEnabled('mapillary', false);
- assert.equal(provider.calls.deactivate, 1);
- assert.equal(provider.calls.unmount, 1, 'its viewer is released');
- assert.equal(layer.getUIState().street.open, false);
- assert.equal(layer.getUIState().street.providerId, null);
-});
-
+ test('openNearest without the panel reports it instead of loading forever', async (t) => {
+ const provider = fakeProvider({ nearestImage: async () => 'img1' });
+ const { layer } = await enabledLayer(t, [provider]);
+ assert.equal(await layer.openNearest({ lat: 38.58, lon: -121.49 }), false);
+ const { street } = layer.getUIState();
+ assert.equal(street.loading, false);
+ assert.match(street.error, /Open the Street Level panel/);
+ assert.equal(provider.calls.mount, 0);
+ });
+
+ test('openNearest opens nothing once the layer went off during the lookup', async (t) => {
+ const answer = deferred();
+ const provider = fakeProvider({ nearestImage: () => answer.promise });
+ const { layer } = await enabledLayer(t, [provider]);
+ layer.attachViewerHost({});
+ const opening = layer.openNearest({ lat: 38.58, lon: -121.49 });
+ layer.disable();
+ answer.resolve('img1');
+ assert.equal(await opening, false);
+ assert.equal(provider.calls.mount, 0, 'no viewer was stood up');
+ const { street } = layer.getUIState();
+ assert.equal(street.open, false);
+ assert.equal(street.loading, false);
+ assert.equal(street.error, null);
+ });
+
+ test('openNearest skips a provider switched off during its lookup', async (t) => {
+ const answer = deferred();
+ const provider = fakeProvider({ nearestImage: () => answer.promise });
+ const { layer } = await enabledLayer(t, [provider]);
+ layer.attachViewerHost({});
+ const opening = layer.openNearest({ lat: 38.58, lon: -121.49 });
+ layer.setProviderEnabled('mapillary', false);
+ answer.resolve('img1');
+ assert.equal(await opening, false);
+ assert.deepEqual(provider.calls.open, []);
+ assert.equal(layer.getUIState().street.loading, false);
+ });
+
+ test('a provider withdraws only the error it reported', async (t) => {
+ const provider = fakeProvider();
+ const { layer } = await enabledLayer(t, [provider]);
+ const { actions } = provider.context();
+ actions.reportError('Sequence images unavailable');
+ assert.equal(layer.getUIState().street.error, 'Sequence images unavailable');
+ actions.reportError(null);
+ assert.equal(layer.getUIState().street.error, null, 'withdrawn');
+
+ // The viewer's own error is not the provider's to clear.
+ layer.attachViewerHost(null);
+ actions.reportError('Sequence images unavailable');
+ await layer.openImage('mapillary', 'img1');
+ actions.reportError(null);
+ assert.match(layer.getUIState().street.error, /Open the Street Level panel/);
+ });
-
-test('closing the photo stops the globe flying to it', async (t) => {
- const { layer, viewer } = await enabledLayer(t, [posingProvider()]);
- layer.attachViewerHost({});
- assert.equal(await layer.openImage('mapillary', 'img1'), true);
- assert.equal(viewer.flights.started, 1, 'the photo is framed');
- layer.closeViewer();
- assert.equal(viewer.flights.cancelled, 1);
-});
-
-test('switching the layer off or destroying it stops the framing flight', async (t) => {
- const { layer, viewer } = await enabledLayer(t, [posingProvider()]);
- layer.attachViewerHost({});
- await layer.openImage('mapillary', 'img1');
- layer.disable();
- assert.equal(viewer.flights.cancelled, 1, 'layer off');
-
- layer.enable(viewer);
- await layer.openImage('mapillary', 'img2');
- layer.destroy();
- assert.equal(viewer.flights.cancelled, 2, 'destroyed');
-});
-
-test('closing the photo leaves a newer navigation flight alone', async (t) => {
- const { layer, viewer } = await enabledLayer(t, [posingProvider()]);
- layer.attachViewerHost({});
- await layer.openImage('mapillary', 'img1');
- assert.equal(viewer.flights.started, 1, 'the photo is being framed');
- // A search result flies the globe elsewhere before the framing lands.
- viewer.camera.flyToBoundingSphere(null, {});
- layer.closeViewer();
- assert.equal(viewer.flights.cancelled, 0, 'the search flight keeps going');
-});
-
+ test('an older nearest lookup that answers late cannot replace a newer one', async (t) => {
+ const { lookups, nearestImage } = slowLookups();
+ const provider = fakeProvider({ nearestImage });
+ const { layer } = await enabledLayer(t, [provider]);
+ layer.attachViewerHost({});
+ const older = layer.openNearest({ lat: 38.58, lon: -121.49 });
+ const newer = layer.openNearest({ lat: 38.59, lon: -121.48 });
+ lookups[1].answer.resolve('newer');
+ assert.equal(await newer, true);
+ lookups[0].answer.resolve('older');
+ assert.equal(await older, false);
+ assert.deepEqual(provider.calls.open, ['newer']);
+ assert.equal(lookups[0].signal?.aborted, true, 'its request was aborted');
+ assert.equal(lookups[1].signal?.aborted, false);
+ });
+
+ test('an image picked during a nearest lookup wins over its late answer', async (t) => {
+ const { lookups, nearestImage } = slowLookups();
+ const provider = fakeProvider({ nearestImage });
+ const { layer } = await enabledLayer(t, [provider]);
+ layer.attachViewerHost({});
+ const lookup = layer.openNearest({ lat: 38.58, lon: -121.49 });
+ // A cone click goes through the provider's openImage action.
+ assert.equal(await provider.context().actions.openImage('picked'), true);
+ lookups[0].answer.resolve('nearest');
+ assert.equal(await lookup, false);
+ assert.deepEqual(provider.calls.open, ['picked']);
+ assert.equal(lookups[0].signal?.aborted, true);
+ });
+
+ test('closing the viewer or switching the layer off retires a nearest lookup', async (t) => {
+ const { lookups, nearestImage } = slowLookups();
+ const provider = fakeProvider({ nearestImage });
+ const { layer, viewer } = await enabledLayer(t, [provider]);
+ layer.attachViewerHost({});
+
+ const closed = layer.openNearest({ lat: 38.58, lon: -121.49 });
+ layer.closeViewer();
+ // The aborted fetch rejects, as fetch does; that is not the user's error.
+ lookups[0].answer.reject(new DOMException('aborted', 'AbortError'));
+ assert.equal(await closed, false);
+ let { street } = layer.getUIState();
+ assert.deepEqual(
+ [street.open, street.loading, street.error],
+ [false, false, null],
+ );
+ assert.equal(lookups[0].signal?.aborted, true, 'closing aborts the request');
+
+ const disabled = layer.openNearest({ lat: 38.58, lon: -121.49 });
+ layer.disable();
+ layer.enable(viewer);
+ lookups[1].answer.resolve('img1');
+ assert.equal(await disabled, false, 'nor does it open once back on');
+ assert.deepEqual(provider.calls.open, []);
+ ({ street } = layer.getUIState());
+ assert.deepEqual(
+ [street.open, street.loading, street.error],
+ [false, false, null],
+ );
+ assert.equal(lookups[1].signal?.aborted, true, 'layer off aborts it too');
+ });
+
-test('the Mapillary provider hands the lookup signal to its source', async () => {
- const requests = [];
- const source = {
- hasToken: () => true,
- getStatus: async () => ({ configured: true }),
- getTile: async () => new Uint8Array(0),
- getSequenceImages: async () => [],
- nearestImages: async (query, options) => {
- requests.push(options);
- return [{ id: 7, is_pano: false, captured_at: 10 }];
- },
- };
- const instance = createMapillaryProvider({ source }).create({
- services: {},
- getFilter: () => ({ pano: 'all', sinceMs: null }),
- isActive: () => true,
- notify() {},
- actions: { openImage() {}, reportError() {} },
- });
- const { signal } = new AbortController();
- assert.equal(
- await instance.nearestImage({ lat: 1, lon: 2 }, { signal }),
- '7',
- );
- assert.equal(requests[0]?.signal, signal);
-});
-
-test('setParams takes "any date" (0 days) and a provider switch over the current values (share-link defaults)', async (t) => {
- const provider = fakeProvider();
- const { layer } = await enabledLayer(t, [provider]);
- layer.setParams({ pano: 'flat', sinceDays: 365 });
- assert.equal(layer.getParams().sinceDays, 365);
- layer.setParams({ sinceDays: 0 });
- assert.deepEqual(layer.getParams(), {
- mapillary: true,
- pano: 'flat',
- sinceDays: 0,
- });
- assert.equal(
- provider.filters.at(-1).sinceMs,
- null,
- 'providers drop the cut-off',
- );
- layer.setParams({ mapillary: false });
- assert.equal(layer.getParams().mapillary, false);
-});
-
-/** A layer initialised on a stand-in viewer but never enabled. */
+ function initialisedLayer(t, providers) {
+ const saved = globalThis.document;
+ const drawing = new Proxy({}, { get: () => () => ({ addColorStop() {} }) });
+ globalThis.document = Object.assign(new EventTarget(), {
+ createElement: () => ({ getContext: () => drawing }),
+ });
+ const viewer = fakeViewer();
+ const layer = createStreetLevelLayer({ providers });
+ layer.init(viewer);
+ t.after(() => {
+ layer.destroy();
+ globalThis.document = saved;
+ });
+ return { layer, viewer };
+ }
+
+ test('switching a provider on while the layer is off activates nothing (M01)', async (t) => {
+ const provider = fakeProvider();
+ const prewarmed = [];
+ const create = provider.create;
+ provider.create = (context) => {
+ const instance = create(context);
+ instance.viewer.prewarm = async (host) => prewarmed.push(host);
+ return instance;
+ };
+ const { layer, viewer } = initialisedLayer(t, [provider]);
+ layer.attachViewerHost({});
+ layer.setProviderEnabled('mapillary', false);
+ layer.setProviderEnabled('mapillary', true);
+ layer.setParams({ mapillary: false });
+ layer.setParams({ mapillary: true });
+ await new Promise((resolve) => setTimeout(resolve, 40)); // past whenIdle
+ assert.equal(provider.calls.activate, 0, 'no coverage drawn');
+ assert.deepEqual(viewer.credits, [], 'no credit shown');
+ assert.deepEqual(prewarmed, [], 'no viewer stood up');
+ assert.equal(layer.getUIState().providers[0].on, true, 'the switch is kept');
+ // Enabling the layer is what activates it, once.
+ layer.enable(viewer);
+ assert.equal(provider.calls.activate, 1);
+ assert.equal(viewer.credits.length, 1);
+ });
+
+ /** The real Google provider over the Street View fakes, beside a Mapillary stand-in. */
+ async function withStreetView(
+ t,
+ { mapStack = 'photoreal', nearest, mapillaryKeyless = false } = {},
+ ) {
+ const { createGoogleProvider } = await import('./providers/google/index.js');
+ const { fakeHost, fakeMapsLoader, fakeStreetViewLibrary } =
+ await import('../../testSupport/googleStreetViewFakes.mjs');
+ const fake = fakeStreetViewLibrary({
+ panoramas: {
+ 'pano-a': { lat: 38.5816, lng: -121.4944, imageDate: '2024-05' },
+ },
+ nearest: nearest ?? (() => 'pano-a'),
+ });
+ const mapillaryLookups = [];
+ const mapillary = fakeProvider({
+ nearestImage: async (point) => {
+ mapillaryLookups.push(point);
+ return null;
+ },
+ });
+ mapillary.requiresKeyId = 'mapillary';
+ if (mapillaryKeyless) {
+ mapillary.stats.keyRequired = true;
+ const create = mapillary.create;
+ mapillary.create = (context) => ({
+ ...create(context),
+ status: async () => ({ configured: false }),
+ });
+ }
+ const loader = fakeMapsLoader(fake.library);
+ const google = createGoogleProvider({
+ getApiKey: () => 'browser-key',
+ loader,
+ });
+ const { layer, viewer } = await enabledLayer(t, [mapillary, google]);
+ const stack = fakeMapStack(mapStack);
+ layer.attachMapStackController(stack);
+ layer.attachViewerHost(fakeHost());
+ return { layer, viewer, stack, fake, loader, mapillaryLookups };
+ }
+
+ test('Street View starts off, and the layer row names the key of the providers that are on', async (t) => {
+ const { layer } = await withStreetView(t);
+ const google = () =>
+ layer.getUIState().providers.find((p) => p.id === 'google');
+ assert.equal(google().on, false);
+ assert.equal(layer.requiresKeyId, 'mapillary');
+ layer.setProviderEnabled('google', true);
+ assert.equal(layer.requiresKeyId, 'google-maps', 'Street View alone');
+ });
+
+ test('the layer starts with one source lit: the first that defaults on', async (t) => {
+ const { layer } = await enabledLayer(t, [
+ fakeProvider(),
+ fakeProvider({ id: 'panoramax', pickPrefix: 'pmx:' }),
+ ]);
+ assert.deepEqual(
+ layer
+ .getUIState()
+ .providers.filter((p) => p.on)
+ .map((p) => p.id),
+ ['mapillary'],
+ );
+ });
+
+ test('leaving Google 3D during a Street View lookup ends it without an error or a stuck spinner', async (t) => {
+ const { layer, stack, fake } = await withStreetView(t);
+ layer.setProviderEnabled('google', true);
+ let answer;
+ fake.library.StreetViewService.prototype.getPanorama = () =>
+ new Promise((resolve) => {
+ answer = resolve;
+ });
+ const opening = layer.openNearest({ lat: 38.5816, lon: -121.4944 });
+ await settle();
+ assert.equal(layer.getUIState().street.loading, true);
+ stack.switchTo('bing');
+ answer({ data: { location: { pano: 'pano-a' }, imageDate: '2024-05' } });
+ assert.equal(await opening, false);
+ const { street } = layer.getUIState();
+ assert.equal(street.loading, false, 'OPEN STREET VIEW is usable again');
+ assert.equal(street.error, null);
+ assert.equal(street.open, false);
+ });
+
+ test('a source swap during a lookup reports no false "no imagery"', async (t) => {
+ let answer;
+ const mapillary = fakeProvider({
+ nearestImage: () =>
+ new Promise((resolve) => {
+ answer = resolve;
+ }),
+ });
+ const other = fakeProvider({ id: 'panoramax', pickPrefix: 'pmx:' });
+ const { layer } = await enabledLayer(t, [mapillary, other]);
+ const opening = layer.openNearest({ lat: 1, lon: 2 });
+ layer.setProviderEnabled('panoramax', true);
+ answer('img-1');
+ assert.equal(await opening, false);
+ assert.equal(layer.getUIState().street.error, null);
+ assert.equal(layer.getUIState().street.loading, false);
+ });
+
+ test('Street View lit off Google 3D says why the panel is empty', async (t) => {
+ const { layer, stack } = await withStreetView(t);
+ layer.setProviderEnabled('google', true);
+ stack.switchTo('esri-imagery');
+ assert.match(
+ layer.getUIState().coverage.hint,
+ /Google Street View needs the Google 3D map/,
+ );
+ layer.setProviderEnabled('mapillary', true);
+ assert.doesNotMatch(layer.getUIState().coverage.hint, /Google 3D/);
+ });
+
+ test('one imagery source at a time: lighting one darkens the other, either way', async (t) => {
+ const { layer } = await withStreetView(t);
+ const lit = () =>
+ layer
+ .getUIState()
+ .providers.filter((p) => p.on)
+ .map((p) => p.id);
+ assert.deepEqual(lit(), ['mapillary'], 'Mapillary by default: it is free');
+ layer.setProviderEnabled('google', true);
+ assert.deepEqual(lit(), ['google']);
+ assert.equal(layer.getParams().mapillary, false);
+ layer.setProviderEnabled('mapillary', true);
+ assert.deepEqual(lit(), ['mapillary']);
+ assert.equal(layer.getParams().google, false);
+ // Params that light one switch to it; reapplying them changes nothing.
+ layer.setParams({ google: true });
+ assert.deepEqual(lit(), ['google']);
+ layer.setParams({ google: true });
+ assert.deepEqual(lit(), ['google']);
+ // Params lighting both keep the one already on, however often applied.
+ for (let i = 0; i < 2; i++) {
+ layer.setParams({ mapillary: true, providerSwitches: 'google-1' });
+ assert.deepEqual(lit(), ['google']);
+ }
+ layer.setParams({ mapillary: true, google: false });
+ assert.deepEqual(lit(), ['mapillary']);
+ // Filter-only params leave the source alone.
+ layer.setParams({ pano: 'pano' });
+ assert.deepEqual(lit(), ['mapillary']);
+ // Darkening the only lit one leaves none: the panel turns the layer off.
+ layer.setProviderEnabled('mapillary', false);
+ assert.deepEqual(lit(), []);
+ });
+
-test('Street View appears only on the Google 3D map: chip, legend, credit, source and images', async (t) => {
++test('Street View appears only on the Google 3D map: chip, credit, source and images', async (t) => {
+ const { layer, viewer, stack } = await withStreetView(t, {
+ mapStack: 'esri-imagery',
+ });
+ layer.setProviderEnabled('google', true);
+ await settle();
+ const ui = () => layer.getUIState();
+ const listed = () => ui().providers.map((p) => p.id);
+ const credited = () =>
+ viewer.credits.some((credit) => /Street View imagery/.test(credit.html));
+ assert.deepEqual(listed(), ['mapillary'], 'no Street View chip');
- assert.ok(!ui().legend.some((item) => item.key === 'google'));
+ assert.equal(credited(), false, 'no Google credit on another map');
+ assert.equal(layer.source, 'Mapillary');
+ assert.equal(layer.getStats().source, 'Mapillary');
+ assert.equal(await layer.openImage('google', 'pano-a'), false);
+ assert.match(ui().street.error, /needs the Google 3D map/);
+ assert.equal(layer.getParams().google, true, 'the choice is kept');
+
+ stack.switchTo('photoreal');
+ assert.deepEqual(listed(), ['mapillary', 'google']);
+ assert.equal(credited(), true);
+ assert.equal(layer.source, 'Mapillary · Google Street View');
+ assert.equal(await layer.openImage('google', 'pano-a'), true);
+ assert.equal(ui().street.providerId, 'google');
+
+ stack.switchTo('bing');
+ await settle();
+ assert.equal(ui().street.open, false, 'closed with the map');
+ assert.equal(credited(), false);
+ assert.deepEqual(listed(), ['mapillary']);
+ });
+
+ test('the UI state says when a click (or the button) can open Street View here', async (t) => {
+ const { layer } = await withStreetView(t);
+ assert.equal(typeof layer.getUIState().groundClickReady, 'boolean');
+ });
+
+ test('a lookup for the click-to-open providers asks only them and reports "that point"', async (t) => {
+ const { layer, mapillaryLookups } = await withStreetView(t, {
+ nearest: () => null,
+ });
+ layer.setProviderEnabled('google', true);
+ await settle();
+ const opened = await layer.openNearest(
+ { lat: 38.58, lon: -121.49 },
+ { providerIds: ['google'], frame: false },
+ );
+ assert.equal(opened, false);
+ assert.deepEqual(mapillaryLookups, [], 'Mapillary was not asked');
+ assert.equal(
+ layer.getUIState().street.error,
+ 'No street-level imagery within 50 m of that point',
+ );
+ });
+
+ test('the nearest-image refusal is written in the language of the page', async (t) => {
+ const { layer } = await withStreetView(t, { nearest: () => null });
+ layer.setProviderEnabled('google', true);
+ await settle();
+ setLocale('es');
+ try {
+ await layer.openNearest(
+ { lat: 38.58, lon: -121.49 },
+ { providerIds: ['google'], frame: false },
+ );
+ const error = layer.getUIState().street.error;
+ assert.notEqual(error, 'No street-level imagery within 50 m of that point');
+ assert.match(error, /50/, 'keeps the radius');
+ } finally {
+ setLocale('en');
+ }
+ });
+
+ test('an image opened from a ground click leaves the camera where it is', async (t) => {
+ const { layer, viewer } = await withStreetView(t);
+ layer.setProviderEnabled('google', true);
+ await settle();
+ await layer.openNearest(
+ { lat: 38.58, lon: -121.49 },
+ { providerIds: ['google'], frame: false },
+ );
+ assert.equal(layer.getUIState().street.imageId, 'pano-a');
+ assert.equal(viewer.flights.started, 0, 'no framing flight');
+ });
+
+ test('off Google 3D not even Google\u2019s script is loaded for Street View', async (t) => {
+ const { layer, loader } = await withStreetView(t, {
+ mapStack: 'esri-imagery',
+ });
+ layer.setProviderEnabled('google', true);
+ layer.attachViewerHost({ ownerDocument: { createElement: () => ({}) } });
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ assert.deepEqual(loader.imports, [], 'no prewarm, no lookup');
+ });
+
+ test('the button’s “centre of the view” is the ground under the middle of the screen', async (t) => {
+ const { createStreetLevelLayer: create } = await import('./index.js');
+ const scenePick = await import('../../data/scenePick.js');
+ const lookups = [];
+ const provider = fakeProvider({
+ nearestImage: async (point) => {
+ lookups.push(point);
+ return null;
+ },
+ });
+ const saved = globalThis.document;
+ const drawing = new Proxy({}, { get: () => () => ({ addColorStop() {} }) });
+ globalThis.document = Object.assign(new EventTarget(), {
+ createElement: () => ({ getContext: () => drawing }),
+ });
+ const viewer = fakeViewer();
+ const centre = Cesium.Cartesian3.fromDegrees(-121.4937, 38.5799, 0);
+ Object.assign(viewer.scene, {
+ pickPositionSupported: true,
+ pickPosition: (at) => (at.x === 500 && at.y === 300 ? centre : undefined),
+ });
+ viewer.scene.canvas.clientWidth = 1000;
+ viewer.scene.canvas.clientHeight = 600;
+ const layer = create({ providers: [provider], services: { scenePick } });
+ layer.init(viewer);
+ layer.enable(viewer);
+ t.after(() => {
+ layer.destroy();
+ globalThis.document = saved;
+ });
+ await layer.openNearest(undefined, { aim: 'screen-centre' });
+ assert.equal(lookups.length, 1);
+ assert.ok(Math.abs(lookups[0].lat - 38.5799) < 1e-9);
+ assert.ok(Math.abs(lookups[0].lon - -121.4937) < 1e-9);
+ });
+
+ test('the button aimed at the sky opens nothing, and says to aim at a street', async (t) => {
+ const { createStreetLevelLayer: create } = await import('./index.js');
+ const scenePick = await import('../../data/scenePick.js');
+ const lookups = [];
+ const provider = fakeProvider({
+ nearestImage: async (point) => {
+ lookups.push(point);
+ return null;
+ },
+ });
+ const saved = globalThis.document;
+ const drawing = new Proxy({}, { get: () => () => ({ addColorStop() {} }) });
+ globalThis.document = Object.assign(new EventTarget(), {
+ createElement: () => ({ getContext: () => drawing }),
+ });
+ const viewer = fakeViewer();
+ // Every ground pick misses: the middle of the screen is sky.
+ Object.assign(viewer.scene, {
+ pickPositionSupported: true,
+ pickPosition: () => undefined,
+ });
+ viewer.camera.pickEllipsoid = () => undefined;
+ viewer.scene.canvas.clientWidth = 1000;
+ viewer.scene.canvas.clientHeight = 600;
+ const layer = create({ providers: [provider], services: { scenePick } });
+ layer.init(viewer);
+ layer.enable(viewer);
+ t.after(() => {
+ layer.destroy();
+ globalThis.document = saved;
+ });
+ assert.equal(
+ await layer.openNearest(undefined, { aim: 'screen-centre' }),
+ false,
+ );
+ assert.deepEqual(lookups, [], 'no lookup at the view centre instead');
+ const { street } = layer.getUIState();
+ assert.match(street.error, /Aim the middle of the view at a street/);
+ assert.equal(street.loading, false);
+ });
+
+ test('with no Mapillary token, the layer points at Street View, on Google 3D only', async (t) => {
+ const { layer, stack } = await withStreetView(t, { mapillaryKeyless: true });
+ await settle();
+ const stats = layer.getStats();
+ assert.equal(stats.keyRequired, true);
+ assert.deepEqual(stats.keyAlternatives, [
+ { id: 'google', label: 'GOOGLE STREET VIEW', requiresKeyId: 'google-maps' },
+ ]);
+ assert.deepEqual(layer.getUIState().keyAlternatives, stats.keyAlternatives);
+ stack.switchTo('esri-imagery');
+ assert.deepEqual(layer.getStats().keyAlternatives, [], 'not off Google 3D');
+ // Lit, Street View draws: the layer is no longer key-gated.
+ stack.switchTo('photoreal');
+ layer.setProviderEnabled('google', true);
+ assert.equal(layer.getStats().keyRequired, false);
+ });
+
-test('an empty provider composition enables and tears down without acquiring imagery', async (t) => {
- const { layer, viewer } = await enabledLayer(t, []);
- assert.deepEqual(layer.providerIds, []);
- assert.deepEqual(layer.getUIState().providers, []);
- assert.equal(layer.getUIState().keyRequired, false);
- assert.match(
- layer.getUIState().coverage.hint,
- /No street-level imagery providers/,
- );
- layer.disable();
- layer.enable(viewer);
- assert.deepEqual(layer.getUIState().providers, []);
-});
-
+ test('a failed lookup’s error goes when another source is lit; a provider can open an image without framing', async (t) => {
+ const failing = fakeProvider({
+ nearestImage: async () => {
+ throw new Error('KartaView did not answer in time — try again');
+ },
+ });
+ const other = fakeProvider({ id: 'other', pickPrefix: 'oth:' });
+ const { layer, viewer } = await enabledLayer(t, [failing, other]);
+ layer.attachViewerHost({});
+ await layer.openNearest({ lat: 1, lon: 1 });
+ assert.match(layer.getUIState().street.error, /did not answer/);
+ layer.setProviderEnabled('other', true);
+ await settle();
+ assert.equal(layer.getUIState().street.error, null);
+ // A provider's own open (KartaView's ‹ ›) can leave the camera alone.
+ await other.context().actions.openImage('img-1', { frame: false });
+ assert.deepEqual(other.calls.open, ['img-1']);
+ assert.equal(viewer.flights.started, 0);
+ });
+
+ test('a provider’s own open can leave the camera where it is; a default open frames', async (t) => {
+ const provider = posingProvider();
+ const { layer, viewer } = await enabledLayer(t, [provider]);
+ layer.attachViewerHost({});
+ await provider.context().actions.openImage('img-1', { frame: false });
+ assert.deepEqual(provider.calls.open, ['img-1']);
+ assert.equal(viewer.flights.started, 0, 'frame: false keeps the camera');
+ await provider.context().actions.openImage('img-2');
+ assert.equal(viewer.flights.started, 1, 'a default open frames the image');
+ });
+
+ test('a provider’s openNearest (a line click) asks only that provider and leaves the camera', async (t) => {
+ const lit = posingProvider({ nearestImage: async () => 'lit-near' });
+ const other = fakeProvider({
+ id: 'other',
+ pickPrefix: 'oth:',
+ nearestImage: async () => 'other-near',
+ });
+ const { layer, viewer } = await enabledLayer(t, [lit, other]);
+ layer.attachViewerHost({});
+ const point = { lat: 38.58, lon: -121.49 };
+ // The other source is off: its click asks nobody else.
+ await other.context().actions.openNearest(point);
+ await settle();
+ assert.deepEqual(lit.calls.open, [], 'the lit source was not asked');
+ assert.deepEqual(other.calls.open, []);
+ await lit.context().actions.openNearest(point);
+ assert.deepEqual(lit.calls.open, ['lit-near']);
+ assert.equal(viewer.flights.started, 0, 'the user picked the spot');
+ });
+
-test('KartaView through the core: its own swatch without Selected, its lines counted as streets', async (t) => {
++test('KartaView through the core: its lines counted as streets', async (t) => {
+ const kartaView = createKartaViewProvider({
+ source: {
+ getTile: async () => ({ lines: [] }),
+ nearestPhotos: async () => [],
+ getPhoto: async () => {
+ throw new Error('KartaView has no such photo');
+ },
+ getSequencePhotos: async () => ({ photos: [], hasMore: false }),
+ probeImage: async () => true,
+ },
+ });
+ const { layer } = await enabledLayer(t, [kartaView]);
+ layer.setProviderEnabled('kartaview', true);
+ await settle();
+ const ui = layer.getUIState();
- assert.deepEqual(
- ui.legend.map((entry) => entry.key),
- ['kartaview'],
- );
+ assert.equal(ui.coverage.label?.noun, 'streets');
- assert.equal(
- ui.providers.find((p) => p.id === 'kartaview').highlightsSequence,
- false,
- );
+ });
+
+ test('switching source by params (the chip path) stops a running lookup and clears its spinner and error', async (t) => {
+ const slow = slowLookups();
+ const looking = fakeProvider({ nearestImage: slow.nearestImage });
+ const other = fakeProvider({ id: 'other', pickPrefix: 'oth:' });
+ const { layer } = await enabledLayer(t, [looking, other]);
+ layer.attachViewerHost({});
+ const opening = layer.openNearest({ lat: 1, lon: 1 });
+ await settle();
+ assert.equal(layer.getUIState().street.loading, true);
+ layer.setParams({ mapillary: false, other: true });
+ assert.equal(slow.lookups[0].signal.aborted, true, 'the lookup is stopped');
+ assert.equal(
+ layer.getUIState().street.loading,
+ false,
+ 'no spinner left behind',
+ );
+ // The stopped lookup answers late: nothing opens, nothing is reported.
+ slow.lookups[0].answer.resolve('img1');
+ assert.equal(await opening, false);
+ assert.deepEqual(looking.calls.open, []);
+ assert.equal(layer.getUIState().street.error, null);
+ });
+
+ test('switching source by params clears a failed lookup’s error; reapplying the same switches does not', async (t) => {
+ const failing = fakeProvider({
+ nearestImage: async () => {
+ throw new Error('KartaView did not answer in time — try again');
+ },
+ });
+ const { layer: second } = await enabledLayer(t, [
+ failing,
+ fakeProvider({ id: 'other', pickPrefix: 'oth:' }),
+ ]);
+ second.attachViewerHost({});
+ await second.openNearest({ lat: 1, lon: 1 });
+ assert.match(second.getUIState().street.error, /did not answer/);
+ second.setParams({ mapillary: false, other: true });
+ assert.equal(second.getUIState().street.error, null);
+ // Reapplying the same switches (a restore) leaves state alone.
+ await second.openNearest({ lat: 1, lon: 1 });
+ const kept = second.getUIState().street.error;
+ assert.match(kept, /No street-level imagery/);
+ second.setParams({ mapillary: false, other: true });
+ assert.equal(second.getUIState().street.error, kept);
+ });
diff --cc src/layers/streetLevel/lineCoverage.js
index 6db6bda0e,fbd992f88..b40104544
--- a/src/layers/streetLevel/lineCoverage.js
+++ b/src/layers/streetLevel/lineCoverage.js
@@@ -1,87 -1,133 +1,148 @@@
import * as Cesium from 'cesium';
- import { decodeCoverageTile } from './decode.js';
import { passesImageryFilter } from './filter.js';
-import {
- createHorizonCull,
- groundUnderCamera,
- metresBetween,
- viewFocus,
- visibleBbox,
- whenIdle,
-} from './view.js';
-import { densifyLine, MESH_DENSIFY_DEG } from './groundCast.js';
+import { groundUnderCamera, viewFocus, visibleBbox } from './view.js';
- import { coverageZoomForHeight, tilesForBbox } from './tileMath.js';
- import {
- COLORS,
- COVERAGE_LINE_WIDTH_PX,
- COVERAGE_MAX_SEQUENCES,
- COVERAGE_MAX_TILES,
- COVERAGE_MOVE_DEBOUNCE_MS,
- KEY_REJECTED_MESSAGE,
- PICK_PREFIX,
- RATE_LIMITED_MESSAGE,
- SEQUENCE_VIEW_RANGE_MIN_M,
- SEQUENCE_VIEW_RANGE_PER_HEIGHT,
- } from './policy.js';
++import { tilesForBbox } from './tileMath.js';
+ import { msg } from '../../i18n/index.js';
-import { MESH_SAMPLE_RADIUS_M } from './meshSampler.js';
-import { tileBounds, tilesForBbox } from './tileMath.js';
-/** A tile's shared point cap must move by this much to redraw it. */
-const SHARE_HYSTERESIS = 0.1;
-/** Draped lines stay at most this long while a tile's cast lines build. */
-export const SWAP_MAX_WAIT_MS = 4000;
-/** Tiles touched by new mesh samples are redrawn at most this often. */
-const REMESH_INTERVAL_MS = 1500;
-/** Gap between redrawing one dirty tile and the next. */
-const REMESH_STAGGER_MS = 120;
-/** Old-zoom tiles are kept at most this long after a zoom change. */
-const STALE_TILE_MAX_MS = 6000;
/** Sequences per primitive: smaller batches build, and show, sooner. */
const SEQUENCE_PRIMITIVE_BATCH = 120;
- const PER_TILE_SEQUENCE_CAP = Math.floor(
- COVERAGE_MAX_SEQUENCES / COVERAGE_MAX_TILES,
-/** Separates a multi-part sequence's part index from its id in pick ids. */
-const PART_SEPARATOR = '~';
++/** Hint above the street-zoom ceiling, where no coverage is drawn. */
++export const ZOOM_IN_HINT = msg('Zoom in to see street-level coverage');
++/** Hint when no ground is in view within range (looking at the sky). */
++const NO_GROUND_HINT = msg(
++ 'Point the camera at the ground for street-level coverage',
+);
- /** Sequence id for a line's pick id (`mly:seq:<id>`), else null. */
- export function sequenceIdFromPick(pickId) {
- if (typeof pickId !== 'string' || !pickId.startsWith(PICK_PREFIX.sequence))
-/** Pick ids for every part of a sequence; the first part is unsuffixed. */
-function partIds(sequence, prefix) {
- return sequence.parts.map((_, index) =>
- index
- ? `${prefix}${sequence.id}${PART_SEPARATOR}${index}`
- : `${prefix}${sequence.id}`,
- );
-}
-
-/** Sequence id for any part's pick id (`<prefix><id>[~<part>]`), else null. */
++/** Sequence id for a line's pick id (`<prefix><id>`), else null. */
+ export function sequenceIdFromPick(pickId, prefix) {
+ if (typeof pickId !== 'string' || !prefix || !pickId.startsWith(prefix))
return null;
- return pickId.slice(PICK_PREFIX.sequence.length);
- const rest = pickId.slice(prefix.length);
- const cut = rest.indexOf(PART_SEPARATOR);
- return cut === -1 ? rest : rest.slice(0, cut);
++ return pickId.slice(prefix.length) || null;
+ }
+
+ /**
- * Whether any point of `box` ({west, south, east, north}) is within the mesh
- * sampler's range of `centre`, the ground point under the camera.
++ * A provider's coverage bookkeeping, before the first refresh. A provider
++ * with a key waits for its status (`blocked: 'status'`); a keyless one
++ * draws at once.
+ */
-export function meshBoxInRange(box, centre) {
- // Move the camera's longitude to the box's side of the date line first:
- // clamping 179.999 into a box at -179.99 would pick its far edge.
- const lon =
- centre.lon +
- 360 * Math.round(((box.west + box.east) / 2 - centre.lon) / 360);
- const nearest = {
- lon: Math.min(box.east, Math.max(box.west, lon)),
- lat: Math.min(box.north, Math.max(box.south, centre.lat)),
++export function freshCoverage({ keyless = false } = {}) {
++ return {
++ zoom: null,
++ /** Current zoom's tiles by `z/x/y` key. */
++ tiles: new Map(),
++ /** The selected sequence drawn over the coverage, or null. */
++ highlight: null,
++ /** Tile key → its request's controller; any entry means LOADING. */
++ pending: new Map(),
++ lastError: null,
++ /**
++ * Why tile requests are paused, or null: 'status' until the key status
++ * answers, 'no-key', 'rejected' (until the provider goes off) or
++ * 'rate-limited' (until `blockTimer` fires).
++ */
++ blocked: keyless ? null : 'status',
++ blockTimer: null,
++ debounceTimer: null,
++ removeCameraListener: null,
++ terrainReady: null,
++ hint: '',
+ };
- return metresBetween(centre, nearest) <= MESH_SAMPLE_RADIUS_M;
+}
+
+/** Line instances for sequences' parts, every part picking its sequence. */
- function lineInstances(sequences, color, width) {
++function lineInstances(sequences, color, width, prefix) {
+ const attributes = {
+ color: Cesium.ColorGeometryInstanceAttribute.fromColor(color),
+ };
+ const instances = [];
+ for (const sequence of sequences)
+ for (const coordinates of sequence.parts) {
+ let positions;
+ try {
+ positions = Cesium.Cartesian3.fromDegreesArray(coordinates.flat());
+ } catch {
+ continue;
+ }
+ if (positions.length < 2) continue;
+ instances.push(
+ new Cesium.GeometryInstance({
+ geometry: new Cesium.GroundPolylineGeometry({ positions, width }),
- id: `${PICK_PREFIX.sequence}${sequence.id}`,
++ id: `${prefix}${sequence.id}`,
+ attributes,
+ }),
+ );
+ }
+ return instances;
+}
+
+/** Draped lines that follow terrain and 3D tiles (Google 3D) alike. */
+function linePrimitive(geometryInstances, asynchronous) {
+ return new Cesium.GroundPolylinePrimitive({
+ geometryInstances,
+ appearance: new Cesium.PolylineColorAppearance(),
+ classificationType: Cesium.ClassificationType.BOTH,
+ asynchronous,
+ allowPicking: true,
+ });
+}
+
- /** Hint above the street-zoom ceiling, where no coverage is drawn. */
- export const ZOOM_IN_HINT = 'Zoom in to see street-level coverage';
- /** Hint when no ground is in view within range (looking at the sky). */
- const NO_GROUND_HINT =
- 'Point the camera at the ground for street-level coverage';
++function pointsOf(sequence) {
++ let count = 0;
++ for (const part of sequence.parts) count += part.length;
++ return count;
+ }
/**
- * Camera-driven coverage: Mapillary sequence lines (z11–14) near the ground,
- * draped on terrain and 3D tiles alike. Nothing is drawn from orbit.
+ * @typedef {object} LineCoverageTuning
- * @property {number} maxTiles Line tiles drawn at once.
- * @property {number} overviewMaxTiles Overview tiles drawn at once.
++ * @property {number} maxTiles Tiles drawn at once.
+ * @property {number} maxSequences Lines drawn at once, over every tile.
++ * @property {number} [maxPoints] Line points drawn at once, over every tile (default: no limit).
+ * @property {number} lineWidthPx
- * @property {number} overviewPointPx
+ * @property {number} moveDebounceMs Camera rest before the tile set is recomputed.
- * @property {number} viewRangeMinM Street-zoom coverage reaches at least this far…
++ * @property {number} viewRangeMinM Coverage reaches at least this far…
+ * @property {number} viewRangePerHeight …or camera height times this.
- * @property {number} viewNearM Ground always covered around a tilted camera.
+ * @property {boolean} [keepOrder] Cap a tile's lines in the order decoded (default: newest first).
- * @property {number} [maxPoints] Line points drawn at once, over every tile (default: no limit).
*/
- export function createCoverage({ state, source }) {
+
+ /**
- * Camera-driven coverage from any XYZ line-tile source: overview points from
- * orbit, sequence lines near the ground. In terrain surface mode a tile is
- * drawn draped first, then swapped for lines cast to the bare earth (draped
- * lines would land on roofs), so coverage never waits on terrain heights.
++ * Camera-driven sequence lines from any XYZ line-tile source, near the
++ * ground only, draped on terrain and 3D tiles alike. Nothing is drawn from
++ * orbit.
+ *
+ * @param {object} options
- * @param {object} options.state Provider state: `context`, `services`, `viewer`, `coverage`, `sequence`, key flags.
- * @param {(tile: {x: number, y: number, z: number}, init: {signal: AbortSignal}) => Promise<{sequences: Array<object>, overview: Array<object>}>} options.fetchTile
- * A decoded tile. Sequences are `{id, parts, capturedAt, isPano}`; overview
- * points `{lon, lat, capturedAt, isPano}`. A rejection may carry
- * `keyRequired`, `keyRejected` or `retryAfterSec`.
- * @param {(heightM: number|null) => {zoom: number, kind: 'sequence'|'overview'}|null} options.zoomFor
++ * @param {object} options.state Provider state: `context`, `services`, `viewer`, `coverage` (freshCoverage), `sequence`.
++ * @param {(tile: {x: number, y: number, z: number}, init: {signal: AbortSignal}) => Promise<{sequences: Array<object>}>} options.fetchTile
++ * A decoded tile; sequences are `{id, parts, capturedAt, isPano}`. A
++ * rejection may carry `keyRequired`, `keyRejected` or `retryAfterSec`.
++ * @param {(heightM: number|null) => number|null} options.zoomFor
+ * Tile zoom for a camera height above ground; null draws nothing.
+ * @param {{coverage: string, selected: string}} options.colors
+ * @param {string} options.pickPrefix Pick-id prefix of the lines.
+ * @param {string} options.renderKey Render-governor reason.
+ * @param {LineCoverageTuning} options.tuning
+ * @param {{keyRejected?: string, rateLimited: string, tooHigh?: string}} options.messages
- * @param {(sequence: object, filter: object) => boolean} [options.passes] Whether the imagery filter keeps a line or point.
- * @param {(point: object) => number} [options.overviewPointSize] An overview point's size in pixels (default `tuning.overviewPointPx`).
++ * @param {(sequence: object, filter: object) => boolean} [options.passes] Whether the imagery filter keeps a line.
+ */
+ export function createLineCoverage({
+ state,
+ fetchTile,
+ zoomFor,
+ colors,
+ pickPrefix,
+ renderKey,
+ tuning,
+ messages,
+ passes = passesImageryFilter,
- overviewPointSize = null,
+ }) {
const { render } = state.services;
+ const perTileSequenceCap = Math.floor(tuning.maxSequences / tuning.maxTiles);
+ const perTilePointCap = tuning.maxPoints
+ ? Math.floor(tuning.maxPoints / tuning.maxTiles)
+ : Infinity;
- /** Colour for a line: the provider's, GEV cyan while selected. */
- function sequenceColor({ selected = false } = {}) {
- return selected
- ? Cesium.Color.fromCssColorString(colors.selected)
- : Cesium.Color.fromCssColorString(colors.coverage).withAlpha(0.92);
- }
-
function requestRender() {
- render?.governorRequestRender?.('mapillary-coverage');
+ render?.governorRequestRender?.(renderKey);
}
function ensureTerrainReady() {
@@@ -95,65 -141,435 +156,73 @@@
/** The imagery filter, resolved now: "since N days" moves with the clock. */
function filter() {
- return state.getFilter();
+ return state.context.getFilter();
}
- function terrainMode() {
- return (
- state.context.getSurface?.() === 'terrain' &&
- Boolean(state.context.groundCaster)
- );
- }
-
/**
* A tile's sequences, filtered then capped: capping first could leave a
- * dense tile of newer flat captures with no 360° lines at all.
- * dense tile of newer flat captures with no 360° lines at all. `measure`
- * only records what the lines need, for a draw that follows.
++ * dense tile of newer flat captures with no 360° lines at all. A line past
++ * the point budget is skipped; a shorter one may still fit.
*/
- function drawnSequences(entry, { measure = false } = {}) {
+ function drawnSequences(entry) {
const drawn = [];
const current = filter();
- const selectedId = state.sequence.selectedId ?? null;
- const cap = entry.pointCap ?? perTilePointCap;
+ let points = 0;
- let demand = 0;
for (const sequence of entry.sequenceList) {
- if (drawn.length >= PER_TILE_SEQUENCE_CAP) break;
- if (passesImageryFilter(sequence, current)) drawn.push(sequence);
++ if (drawn.length >= perTileSequenceCap) break;
+ if (!passes(sequence, current)) continue;
+ const size = pointsOf(sequence);
- demand += size;
- // The selected sequence is always drawn: its highlight is the answer
- // to a click, whatever the caps leave out. It is outside the cap, so
- // it is not counted against it.
- if (sequence.id === selectedId) {
- drawn.push(sequence);
- continue;
- }
- if (drawn.length >= perTileSequenceCap) continue;
- // A line past the point budget is skipped; a shorter one may still fit.
- if (points + size > cap) continue;
++ if (points + size > perTilePointCap) continue;
+ points += size;
+ drawn.push(sequence);
}
- // What every passing line would take: the budget is shared by it.
- entry.pointDemand = demand;
- if (!measure) {
- entry.pointsDrawn = points;
- // The cap this draw used: a share is judged against it, not against
- // later shares that redrew nothing (small steps add up).
- entry.drawnCap = cap;
- }
return drawn;
}
- /**
- * Share the point budget across the tiles in view (water-filling): a
- * sparse tile keeps what it needs and the rest goes to the dense ones,
- * so a city centre is not drawn thinner than its suburbs. Sets each
- * tile's cap; returns the tiles whose cap changes what they draw.
- */
- function shareCaps() {
- const changed = [];
- if (!tuning.maxPoints) return changed;
- const entries = [...state.coverage.tiles.values()].filter(
- (entry) => entry.kind === 'sequence',
- );
- const byDemand = [...entries].sort(
- (a, b) => (a.pointDemand || 0) - (b.pointDemand || 0),
- );
- let left = tuning.maxPoints;
- byDemand.forEach((entry, i) => {
- const share = left / (byDemand.length - i);
- const cap = Math.floor(Math.min(entry.pointDemand || 0, share));
- left -= cap;
- const before = entry.drawnCap ?? perTilePointCap;
- entry.pointCap = cap;
- // Only a change that alters what is drawn, by enough to be worth a
- // rebuild: more room for a tile that had lines left out, or well
- // under what it draws now (a small overshoot stays until the next
- // natural redraw).
- const grows =
- cap > before * (1 + SHARE_HYSTERESIS) &&
- entry.pointsDrawn < entry.pointDemand;
- const shrinks = cap < entry.pointsDrawn * (1 - SHARE_HYSTERESIS);
- if (grows || shrinks) changed.push(entry);
- });
- return changed;
- }
-
- /**
- * Once loading settles: redraw the tiles the shared budget changes,
- * keeping their old lines until the new ones are ready (no blink).
- */
- function shareBudget() {
- const changed = shareCaps();
- for (const entry of changed) redrawEntry(entry, { swap: true });
- if (changed.length) {
- requestRender();
- notify();
- }
- }
-
- /**
- * Draw one tile again from its decoded lines (filter, caps or selection
- * changed). With `swap`, its old lines stay until the new ones are ready.
- */
- function redrawEntry(entry, { swap = false } = {}) {
- cancelCast(entry);
- entry.castRequested = false;
- entry.meshParts = null;
- if (swap && entry.kind === 'sequence' && entry.primitives?.length) {
- redrawTile(entry);
- return;
- }
- detachPrimitive(entry);
- attachPrimitive(entry);
- }
-
- function pointsOf(sequence) {
- let count = 0;
- for (const part of sequence.parts) count += part.length;
- return count;
- }
-
- /**
- * Batched primitives for a tile's sequence parts: cast polylines where
- * terrain heights are cached, draped ground lines otherwise. Each batch
- * records the selection its colours were built with.
- */
+ /** Batched draped primitives for a tile's sequences. */
function buildSequencePrimitives(sequences) {
- const ground = terrainMode() ? state.context.groundCaster : null;
- const meshAt = ground ? state.context.meshSampler?.meshAt : undefined;
- const selectedId = state.sequence.selectedId ?? null;
- const draped = [];
- const cast = [];
- for (const sequence of sequences) {
- const color = Cesium.ColorGeometryInstanceAttribute.fromColor(
- sequenceColor({ selected: sequence.id === selectedId }),
- );
- const ids = partIds(sequence, pickPrefix);
- sequence.parts.forEach((coordinates, index) => {
- const flat = ground?.castLine(coordinates, { meshAt });
- let positions;
- try {
- positions = flat
- ? Cesium.Cartesian3.fromDegreesArrayHeights(flat)
- : Cesium.Cartesian3.fromDegreesArray(coordinates.flat());
- } catch {
- return;
- }
- if (positions.length < 2) return;
- const geometry = flat
- ? new Cesium.PolylineGeometry({
- positions,
- width: tuning.lineWidthPx,
- vertexFormat: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
- arcType: Cesium.ArcType.NONE,
- })
- : new Cesium.GroundPolylineGeometry({
- positions,
- width: tuning.lineWidthPx,
- });
- (flat ? cast : draped).push(
- new Cesium.GeometryInstance({
- geometry,
- id: ids[index],
- attributes: { color },
- }),
- );
- });
- }
- const primitives = [];
- for (let i = 0; i < draped.length; i += SEQUENCE_PRIMITIVE_BATCH)
- primitives.push({
- onGround: true,
- selectedId,
- primitive: new Cesium.GroundPolylinePrimitive({
- geometryInstances: draped.slice(i, i + SEQUENCE_PRIMITIVE_BATCH),
- appearance: new Cesium.PolylineColorAppearance(),
- classificationType: Cesium.ClassificationType.BOTH,
- asynchronous: true,
- allowPicking: true,
- }),
- });
- for (let i = 0; i < cast.length; i += SEQUENCE_PRIMITIVE_BATCH)
- primitives.push({
- onGround: false,
- selectedId,
- primitive: new Cesium.Primitive({
- geometryInstances: cast.slice(i, i + SEQUENCE_PRIMITIVE_BATCH),
- appearance: new Cesium.PolylineColorAppearance({ translucent: true }),
- asynchronous: true,
- allowPicking: true,
- }),
- });
- return { primitives, draped, cast: cast.length };
- }
-
- /**
- * Fetch the terrain heights a tile's lines need, then redraw it cast.
- * `castRequested` stops the redraw from casting again at once; a refresh
- * `retry`s a tile whose lines are still draped (a failed or partial cast),
- * and it is redrawn only when more of its lines can be cast.
- */
- function castTile(entry, { retry = false } = {}) {
- if ((entry.castRequested && !retry) || entry.castAbort || !terrainMode())
- return;
- entry.castRequested = true;
- entry.castAbort = new AbortController();
- const { signal } = entry.castAbort;
- const lines = [...entry.sequences.values()].flatMap(
- (sequence) => sequence.parts,
+ const instances = lineInstances(
+ sequences,
- Cesium.Color.fromCssColorString(COLORS.coverage).withAlpha(0.92),
- COVERAGE_LINE_WIDTH_PX,
++ Cesium.Color.fromCssColorString(colors.coverage).withAlpha(0.92),
++ tuning.lineWidthPx,
++ pickPrefix,
);
- const caster = state.context.groundCaster;
- caster.prepareLines(lines, { signal }).then(() => {
- if (entry.castAbort?.signal === signal) entry.castAbort = null;
- const attached = [...state.coverage.tiles.values()].includes(entry);
- if (signal.aborted || !attached || !terrainMode()) return;
- // Nothing new to cast: keep what is drawn until the next refresh.
- // Counted like buildSequencePrimitives: a cast line needs two points.
- const castable = lines.filter(
- (coords) => caster.castLine(coords)?.length >= 6,
- ).length;
- if (castable <= (entry.castLines || 0)) {
- entry.castRequested = (entry.castLines || 0) > 0;
- return;
- }
- // A remesh may have cleared the flag while this was in flight.
- entry.castRequested = true;
- redrawTile(entry);
- requestMesh(entry);
- });
- }
-
- /** Rebuild a tile's lines; the old ones stay up until the new are ready. */
- function redrawTile(entry) {
- let previous = entry.primitives;
- if (entry.swap) {
- // A swap still building: what is on screen is its old lines and
- // whichever new ones are ready. Those stay; the rest never showed.
- const shown = [...entry.swap.old];
- const building = [];
- for (const record of previous)
- (record.primitive.ready && !record.primitive.isDestroyed?.()
- ? shown
- : building
- ).push(record);
- entry.swap.stop();
- entry.swap = null;
- removePrimitives(building);
- previous = shown;
- }
- entry.primitives = [];
- attachPrimitive(entry);
- removeWhenReady(entry, previous);
- }
-
- /** Lon/lat under the camera, where mesh range is measured from. */
- function meshCentre() {
- const carto = state.viewer?.camera?.positionCartographic;
- if (!carto) return null;
- return {
- lon: Cesium.Math.toDegrees(carto.longitude),
- lat: Cesium.Math.toDegrees(carto.latitude),
- };
- }
-
- /**
- * A tile's drawn lines with bounding boxes, built once per filter; mesh
- * points are densified the first time a line is in range.
- */
- function meshParts(entry) {
- if (entry.meshParts) return entry.meshParts;
- entry.meshParts = [];
- for (const sequence of entry.sequences.values())
- for (const part of sequence.parts) {
- const box = {
- west: Infinity,
- south: Infinity,
- east: -Infinity,
- north: -Infinity,
- };
- for (const [lon, lat] of part) {
- if (lon < box.west) box.west = lon;
- if (lon > box.east) box.east = lon;
- if (lat < box.south) box.south = lat;
- if (lat > box.north) box.north = lat;
- }
- entry.meshParts.push({ part, box, points: null });
- }
- return entry.meshParts;
- }
-
- /**
- * Ask for mesh samples under a cast tile's lines within the sampler's range
- * of the camera; the rest are asked for when a camera move brings them in.
- */
- function requestMesh(entry) {
- const sampler = state.context.meshSampler;
- if (!sampler || entry.kind !== 'sequence' || !terrainMode()) return;
- const centre = meshCentre();
- if (!centre || !entry.bounds || !meshBoxInRange(entry.bounds, centre))
- return;
- const points = [];
- for (const line of meshParts(entry)) {
- if (!meshBoxInRange(line.box, centre)) continue;
- line.points ||= densifyLine(line.part, MESH_DENSIFY_DEG);
- for (const point of line.points) points.push(point);
- }
- if (points.length) sampler.request(points);
- }
-
- /** Redraw the tiles new mesh samples fall in, throttled. */
- function onMeshSampled(batch) {
- if (!terrainMode() || !state.context.isActive()) return;
- for (const entry of state.coverage.tiles.values()) {
- if (entry.kind !== 'sequence' || !entry.bounds) continue;
- const { west, south, east, north } = entry.bounds;
- if (
- batch.some(
- ([lon, lat]) =>
- lon >= west && lon <= east && lat >= south && lat <= north,
- )
- )
- state.coverage.remeshDirty.add(entry);
- }
- if (!state.coverage.remeshDirty.size || state.coverage.remeshTimer) return;
- const wait = Math.max(
- 0,
- REMESH_INTERVAL_MS - (Date.now() - (state.coverage.remeshAt || 0)),
- );
- state.coverage.remeshTimer = setTimeout(remesh, wait);
- }
-
- /** Redraw one dirty tile per idle slice, so a burst of samples never stalls a frame. */
- function remesh() {
- state.coverage.remeshTimer = null;
- state.coverage.remeshAt = Date.now();
- if (!terrainMode() || !state.context.isActive()) {
- state.coverage.remeshDirty.clear();
- return;
- }
- const attached = new Set(state.coverage.tiles.values());
- const [entry] = state.coverage.remeshDirty;
- if (!entry) return;
- state.coverage.remeshDirty.delete(entry);
- if (attached.has(entry)) {
- redrawTile(entry);
- requestRender();
- }
- if (state.coverage.remeshDirty.size)
- state.coverage.remeshTimer = setTimeout(
- () => whenIdle(remesh, 500),
- REMESH_STAGGER_MS,
+ const primitives = [];
+ for (let i = 0; i < instances.length; i += SEQUENCE_PRIMITIVE_BATCH)
+ primitives.push(
+ linePrimitive(instances.slice(i, i + SEQUENCE_PRIMITIVE_BATCH), true),
);
+ return primitives;
}
- state.coverage.remeshDirty = new Set();
- state.context.meshSampler?.onSampled(onMeshSampled);
-
/**
- * Remove a tile's previous primitives once all its current ones are ready
- * (or after a few seconds); detaching the tile removes them at once.
+ * Draw the selected sequence again over the coverage, in the selection
+ * colour, from every loaded tile it crosses; none when nothing is selected.
+ * Built at once: its tiles loaded, so the terrain table has too.
*/
- function removeWhenReady(entry, old) {
+ function highlight(sequenceId = state.sequence.selectedId) {
const scene = state.viewer?.scene;
- finishSwap(entry);
- if (!scene?.postRender) {
- removePrimitives(old);
- return;
+ if (state.coverage.highlight) {
+ scene?.groundPrimitives?.remove(state.coverage.highlight);
+ state.coverage.highlight = null;
}
- const fresh = entry.primitives;
- const started = Date.now();
- const stop = scene.postRender.addEventListener(() => {
- const ready = fresh.every(
- ({ primitive }) => primitive.ready || primitive.isDestroyed?.(),
- );
- if (!ready && Date.now() - started < SWAP_MAX_WAIT_MS) {
- requestRender();
- return;
- }
- finishSwap(entry);
- requestRender();
- });
- entry.swap = { old, stop };
- requestRender();
- }
-
- function finishSwap(entry) {
- if (!entry.swap) return;
- entry.swap.stop();
- removePrimitives(entry.swap.old);
- entry.swap = null;
- }
-
- function buildOverviewCollection(points) {
- const collection = new Cesium.PointPrimitiveCollection({
- blendOption: Cesium.BlendOption.TRANSLUCENT,
- });
- const tint = Cesium.Color.fromCssColorString(colors.coverage).withAlpha(
- 0.85,
+ if (!sequenceId || !scene) return;
+ const parts = [];
+ for (const entry of state.coverage.tiles.values())
+ parts.push(...(entry.sequences.get(sequenceId)?.parts || []));
+ const instances = lineInstances(
+ [{ id: sequenceId, parts }],
- Cesium.Color.fromCssColorString(COLORS.selected),
- COVERAGE_LINE_WIDTH_PX + 1,
++ Cesium.Color.fromCssColorString(colors.selected),
++ tuning.lineWidthPx + 1,
++ pickPrefix,
);
- const drawn = [];
- const current = filter();
- for (const point of points) {
- if (!passes(point, current)) continue;
- drawn.push(
- collection.add({
- position: Cesium.Cartesian3.fromDegrees(point.lon, point.lat),
- color: tint,
- pixelSize: overviewPointSize?.(point) ?? tuning.overviewPointPx,
- // Google 3D terrain and clouds must not hide the near side's dots;
- // the horizon cull hides the far side's, which this lets through.
- disableDepthTestDistance: Number.POSITIVE_INFINITY,
- }),
- );
- }
- return { collection, points: drawn };
- }
-
- /** Every overview point on the globe, current zoom and old alike. */
- function* overviewPoints() {
- for (const entry of drawnEntries())
- if (entry.overviewPoints) yield* entry.overviewPoints;
+ if (!instances.length) return;
+ state.coverage.highlight = scene.groundPrimitives.add(
+ linePrimitive(instances, false),
+ );
+ requestRender();
}
- // Overview points skip the depth test: hide the far hemisphere's.
- const horizon = createHorizonCull({
- getViewer: () => state.viewer,
- items: overviewPoints,
- onChange: requestRender,
- });
-
function attachPrimitive(entry) {
const scene = state.viewer?.scene;
if (!scene) return;
@@@ -194,27 -653,47 +263,27 @@@
try {
// Fetch and the one-time terrain-height table load run side by side,
// both handled from the start so an early tile failure is not unhandled.
- const [bytes] = await Promise.all([
- source.getTile('coverage', tile.z, tile.x, tile.y, {
- signal: controller.signal,
- }),
+ const [decoded] = await Promise.all([
+ fetchTile(tile, { signal: controller.signal }),
- kind === 'sequence' ? ensureTerrainReady() : null,
+ ensureTerrainReady(),
]);
- // Only an abort, a retire, a clear or a newer request for this tile
- // discards the bytes; a refresh that still wants the tile keeps them.
- const current = () =>
- state.coverage.pending.get(key) === controller &&
- !state.coverage.tiles.has(key);
+ // Only an abort, a zoom change, a clear or a newer request for this tile
- // discards the bytes; a refresh that still wants the tile keeps them.
++ // discards it; a refresh that still wants the tile keeps it.
if (
controller.signal.aborted ||
- !current() ||
- kind !== state.coverage.kind ||
+ state.coverage.pending.get(key) !== controller ||
+ state.coverage.tiles.has(key) ||
tile.z !== state.coverage.zoom
)
return;
- const decoded = decodeCoverageTile(bytes, tile);
- const entry = { kind, primitive: null, primitives: [], count: 0 };
- // Padded: vector tiles carry a small buffer past their edge.
- const bounds = tileBounds(tile.x, tile.y, tile.z);
- const pad = (bounds.east - bounds.west) * 0.05;
- entry.bounds = {
- west: bounds.west - pad,
- east: bounds.east + pad,
- south: bounds.south - pad,
- north: bounds.north + pad,
- };
- if (kind === 'sequence') {
- // Newest first, unless the provider ordered them itself; the
- // per-tile cap applies to what passes the filter.
- entry.sequenceList = tuning.keepOrder
- ? decoded.sequences
- : decoded.sequences.sort(
- (a, b) => (b.capturedAt || 0) - (a.capturedAt || 0),
- );
- entry.sequences = new Map();
- entry.total = decoded.sequences.length;
- } else {
- entry.points = decoded.overview;
- entry.sequences = new Map();
- entry.total = decoded.overview.length;
- }
++ const sequences = decoded?.sequences || [];
+ const entry = { primitives: [], sequences: new Map() };
- // Newest first; the per-tile cap applies to what passes the filter.
- entry.sequenceList = decoded.sequences.sort(
- (a, b) => (b.capturedAt || 0) - (a.capturedAt || 0),
- );
++ // Newest first, unless the provider ordered them itself; the per-tile
++ // cap applies to what passes the filter.
++ entry.sequenceList = tuning.keepOrder
++ ? sequences
++ : sequences.sort((a, b) => (b.capturedAt || 0) - (a.capturedAt || 0));
++ entry.total = sequences.length;
attachPrimitive(entry);
state.coverage.tiles.set(key, entry);
state.coverage.lastError = null;
@@@ -227,11 -704,15 +296,13 @@@
state.coverage.pending.get(key) !== controller
)
return;
- state.coverage.lastError = error?.message || msg('Coverage tile failed');
- if (error?.keyRequired) state.keyRequired = true;
- if (error?.keyRejected) {
- // Every other tile would be refused too: stop asking.
- state.keyRejected = true;
+ // Every other tile would be refused too: stop asking.
+ if (error?.keyRejected) block('rejected');
+ else if (error?.keyRequired) block('no-key');
+ else if (error?.retryAfterSec) block('rate-limited', error.retryAfterSec);
- else state.coverage.lastError = error?.message || 'Coverage tile failed';
++ else
+ state.coverage.lastError =
- messages.keyRejected || state.coverage.lastError;
- }
- if (error?.retryAfterSec) holdFor(error.retryAfterSec);
++ error?.message || msg('Coverage tile failed');
} finally {
// Only the request that still owns the key settles it: a superseded one
// must not drop a newer request's entry (which is what counts as loading).
@@@ -242,42 -728,55 +313,43 @@@
}
/**
- * Pause tile requests (see `blocked` in state.js). A rate limit keeps what
- * is drawn and refreshes once its wait is over; a key problem outranks it,
- * and a rejected key holds until `unblock` (the layer goes off).
- * The source is rate-limiting: keep what is drawn, request nothing until the
- * wait is over, then refresh once.
++ * Pause tile requests (see `blocked` in freshCoverage). A rate limit keeps
++ * what is drawn and refreshes once its wait is over; a key problem
++ * outranks it, and a rejected key holds until `unblock` (the provider goes
++ * off).
*/
- function holdFor(seconds) {
- clearTimeout(state.coverage.holdTimer);
- state.coverage.holdUntil = Date.now() + seconds * 1000;
- state.coverage.lastError = messages.rateLimited;
- state.coverage.holdTimer = setTimeout(() => {
- state.coverage.holdTimer = null;
- state.coverage.holdUntil = 0;
- if (state.coverage.lastError === messages.rateLimited)
- state.coverage.lastError = null;
- refresh();
- }, seconds * 1000);
- }
-
- /** Forget refusals when the provider goes off, so the next run asks again. */
- function resetErrors() {
- clearTimeout(state.coverage.holdTimer);
- state.coverage.holdTimer = null;
- state.coverage.holdUntil = 0;
+ function block(reason, retryAfterSec = 0) {
+ const current = state.coverage.blocked;
+ if (current === 'rejected') return;
+ if (reason === 'rate-limited' && current === 'no-key') return;
+ clearTimeout(state.coverage.blockTimer);
+ state.coverage.blockTimer = null;
+ state.coverage.blocked = reason;
+ if (reason === 'rate-limited')
+ state.coverage.blockTimer = setTimeout(() => {
+ state.coverage.blockTimer = null;
+ state.coverage.blocked = null;
+ refresh();
+ }, retryAfterSec * 1000);
+ }
+
- /** The layer went off: forget refusals and errors, so the next run asks again. */
++ /** The provider went off: forget refusals and errors, so the next run asks again. */
+ function unblock() {
+ clearTimeout(state.coverage.blockTimer);
+ state.coverage.blockTimer = null;
+ if (['rejected', 'rate-limited'].includes(state.coverage.blocked))
+ state.coverage.blocked = null;
state.coverage.lastError = null;
- state.keyRejected = false;
- }
-
- /** Drop the previous zoom's tiles once the new ones are on screen. */
- function purgeStale() {
- clearTimeout(state.coverage.staleTimer);
- state.coverage.staleTimer = null;
- if (!state.coverage.stale.size) return;
- for (const entry of state.coverage.stale.values()) detachPrimitive(entry);
- state.coverage.stale.clear();
- requestRender();
}
- /** Move tiles to the stale set: the old zoom shows until the new one loads. */
- function retire() {
- for (const controller of state.coverage.pending.values())
- controller.abort();
- state.coverage.pending.clear();
- for (const [key, entry] of state.coverage.tiles) {
- cancelCast(entry);
- const previous = state.coverage.stale.get(key);
- if (previous) detachPrimitive(previous);
- state.coverage.stale.set(key, entry);
+ /** The server's key status: until it answers, nothing is requested. */
+ function setKeyStatus(configured) {
+ if (!configured) block('no-key');
+ else if (['status', 'no-key'].includes(state.coverage.blocked)) {
+ state.coverage.blocked = null;
+ refresh();
}
- state.coverage.tiles.clear();
- clearTimeout(state.coverage.staleTimer);
- state.coverage.staleTimer = setTimeout(purgeStale, STALE_TILE_MAX_MS);
+ notify();
}
function notify() {
@@@ -294,35 -805,37 +366,35 @@@
const height = Number.isFinite(cameraHeight)
? cameraHeight - (ground ?? 0)
: null;
- const zoom = coverageZoomForHeight(height);
- if (zoom == null) return { hint: ZOOM_IN_HINT };
- const level = zoomFor(height);
- const zoom = level?.zoom ?? null;
- const kind = level?.kind ?? null;
- // At street zooms the rays meet the ground where it really is (1,600 m up
- // in Denver; Google 3D hides the globe) and stop short of the horizon.
- const ranged =
- kind === 'sequence'
- ? {
- groundHeight: ground,
- maxRange: Math.max(
- tuning.viewRangeMinM,
- height * tuning.viewRangePerHeight,
- ),
- }
- : {};
- // Tilted street views rank tiles along the line of sight, from the ground
- // under the camera to the ground at the centre of the screen.
- const focus = kind === 'sequence' ? viewFocus(viewer, ranged) : null;
- let bbox = visibleBbox(viewer, {
- ...ranged,
- // A tilted view's screen rows jump from the first metres to the horizon:
- // keep the ground around the camera too. Looking down needs no help.
- nearRange: focus && isTilted(focus, height) ? tuning.viewNearM : null,
++ const zoom = zoomFor(height);
++ if (zoom == null) return { hint: messages.tooHigh || ZOOM_IN_HINT };
+ // Rays meet the ground where it really is (1,600 m up in Denver) and stop
+ // short of the horizon, which would stretch the box to the world.
+ const ranged = {
+ groundHeight: ground,
+ maxRange: Math.max(
- SEQUENCE_VIEW_RANGE_MIN_M,
- height * SEQUENCE_VIEW_RANGE_PER_HEIGHT,
++ tuning.viewRangeMinM,
++ height * tuning.viewRangePerHeight,
+ ),
+ };
+ const bbox = visibleBbox(viewer, ranged);
+ if (!bbox) return { hint: NO_GROUND_HINT };
+ // Ranked from between the camera's ground point and the screen centre's:
+ // a tilted view's box centre can sit kilometres past both.
+ const tiles = tilesForBbox(bbox, zoom, {
- limit: COVERAGE_MAX_TILES,
++ limit: tuning.maxTiles,
+ from: viewFocus(viewer, ranged),
});
- if (kind === 'overview' && (!bbox || zoom <= 1))
- bbox = [-180, -85, 180, 85];
- if (zoom == null || !bbox) {
- state.coverage.hint =
- zoom == null && Number.isFinite(height) && messages.tooHigh
- ? messages.tooHigh
- : msg('Point the camera at the globe for street-level coverage');
+ return { zoom, tiles };
+ }
+
+ /** Recompute the tile set for the current camera and reconcile primitives. */
+ function refresh() {
+ const viewer = state.viewer;
- if (!viewer || !state.isActive() || state.coverage.blocked) return;
++ if (!viewer || !state.context.isActive() || state.coverage.blocked) return;
+ const { zoom, tiles, hint } = wantedTiles(viewer);
+ if (hint) {
+ state.coverage.hint = hint;
clear();
notify();
return;
@@@ -379,47 -908,157 +448,53 @@@
requestRender();
}
-- /** Rebuild every loaded tile from its decoded cache (after a filter change). */
++ /** Rebuild every loaded tile from its decoded lines (after a filter change). */
function rebuild() {
- purgeStale();
- // What each tile's lines need under the new filter, then the shares,
- // then one redraw each.
- for (const entry of state.coverage.tiles.values())
- if (entry.kind === 'sequence') drawnSequences(entry, { measure: true });
- shareCaps();
- for (const entry of state.coverage.tiles.values()) redrawEntry(entry);
+ for (const entry of state.coverage.tiles.values()) {
+ detachPrimitive(entry);
+ attachPrimitive(entry);
+ }
+ highlight();
requestRender();
notify();
}
- /**
- * Load every tile again (a source that filters on its server had its
- * filter changed); the lines drawn now show until the new ones are in.
- */
++ /** Load every tile again (a source that filters on its server had its filter changed). */
+ function reload() {
- retire();
++ clear();
+ refresh();
+ }
+
/**
- * Redraw tiles draped or cast for the new surface mode, then re-pick the
- * zoom, since the ground height under the camera may have changed.
- */
- function setSurface() {
- if (!state.context.isActive()) return;
- rebuild();
- refresh();
- }
-
- /** Recolour every part of a sequence in one ready primitive. */
- function recolorInstances(primitive, sequence, selected) {
- const value = sequenceColor({ selected });
- for (const instanceId of partIds(sequence, pickPrefix)) {
- try {
- const attributes = primitive.getGeometryInstanceAttributes(instanceId);
- if (attributes)
- attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(
- value,
- attributes.color,
- );
- } catch {
- /* instance not in this primitive */
- }
- }
- }
-
- /** Every tile on the globe: the current zoom's and the stale zoom's. */
- function drawnEntries() {
- return [...state.coverage.tiles.values(), ...state.coverage.stale.values()];
- }
-
- /** A tile's primitives on the globe: its own, and the ones a swap still shows. */
- function drawnRecords(entry) {
- const records = entry.primitives || [];
- return entry.swap ? [...records, ...entry.swap.old] : records;
- }
-
- /** Recolour one sequence, every part of it, in place (selection highlight). */
- function recolorSequence(id, selected) {
- // Selected but left out by a cap: draw it (it is always admitted).
- if (selected && (tuning.maxPoints || 0) > 0)
- for (const entry of state.coverage.tiles.values())
- if (
- entry.kind === 'sequence' &&
- !entry.sequences.has(id) &&
- entry.sequenceList.some(
- (sequence) => sequence.id === id && passes(sequence, filter()),
- )
- )
- redrawEntry(entry, { swap: true });
- for (const entry of drawnEntries()) {
- const sequence = entry.sequences.get(id);
- if (!sequence) continue;
- for (const record of drawnRecords(entry)) {
- // Still building: `syncSelection` catches it up once it is ready.
- if (!record.primitive.ready) continue;
- recolorInstances(record.primitive, sequence, selected);
- if (selected) record.selectedId = id;
- else if (record.selectedId === id) record.selectedId = null;
- }
- }
- requestRender();
- }
-
- /**
- * Bring a ready primitive's highlight up to the current selection, when
- * it was built with another one (or none). True when it changed.
- */
- function syncSelection(entry, record) {
- const current = state.sequence.selectedId ?? null;
- if (record.selectedId === current || !record.primitive.ready) return false;
- const previous =
- record.selectedId && entry.sequences.get(record.selectedId);
- if (previous) recolorInstances(record.primitive, previous, false);
- const next = current && entry.sequences.get(current);
- if (next) recolorInstances(record.primitive, next, true);
- record.selectedId = current;
- return true;
- }
-
- /**
- * A primitive cannot be recoloured until it is ready, so while any is
- * building, catch each one up with the selection as it becomes ready.
- */
- function watchSelection() {
- const scene = state.viewer?.scene;
- if (state.coverage.stopSelectionWatch || !scene?.postRender) return;
- const stop = scene.postRender.addEventListener(() => {
- let building = false;
- let changed = false;
- for (const entry of drawnEntries()) {
- for (const record of entry.primitives || []) {
- if (!record.primitive.ready) building = true;
- else if (syncSelection(entry, record)) changed = true;
- }
- // Lines a swap still shows were ready (or never show): catch up only.
- for (const record of entry.swap?.old || [])
- if (syncSelection(entry, record)) changed = true;
- }
- if (changed) requestRender();
- if (!building) stopSelectionWatch();
- });
- state.coverage.stopSelectionWatch = stop;
- }
-
- function stopSelectionWatch() {
- state.coverage.stopSelectionWatch?.();
- state.coverage.stopSelectionWatch = null;
- }
-
- /**
- * Sequences (or overview points) drawn. A sequence that crosses a tile
- * edge is in both tiles' lists, so sequences count once by id.
+ * Sequences drawn. A sequence that crosses a tile edge is in both tiles'
+ * lists, so sequences count once by id.
*/
function sequenceCount() {
const ids = new Set();
- let points = 0;
for (const entry of state.coverage.tiles.values())
- if (entry.kind === 'sequence')
- for (const id of entry.sequences.keys()) ids.add(id);
- else points += entry.count;
- return ids.size + points;
+ for (const id of entry.sequences.keys()) ids.add(id);
+ return ids.size;
+ }
+
+ /** What the panel and the layer list show: count, LOADING, key gate, error. */
+ function stats() {
+ const { blocked } = state.coverage;
+ return {
+ count: sequenceCount(),
+ // Waiting for the key status is loading too, not an empty view.
+ loading:
+ state.coverage.pending.size > 0 ||
- (blocked === 'status' && state.isActive()),
++ (blocked === 'status' && state.context.isActive()),
+ hint: state.coverage.hint,
+ keyRequired: blocked === 'no-key' || blocked === 'rejected',
+ keyRejected: blocked === 'rejected',
+ error:
+ blocked === 'rejected'
- ? KEY_REJECTED_MESSAGE
++ ? messages.keyRejected || null
+ : blocked === 'rate-limited'
- ? RATE_LIMITED_MESSAGE
++ ? messages.rateLimited
+ : state.coverage.lastError,
+ };
}
return {
@@@ -427,10 -1066,11 +502,12 @@@
detach,
refresh,
clear,
- resetErrors,
+ unblock,
+ setKeyStatus,
rebuild,
+ reload,
- setSurface,
- recolorSequence,
+ highlight,
+ sequenceCount,
+ stats,
};
}
diff --cc src/layers/streetLevel/lineCoverage.test.mjs
index 171368556,7fdc19773..c3b1b6142
--- a/src/layers/streetLevel/lineCoverage.test.mjs
+++ b/src/layers/streetLevel/lineCoverage.test.mjs
@@@ -1,107 -1,72 +1,148 @@@
import assert from 'node:assert/strict';
import test from 'node:test';
-import { createLineCoverage } from './lineCoverage.js';
+import * as Cesium from 'cesium';
- import { createCoverage, ZOOM_IN_HINT } from './coverage.js';
- import { freshCoverage } from './state.js';
+ import {
- coverageViewer,
- tileCentre,
-} from '../../testSupport/streetLevelFakes.mjs';
-import { until } from '../../testSupport/kartaViewFakes.mjs';
++ createLineCoverage,
++ freshCoverage,
++ ZOOM_IN_HINT,
++} from './lineCoverage.js';
+import { resolveFilter } from './filter.js';
- import { encodeCoverageTile } from './coverageFixture.mjs';
++import { encodeCoverageTile } from './providers/mapillary/coverageFixture.mjs';
++import { decodeCoverageTile } from './providers/mapillary/decode.js';
+import { rayCamera } from '../../testSupport/streetLevelFakes.mjs';
- import { COVERAGE_MAX_SEQUENCES, COVERAGE_MAX_TILES } from './policy.js';
- import { lonToTileX, latToTileY, tileBounds } from './tileMath.js';
++import {
++ COLORS,
++ COVERAGE_TUNING,
++ KEY_REJECTED_MESSAGE,
++ PICK_PREFIX,
++ RATE_LIMITED_MESSAGE,
++} from './providers/mapillary/policy.js';
++import {
++ coverageZoomForHeight,
++ lonToTileX,
++ latToTileY,
++ tileBounds,
++} from './tileMath.js';
+
-const TUNING = Object.freeze({
- maxTiles: 9,
- overviewMaxTiles: 0,
- maxSequences: 900,
- lineWidthPx: 2,
- overviewPointPx: 2,
- moveDebounceMs: 10,
- viewRangeMinM: 2_500,
- viewRangePerHeight: 10,
- viewNearM: 1_000,
-});
++const { maxSequences: COVERAGE_MAX_SEQUENCES, maxTiles: COVERAGE_MAX_TILES } =
++ COVERAGE_TUNING;
+
-/**
- * Line coverage over one tile holding one line, on a viewer looking down from
- * `height`. `fetchTile` answers with that line unless `fail` says otherwise.
- */
-function setup(
- t,
- {
- zoomFor,
- messages = { rateLimited: 'busy' },
- passes,
- fail,
- decoded = null,
- tuning = TUNING,
- overviewPointSize = null,
- } = {},
-) {
++/** Line coverage as the Mapillary provider builds it, over `source`. */
++function createCoverage({ state, source }) {
++ return createLineCoverage({
++ state,
++ fetchTile: async (tile, { signal }) =>
++ decodeCoverageTile(
++ await source.getTile('coverage', tile.z, tile.x, tile.y, { signal }),
++ tile,
++ ),
++ zoomFor: coverageZoomForHeight,
++ colors: COLORS,
++ pickPrefix: PICK_PREFIX.sequence,
++ renderKey: 'mapillary-coverage',
++ tuning: COVERAGE_TUNING,
++ messages: {
++ keyRejected: KEY_REJECTED_MESSAGE,
++ rateLimited: RATE_LIMITED_MESSAGE,
++ },
++ });
++}
+
+const RAD = Math.PI / 180;
+// Node has no WebGL context to report line-width limits; a browser's
+// context sets these on startup, and appearances validate against them.
+Cesium.ContextLimits._minimumAliasedLineWidth = 1;
+Cesium.ContextLimits._maximumAliasedLineWidth = 10;
+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+/** A scene collection that remembers what is on the globe. */
+function collection() {
+ const items = new Set();
+ return {
+ items,
+ add(primitive) {
+ items.add(primitive);
+ return primitive;
+ },
+ remove(primitive) {
+ return items.delete(primitive);
+ },
+ };
+}
+
+/** The centre of the z14 tile holding a point, so a small view is one tile. */
+function tileCentre(lon, lat) {
+ const x = lonToTileX(lon, 14);
+ const y = latToTileY(lat, 14);
+ const { west, east, south, north } = tileBounds(x, y, 14);
+ return {
+ tile: { x, y, z: 14 },
+ lon: (west + east) / 2,
+ lat: (south + north) / 2,
+ };
+}
+
+/** A viewer looking straight down on a 0.004° square around `view`. */
+function fakeViewer(view) {
+ return {
+ view,
+ scene: {
+ canvas: { clientWidth: 100, clientHeight: 100 },
+ globe: { show: false, ellipsoid: Cesium.Ellipsoid.WGS84 },
+ groundPrimitives: collection(),
+ primitives: collection(),
+ },
+ camera: {
+ get positionCartographic() {
+ return {
+ longitude: view.lon * RAD,
+ latitude: view.lat * RAD,
+ height: view.height,
+ };
+ },
+ pickEllipsoid(point) {
+ return Cesium.Cartesian3.fromDegrees(
+ view.lon - 0.002 + (point.x / 100) * 0.004,
+ view.lat + 0.002 - (point.y / 100) * 0.004,
+ );
+ },
+ },
+ };
+}
+
+/** A source whose tile requests the test resolves, one call at a time. */
+function deferredSource() {
+ const calls = [];
+ return {
+ calls,
+ getTile(layer, z, x, y, { signal } = {}) {
+ return new Promise((resolve, reject) => {
+ calls.push({ key: `${z}/${x}/${y}`, z, signal, resolve, reject });
+ });
+ },
+ };
+}
+
+function setup() {
const centre = tileCentre(-121.4944, 38.5816);
- const viewer = coverageViewer(
- { lon: centre.lon, lat: centre.lat, height: 900 },
- t,
- );
+ const viewer = fakeViewer({ lon: centre.lon, lat: centre.lat, height: 900 });
+ const source = deferredSource();
const state = {
viewer,
services: {},
- keyRequired: false,
- keyRejected: false,
+ enabled: true,
+ providerOn: true,
+ filter: { pano: 'all', sinceDays: 0 },
- getFilter: () => resolveFilter(state.filter),
- isActive: () => state.enabled && state.providerOn,
- notify() {},
+ context: {
- getFilter: () => ({ pano: 'all', sinceMs: null }),
- isActive: () => true,
++ getFilter: () => resolveFilter(state.filter),
++ isActive: () => state.enabled && state.providerOn,
+ notify() {},
- getSurface: () => 'draped',
- groundCaster: null,
- meshSampler: null,
+ },
coverage: {
- zoom: null,
- kind: null,
- tiles: new Map(),
- stale: new Map(),
- staleTimer: null,
- pending: new Map(),
- lastError: null,
- holdUntil: 0,
- holdTimer: null,
- debounceTimer: null,
- removeCameraListener: null,
+ ...freshCoverage(),
+ // The key status is in; skip Cesium's one-time terrain table download.
+ blocked: null,
terrainReady: Promise.resolve(),
- hint: '',
},
sequence: { selectedId: null },
};
diff --cc src/layers/streetLevel/marker.js
index fb12883de,047eebcc2..a61036b84
--- a/src/layers/streetLevel/marker.js
+++ b/src/layers/streetLevel/marker.js
@@@ -1,13 -1,31 +1,29 @@@
import * as Cesium from 'cesium';
- import { positionMarkerGlyph } from './glyphs.js';
+ import { positionMarkerGlyph, viewConeMarkerGlyph } from './glyphs.js';
import { COLORS, POSITION_PICK_ID } from './policy.js';
-import { refineHeights } from './groundCast.js';
import { createHorizonCull } from './view.js';
const SPRITE_ID = 'street-level:marker';
+ function markerLook(style) {
+ if (style?.kind === 'view-cone') {
+ const color = style.color || COLORS.position;
+ return {
+ key: `view-cone:${color}`,
+ image: viewConeMarkerGlyph({ color }),
+ size: 48,
+ };
+ }
+ return {
+ key: 'pin',
+ image: positionMarkerGlyph({ color: COLORS.position }),
+ size: 40,
+ };
+ }
+
-/** On-globe marker for the open image; in terrain mode it stands on bare earth. */
-export function createMarker({ state, parts }) {
+/** On-globe marker for the open image, clamped to the ground. */
+export function createMarker({ state }) {
const { render, sprites } = state.services;
- let last = null;
function requestRender() {
render?.governorRequestRender?.('street-level-marker');
@@@ -29,10 -47,38 +45,10 @@@
sprites?.registerSpriteCollection?.(SPRITE_ID, state.marker.collection);
}
- /** Move (or create) the marker; a null position removes it. */
- function set(position, bearing) {
- /**
- * Terrain-mode height (bare earth refined by mesh samples), or null to
- * clamp. Requests a missing terrain cell or mesh sample as a side effect.
- */
- function castHeight(position) {
- const ground = parts?.groundCaster;
- if (state.surface !== 'terrain' || !ground) return null;
- const { lon, lat } = position;
- const dem = ground.groundAt(lon, lat);
- if (dem === null) {
- ground.prepare([[lon, lat]]).then((ready) => {
- if (ready && last?.position === position)
- set(position, last.bearing, last.style);
- });
- return null;
- }
- const mesh = parts.meshSampler?.meshAt(lon, lat);
- if (mesh === undefined) parts.meshSampler?.request([[lon, lat]]);
- return refineHeights([{ dem, mesh }])[0];
- }
-
- // A new mesh sample may move the marker onto (or off) the road surface.
- parts?.meshSampler?.onSampled(() => {
- if (last && state.surface === 'terrain')
- set(last.position, last.bearing, last.style);
- });
-
+ /** Move (or create) the marker; null removes it. `style`: the provider's `marker`. */
+ function set(position, bearing, style = null) {
const collection = state.marker.collection;
if (!collection) return;
- last = position ? { position, bearing, style } : null;
if (!position) {
collection.removeAll();
state.marker.billboard = null;
@@@ -40,17 -86,32 +56,23 @@@
requestRender();
return;
}
- const height = castHeight(position);
- const cartesian = Cesium.Cartesian3.fromDegrees(
- position.lon,
- position.lat,
- height ?? 0,
- );
- const heightReference =
- height === null
- ? Cesium.HeightReference.CLAMP_TO_GROUND
- : Cesium.HeightReference.NONE;
+ const cartesian = Cesium.Cartesian3.fromDegrees(position.lon, position.lat);
+ const look = markerLook(style);
+ if (state.marker.billboard && state.marker.look !== look.key) {
+ collection.remove?.(state.marker.billboard);
+ state.marker.billboard = null;
+ }
if (!state.marker.billboard) {
+ state.marker.look = look.key;
state.marker.billboard = collection.add({
id: POSITION_PICK_ID,
position: cartesian,
- image: positionMarkerGlyph({ color: COLORS.position }),
- imageId: 'sl-position',
- width: 40,
- height: 40,
+ image: look.image,
+ imageId: `sl-position:${look.key}`,
+ width: look.size,
+ height: look.size,
alignedAxis: Cesium.Cartesian3.UNIT_Z,
- heightReference,
+ heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
verticalOrigin: Cesium.VerticalOrigin.CENTER,
});
diff --cc src/layers/streetLevel/marker.test.mjs
index 192016f0c,e9e565bb6..d0a1e486a
--- a/src/layers/streetLevel/marker.test.mjs
+++ b/src/layers/streetLevel/marker.test.mjs
@@@ -79,11 -152,64 +80,33 @@@ test('the marker is clamped to the grou
billboard.heightReference,
Cesium.HeightReference.CLAMP_TO_GROUND,
);
- assert.deepEqual(ground.prepares[0].points, [[SPOT.lon, SPOT.lat]]);
- ground.dem = 10;
- ground.prepares[0].resolve(true);
- await new Promise((resolve) => setTimeout(resolve, 0));
- assert.equal(billboard.heightReference, Cesium.HeightReference.NONE);
- assert.ok(Math.abs(heightOf(billboard) - (11 + MESH_LIFT_M)) < 1e-3);
- assert.equal(billboard.rotation, -Cesium.Math.toRadians(45), 'bearing kept');
-});
-
-test('ground that arrives after the marker moved on does not move it back', async () => {
- const { parts, ground } = terrainParts();
- const { state, marker } = setup({ parts, surface: 'terrain' });
- marker.set(SPOT, 0);
- const elsewhere = { lon: -121.5, lat: 38.6 };
- marker.set(elsewhere, 0);
- ground.dem = 10;
- ground.prepares[0].resolve(true);
- await new Promise((resolve) => setTimeout(resolve, 0));
- const placed = Cesium.Cartographic.fromCartesian(
- state.marker.billboard.position,
- );
- assert.ok(
- Math.abs(Cesium.Math.toDegrees(placed.longitude) - elsewhere.lon) < 1e-9,
- );
-});
-
-test('draped mode clamps the marker to the globe whatever the ground says', () => {
- const { parts, ground } = terrainParts({ dem: 10, mesh: 11 });
- const { state, marker } = setup({ parts, surface: 'draped' });
- marker.set(SPOT, 0);
- assert.equal(
- state.marker.billboard.heightReference,
- Cesium.HeightReference.CLAMP_TO_GROUND,
- );
- assert.equal(ground.prepares.length, 0);
+ assert.equal(billboard.rotation, -Cesium.Math.toRadians(45));
+ // Moving it keeps the same billboard.
+ marker.set({ lon: -121.5, lat: 38.6 }, 90);
+ assert.equal(state.marker.billboard, billboard);
+ const placed = Cesium.Cartographic.fromCartesian(billboard.position);
+ assert.ok(Math.abs(Cesium.Math.toDegrees(placed.longitude) + 121.5) < 1e-9);
+ assert.equal(billboard.rotation, -Cesium.Math.toRadians(90));
});
+
+ test('a Street View photo gets a blue view cone; a Mapillary photo GEV\u2019s pin', () => {
+ const { state, marker } = setup();
+ const removed = [];
+ state.marker.collection.remove = (billboard) => removed.push(billboard);
+ const streetView = { kind: 'view-cone', color: '#4285f4' };
+ marker.set({ lon: -121.49, lat: 38.58 }, 45, streetView);
+ const cone = state.marker.billboard;
+ assert.equal(cone.imageId, 'sl-position:view-cone:#4285f4');
+ assert.equal(
+ cone.rotation,
+ -Cesium.Math.toRadians(45),
+ 'it turns with the view',
+ );
+ // Dragging the panorama keeps the look and the billboard.
+ marker.set({ lon: -121.49, lat: 38.58 }, 90, streetView);
+ assert.equal(state.marker.billboard, cone);
- // Re-placed for a surface change: still the cone.
- marker.setSurface();
- assert.equal(state.marker.billboard, cone);
+ // A Mapillary photo next (its provider has no marker): the pin.
+ marker.set({ lon: -121.49, lat: 38.58 }, 90, undefined);
+ assert.equal(state.marker.billboard.imageId, 'sl-position:pin');
+ assert.deepEqual(removed, [cone]);
+ });
diff --cc src/layers/streetLevel/photoViewer.js
index 000000000,705fa8524..7aaa6f948
mode 000000,100644..100644
--- a/src/layers/streetLevel/photoViewer.js
+++ b/src/layers/streetLevel/photoViewer.js
@@@ -1,0 -1,926 +1,935 @@@
+ import {
+ createPanoramaRenderer,
+ PANO_FOV_DEFAULT_DEG,
+ wrapDegrees,
+ } from './panorama.js';
+ import { imageSize } from './imageSize.js';
+ import { msg, t } from '../../i18n/index.js';
+
+ /** A photo download (tens of kilobytes to a few megabytes). */
++/** EXPAND puts the viewer's wrap full screen, or (iPhone) opens it as a popover. */
++const EXPANDED_SELECTOR =
++ '.sl-viewer-wrap:fullscreen, .sl-viewer-wrap:popover-open';
++
+ export const IMAGE_TIMEOUT_MS = 15_000;
+
+ /** A picture file or decoded side past these is refused (a photo is a few MB). */
+ export const MAX_IMAGE_BYTES = 48 * 1024 * 1024;
+ export const MAX_IMAGE_SIDE = 16_384;
+ /** 64 MP: 256 MB once decoded to RGBA. A 16,384 px square is four times that. */
+ export const MAX_IMAGE_PIXELS = 8_192 * 8_192;
+ /** Where in a file to look for its dimensions (a JPEG's EXIF comes first). */
+ const HEADER_BYTES = 256 * 1024;
+
+ /** Whether a picture this size is past what the viewer decodes. */
+ export function tooManyPixels(width, height) {
+ return (
+ width > MAX_IMAGE_SIDE ||
+ height > MAX_IMAGE_SIDE ||
+ width * height > MAX_IMAGE_PIXELS
+ );
+ }
+
+ /** Panorama texture widths: enough for a docked viewer, and for an expanded one. */
+ export const PANO_MID_SIZE = Object.freeze([2048, 1024]);
+ export const PANO_FULL_SIZE = Object.freeze([4096, 2048]);
+
+ /**
+ * Load an image within the timeout. A CORS-clean one (for WebGL) is decoded
+ * off the main thread into an ImageBitmap where the browser can: uploading
+ * a decoded bitmap costs a fraction of uploading an <img> (90 ms → 15 ms for
+ * 4096×2048 on a phone-class CPU). `resize` shrinks a bitmap while decoding
+ * it (a panorama larger than any texture the viewer uploads).
+ * @param {string} url
+ * @param {{crossOrigin?: boolean, timeoutMs?: number, resize?: [number, number]|null, failure?: string}} [options]
+ */
+ export function loadImage(
+ url,
+ {
+ crossOrigin = true,
+ timeoutMs = IMAGE_TIMEOUT_MS,
+ resize = null,
+ failure = msg('The photo could not be loaded'),
+ signal = null,
+ } = {},
+ ) {
+ if (
+ crossOrigin &&
+ url &&
+ typeof globalThis.createImageBitmap === 'function' &&
+ typeof globalThis.fetch === 'function'
+ )
+ return loadBitmap(url, timeoutMs, resize, failure, signal);
+ return new Promise((resolve, reject) => {
+ if (!url) return reject(new Error(failure));
+ if (signal?.aborted) return reject(new Error(failure));
+ const image = new Image();
+ if (crossOrigin) image.crossOrigin = 'anonymous';
+ image.decoding = 'async';
+ // Stop the download: another photo opened, or the time ran out.
+ const stop = () => {
+ clearTimeout(timer);
+ signal?.removeEventListener?.('abort', stop);
+ image.onload = image.onerror = null;
+ image.src = '';
+ reject(new Error(failure));
+ };
+ const timer = setTimeout(stop, timeoutMs);
+ signal?.addEventListener?.('abort', stop, { once: true });
+ const settle = () => {
+ clearTimeout(timer);
+ signal?.removeEventListener?.('abort', stop);
+ };
+ image.onload = () => {
+ settle();
+ // An <img> reads no header first: refuse what it decoded too large.
+ if (tooManyPixels(image.naturalWidth || 0, image.naturalHeight || 0)) {
+ image.src = '';
+ reject(oversized(failure));
+ return;
+ }
+ resolve(image);
+ };
+ image.onerror = () => {
+ settle();
+ reject(new Error(failure));
+ };
+ image.src = url;
+ });
+ }
+
+ async function loadBitmap(url, timeoutMs, resize, failure, signal) {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
+ // The caller's abort (the photo changed) stops a multi-megabyte download.
+ const onAbort = () => controller.abort();
+ if (signal?.aborted) controller.abort();
+ signal?.addEventListener?.('abort', onAbort, { once: true });
+ try {
+ const response = await fetch(url, {
+ mode: 'cors',
+ signal: controller.signal,
+ });
+ if (!response.ok) throw new Error(failure);
+ // Picture hosts are not ours: refuse a file or an image past any real
+ // photo's size before it is decoded.
+ const length = Number(response.headers?.get?.('content-length'));
+ if (length > MAX_IMAGE_BYTES) throw oversized(failure);
+ const blob = await boundedBlob(response, failure);
+ // Its declared size, before anything decodes it.
+ const size = imageSize(
+ new Uint8Array(await blob.slice(0, HEADER_BYTES).arrayBuffer()),
+ );
+ if (size && tooManyPixels(size.width, size.height))
+ throw oversized(failure);
+ const bitmap = await (resize
+ ? createImageBitmap(blob, {
+ resizeWidth: resize[0],
+ resizeHeight: resize[1],
+ resizeQuality: 'high',
+ })
+ : createImageBitmap(blob));
+ // (A resized decode reports its new size: this guards unresized ones.)
+ if (tooManyPixels(bitmap.width, bitmap.height)) {
+ bitmap.close?.();
+ throw oversized(failure);
+ }
+ return bitmap;
+ } catch (error) {
+ // A size refusal stays one: the viewer must not fetch it another way.
+ if (error?.tooLarge) throw error;
+ throw new Error(failure);
+ } finally {
+ clearTimeout(timer);
+ signal?.removeEventListener?.('abort', onAbort);
+ }
+ }
+
+ /**
+ * A picture refused for its size (`tooLarge`): the viewer will not load
+ * that file another way, an <img> having no size limit at all.
+ */
+ export function oversized(failure) {
+ return Object.assign(new Error(failure), { tooLarge: true });
+ }
+
+ /**
+ * The body as a Blob, read with a running count so a host that sends no
+ * length (or a false one) cannot fill memory before the cap is checked.
+ */
+ async function boundedBlob(response, failure) {
+ const reader = response.body?.getReader?.();
+ if (!reader) {
+ const blob = await response.blob();
+ if (blob.size > MAX_IMAGE_BYTES) throw oversized(failure);
+ return blob;
+ }
+ const chunks = [];
+ let total = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > MAX_IMAGE_BYTES) {
+ reader.cancel().catch(() => {});
+ throw oversized(failure);
+ }
+ chunks.push(value);
+ }
+ return new Blob(chunks, {
+ type: response.headers?.get?.('content-type') || 'image/jpeg',
+ });
+ }
+
+ /** The panorama size a canvas this wide can show sharply at this field of view. */
+ export function panoSizeFor(canvasPixels, fovDeg) {
+ const needed = (Math.max(1, canvasPixels) * 360) / Math.max(1, fovDeg);
+ return needed > PANO_MID_SIZE[0] ? PANO_FULL_SIZE : PANO_MID_SIZE;
+ }
+
+ /**
+ * @typedef {object} PhotoSources Where a provider's photo comes from.
+ * @property {(photo: object) => boolean} hasPano A 360° photo with an equirectangular image.
+ * @property {(photo: object) => {url: string, width: number, resize?: [number, number]|null}|null} panoFirst
+ * The panorama shown first, its texture width (0 when it is only a preview), and a size to shrink it to.
+ * @property {(photo: object, size: [number, number], view: {expanded: boolean}) => {url: string, resize?: [number, number]|null, timeoutMs?: number}|null} panoSharp
+ * A sharper panorama for a canvas that needs `size`, or null; `expanded` while the viewer is.
+ * @property {(photo: object, view: {expanded: boolean}) => Array<string>} flatFirst Flat versions to try in turn (`expanded` while the viewer is).
+ * @property {(photo: object, pixels: number) => string|null} flatSharp
+ * A sharper flat version for a picture this many device pixels wide, or null.
+ * @property {(photo: object) => {title?: string|null, creator?: string|null, license?: string|null, externalUrl: string, capturedAtPrecision?: 'day'|'month'}} describe
+ * @property {(photo: object) => number|null} [bearingOf] Where the camera looked (default `photo.heading`).
+ */
+
+ /**
+ * Viewer adapter for providers whose photos are plain image files: a flat
+ * photo in an <img>, a 360° photo on a WebGL panorama (drag to look, wheel
+ * or pinch to zoom), and ‹ › to step along the sequence (also ← →). Poses
+ * follow the view direction.
+ *
+ * Photos are normalized by the provider: `{id, sequenceId, lon, lat,
+ * heading, isPano, capturedAt}` plus whatever its `sources` read.
+ *
+ * @param {object} options
+ * @param {string} options.providerId
+ * @param {string} options.name Provider name for labels and messages, e.g. 'KartaView'.
+ * @param {PhotoSources} options.sources
+ * @param {(photoId: string) => Promise<object>} options.getPhoto A normalized photo.
+ * @param {(photo: object, delta: -1|1) => Promise<string|null>} options.step The photo `delta` along the sequence, or null at its end.
+ * @param {(imageId: string) => void} options.onStep Open the photo ‹ › chose (through the core, so loading and errors show).
+ * @param {(photo: object) => void} [options.onShown] A photo is on screen.
+ * @param {(photo: object) => void} [options.onShowing] The photo this open shows, just before its pose.
+ * @param {(imageId: string) => void} [options.onReopen] Draw the same photo again after a GPU reset (default: `onStep`).
+ * @param {() => boolean} [options.onEscape] Esc in the docked viewer: true when it was used (e.g. a selection cleared).
+ * @param {object} [options.render] Render governor.
+ * @param {(url: string, options?: object) => Promise<HTMLImageElement|ImageBitmap>} [options.load]
+ * @param {(canvas: HTMLCanvasElement) => object} [options.createRenderer]
+ * @returns {import('./registry.js').ViewerAdapter}
+ */
+ export function createPhotoViewer({
+ providerId,
+ name,
+ sources,
+ getPhoto,
+ step,
+ onStep,
+ onShown = () => {},
+ onShowing = () => {},
+ onReopen = onStep,
+ onEscape = () => false,
+ render,
+ load = loadImage,
+ createRenderer = createPanoramaRenderer,
+ }) {
+ const LOAD_FAILED = `The ${name} photo could not be loaded`;
+ const listeners = new Set();
+ let root = null;
+ let picture = null;
+ let canvas = null;
+ let prevButton = null;
+ let nextButton = null;
+ let renderer = null;
+ /** WebGL failed once: 360° photos show their front view instead. */
+ let rendererFailed = false;
+ let photo = null;
+ /** What shows: 'flat', 'pano' or null. */
+ let showing = null;
+ let openSeq = 0;
+ let renderMode = 'letterbox';
+ let drag = null;
+ let poseFrame = 0;
+ let removeListeners = [];
+ /** The document the viewer was built in (new canvases come from it). */
+ let documentOf = null;
+ /** A context loss's look direction, for the reopen of that photo. */
+ let restoreView = null;
+ /** The panel's viewer box, where Esc is listened for (null: the root). */
+ let escapeTarget = null;
+ /** Width of the panorama texture on screen (0: the preview). */
+ let panoWidth = 0;
+ /** The sharper panorama on its way, for which open (resizes come in bursts). */
+ let panoComing = null;
+ /** A resize came while it loaded: look again once it lands. */
+ let lookAgain = false;
+ /** The sharper flat version on screen, and the one on its way. */
+ let flatSharp = { shown: null, loading: null };
+ /** The open in progress: another open, a close or an unmount stops its downloads. */
+ let openAbort = null;
+ /** The photo an open is fetching: ‹ › step on from it, not the old one. */
+ let openingId = null;
+ /** ‹ › chose this photo: keep the panorama's look direction for it. */
+ let keepViewFor = null;
+ /** ‹ › presses run one after another, each from where the last one went. */
+ let steps = Promise.resolve();
+
+ /** Files refused for their size: never loaded again, by any path. */
+ const refused = new Set();
+ async function loadAs(url, options) {
+ if (refused.has(url)) throw oversized(LOAD_FAILED);
+ try {
+ return await load(url, { failure: LOAD_FAILED, ...options });
+ } catch (error) {
+ if (error?.tooLarge) refused.add(url);
+ throw error;
+ }
+ }
+
+ function requestRender() {
+ render?.governorRequestRender?.(`${providerId}-viewer`);
+ }
+
+ function emit() {
+ if (!photo || !showing) return;
+ // A lost GPU context, still being recovered: the open that redraws the
+ // panorama poses once it is on screen.
+ if (showing === 'pano' && !renderer) return;
+ const view = showing === 'pano' ? renderer.getView() : null;
+ const heading = sources.bearingOf
+ ? sources.bearingOf(photo)
+ : photo.heading;
+ const described = sources.describe(photo);
+ const pose = {
+ providerId,
+ imageId: photo.id,
+ position: { lon: photo.lon, lat: photo.lat },
+ bearing:
+ heading === null || heading === undefined
+ ? null
+ : view
+ ? wrapDegrees(heading + view.yaw)
+ : heading,
+ tilt: view ? view.pitch : 0,
+ altitude: null,
+ isPano: showing === 'pano',
+ capturedAt: photo.capturedAt,
+ capturedAtPrecision: described.capturedAtPrecision || 'day',
+ title: described.title ?? null,
+ creator: described.creator ?? null,
+ license: described.license ?? null,
+ sequenceId: photo.sequenceId,
+ externalUrl: described.externalUrl,
+ };
+ for (const listener of [...listeners]) {
+ try {
+ listener(pose);
+ } catch {
+ /* listener errors are the core's to log */
+ }
+ }
+ requestRender();
+ }
+
+ /** Re-emit on the next frame: a drag moves the view many times a frame. */
+ function emitSoon() {
+ if (poseFrame) return;
+ poseFrame = requestAnimationFrame(() => {
+ poseFrame = 0;
+ emit();
+ });
+ }
+
+ function syncButtons() {
+ const enabled = Boolean(photo?.sequenceId) && showing !== null;
+ if (prevButton) prevButton.disabled = !enabled;
+ if (nextButton) nextButton.disabled = !enabled;
+ if (enabled) checkEnds(photo);
+ }
+
+ /** Disable ‹ or › at once where the sequence ends (it also warms the neighbours). */
+ function checkEnds(target) {
+ for (const [delta, button] of [
+ [-1, prevButton],
+ [1, nextButton],
+ ])
+ step(target, delta).then(
+ (id) => {
+ if (photo === target && button && !id) disable(button);
+ },
+ () => {},
+ );
+ }
+
+ /** Disable a step button, keeping keyboard focus in the viewer. */
+ function disable(button) {
+ if (button.ownerDocument?.activeElement === button) root?.focus?.();
+ button.disabled = true;
+ }
+
+ function show(kind) {
+ showing = kind;
+ if (picture) picture.hidden = kind !== 'flat';
+ if (canvas) canvas.hidden = kind !== 'pano';
+ if (root) root.dataset.kind = kind || '';
+ syncButtons();
+ }
+
+ function applyRenderMode() {
+ if (picture)
+ picture.style.objectFit = renderMode === 'fill' ? 'cover' : 'contain';
+ }
+
+ function ensureRenderer() {
+ if (renderer || rendererFailed || !canvas) return renderer;
+ try {
+ renderer = createRenderer(canvas);
+ } catch {
+ rendererFailed = true;
+ renderer = null;
+ }
+ return renderer;
+ }
+
+ /**
+ * A lost WebGL context (GPU reset, memory pressure) takes the panorama
+ * with it: drop the renderer, and show the photo again on a new one.
+ */
+ function onContextLost(event) {
+ event.preventDefault?.();
+ const lost = renderer;
+ renderer = null;
+ // The new renderer starts facing the photo's heading: keep the user's look.
+ if (showing === 'pano' && photo && lost)
+ restoreView = { id: photo.id, view: lost.getView() };
+ try {
+ lost?.destroy();
+ } catch {
+ /* already gone */
+ }
+ // A lost canvas hands back its lost context: draw on a new element.
+ const fresh = makeCanvas(documentOf);
+ fresh.hidden = canvas.hidden;
+ canvas.replaceWith?.(fresh);
+ canvas = fresh;
+ // Show the photo again through the core, unless a newer one is opening.
+ if (showing === 'pano' && photo && openingId === null) {
+ const again = photo.id;
+ show(null);
+ openingId = again;
+ onReopen(again);
+ }
+ }
+
+ /** The panorama canvas, wired for drag, pinch, wheel and context loss. */
+ function makeCanvas(doc) {
+ const element = doc.createElement('canvas');
+ element.className = 'sl-photo-pano';
+ element.hidden = true;
+ listen(element, 'pointerdown', onPointerDown);
+ listen(element, 'pointermove', onPointerMove);
+ listen(element, 'pointerup', onPointerUp);
+ listen(element, 'pointercancel', onPointerUp);
+ listen(element, 'wheel', onWheel, { passive: false });
+ listen(element, 'webglcontextlost', onContextLost);
+ return element;
+ }
+
+ /**
+ * Step along the sequence from the photo showing, or from the one on its
+ * way after an earlier press, and open it through the core.
+ */
+ function stepBy(delta) {
+ steps = steps.then(async () => {
+ const fromId = openingId ?? photo?.id;
+ if (!fromId || !root) return;
+ let from;
+ let nextId = null;
+ try {
+ from = await getPhoto(fromId);
+ if (from.sequenceId) nextId = await step(from, delta);
+ } catch {
+ // Not the end of the sequence, just no answer: the press is lost.
+ return;
+ }
+ // Closed, or another photo was opened meanwhile.
+ if ((openingId ?? photo?.id) !== fromId) return;
+ if (!nextId) {
+ const button = delta < 0 ? prevButton : nextButton;
+ if (button && photo?.id === fromId) disable(button);
+ return;
+ }
+ openingId = nextId;
+ keepViewFor = nextId;
+ onStep(nextId);
+ });
+ }
+
+ /** Pointers on the panorama: one drags the view, two pinch the zoom. */
+ const pointers = new Map();
+ let pinch = null;
+
+ function pinchSpan() {
+ const [a, b] = [...pointers.values()];
+ return Math.max(1, Math.hypot(a.x - b.x, a.y - b.y));
+ }
+
+ function onPointerDown(event) {
+ if (showing !== 'pano' || !renderer) return;
+ if (event.pointerType === 'mouse' && event.button !== 0) return;
+ pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
+ canvas.setPointerCapture?.(event.pointerId);
+ if (pointers.size === 2) {
+ drag = null;
+ pinch = { span: pinchSpan(), fov: renderer.getView().fov };
+ return;
+ }
+ drag = {
+ id: event.pointerId,
+ x: event.clientX,
+ y: event.clientY,
+ view: renderer.getView(),
+ };
+ canvas.classList.add('sl-photo-dragging');
+ }
+
+ function onPointerMove(event) {
+ if (pointers.has(event.pointerId))
+ pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
+ if (pinch && pointers.size === 2 && renderer) {
+ renderer.setView({ fov: pinch.fov * (pinch.span / pinchSpan()) });
+ return;
+ }
+ if (!drag || event.pointerId !== drag.id || !renderer) return;
+ const { fov } = drag.view;
+ const width = Math.max(1, canvas.clientWidth);
+ const height = Math.max(1, canvas.clientHeight);
+ const vertical = fov;
+ const horizontal = fov * (width / height);
+ renderer.setView({
+ yaw: drag.view.yaw - ((event.clientX - drag.x) / width) * horizontal,
+ pitch: drag.view.pitch + ((event.clientY - drag.y) / height) * vertical,
+ });
+ emitSoon();
+ }
+
+ function onPointerUp(event) {
+ pointers.delete(event.pointerId);
+ if (pointers.size < 2) pinch = null;
+ if (!drag || event.pointerId !== drag.id) return;
+ drag = null;
+ canvas.classList.remove('sl-photo-dragging');
+ }
+
+ function onWheel(event) {
+ if (showing !== 'pano' || !renderer) return;
+ event.preventDefault();
+ const { fov } = renderer.getView();
+ renderer.setView({ fov: fov * Math.exp(event.deltaY * 0.001) });
+ }
+
+ /**
+ * Docked, Esc anywhere in the viewer's box (the photo, its toolbar, its
+ * caption) is the provider's before the panel's, which would collapse;
- * expanded, the dialog's own Esc shrinks it.
++ * expanded, the panel's own Esc shrinks it.
+ */
+ function onEscapeKey(event) {
+ if (
+ event.key !== 'Escape' ||
+ event.shiftKey ||
+ event.defaultPrevented ||
- root?.closest?.('.sl-viewer-wrap-expanded') ||
++ isExpanded() ||
+ !onEscape()
+ )
+ return;
+ event.preventDefault();
+ event.stopPropagation();
+ }
+
+ function onKeyDown(event) {
+ if (!escapeTarget) onEscapeKey(event);
+ if (
+ event.defaultPrevented ||
+ event.altKey ||
+ event.ctrlKey ||
+ event.metaKey
+ )
+ return;
+ const pano = showing === 'pano' && renderer;
+ const turn = { ArrowLeft: -1, ArrowRight: 1 }[event.key];
+ // Shift+← → look around a panorama; ← → step along the sequence.
+ if (turn && event.shiftKey && pano) {
+ event.preventDefault();
+ const { yaw, fov } = renderer.getView();
+ renderer.setView({ yaw: yaw + (turn * fov) / 4 });
+ emitSoon();
+ } else if (turn) {
+ event.preventDefault();
+ stepBy(turn);
+ } else if ((event.key === 'ArrowUp' || event.key === 'ArrowDown') && pano) {
+ event.preventDefault();
+ const { pitch, fov } = renderer.getView();
+ renderer.setView({
+ pitch: pitch + ((event.key === 'ArrowUp' ? 1 : -1) * fov) / 6,
+ });
+ emitSoon();
+ } else if (['+', '=', '-', '_'].includes(event.key) && pano) {
+ event.preventDefault();
+ const { fov } = renderer.getView();
+ renderer.setView({
+ fov: fov * (event.key === '+' || event.key === '=' ? 0.85 : 1 / 0.85),
+ });
+ }
+ }
+
+ function listen(target, type, handler, options) {
+ target.addEventListener(type, handler, options);
+ removeListeners.push(() =>
+ target.removeEventListener(type, handler, options),
+ );
+ }
+
+ function build(host) {
+ const doc = host.ownerDocument;
+ documentOf = doc;
+ root = doc.createElement('div');
+ root.className = 'sl-photo-viewer';
+ root.dataset.provider = providerId;
+ root.tabIndex = 0;
+ root.setAttribute('role', 'group');
+ root.setAttribute(
+ 'aria-label',
+ t(
+ '{name} photo. ← and → step along the sequence. On a 360° photo, drag or use Shift+← →, ↑ ↓ to look around, and + − to zoom',
+ { name },
+ ),
+ );
+ picture = doc.createElement('img');
+ picture.className = 'sl-photo-flat';
+ picture.alt = t('{name} street-level photo', { name });
+ picture.draggable = false;
+ picture.hidden = true;
+ canvas = makeCanvas(doc);
+ const nav = (label, glyph, delta) => {
+ const button = doc.createElement('button');
+ button.type = 'button';
+ button.className = `sl-photo-step sl-photo-step-${delta < 0 ? 'prev' : 'next'}`;
+ button.textContent = glyph;
+ button.title = label;
+ button.setAttribute('aria-label', label);
+ button.disabled = true;
+ listen(button, 'click', (event) => {
+ event.stopPropagation();
+ stepBy(delta);
+ });
+ return button;
+ };
+ prevButton = nav(t('Previous photo in this sequence (←)'), '‹', -1);
+ nextButton = nav(t('Next photo in this sequence (→)'), '›', 1);
+ root.append(picture, canvas, prevButton, nextButton);
+ host.append(root);
+ listen(root, 'keydown', onKeyDown);
+ // The viewer's box in the panel; without one, the root's own handler
+ // takes Esc (one listener per element and type).
+ escapeTarget = host.closest?.('.sl-viewer-wrap') ?? null;
+ if (escapeTarget) listen(escapeTarget, 'keydown', onEscapeKey);
+ applyRenderMode();
+ }
+
+ function teardown() {
+ pointers.clear();
+ pinch = null;
+ for (const remove of removeListeners) remove();
+ removeListeners = [];
+ if (poseFrame) cancelAnimationFrame(poseFrame);
+ poseFrame = 0;
+ drag = null;
+ renderer?.destroy();
+ renderer = null;
+ root?.remove();
+ root = picture = canvas = prevButton = nextButton = null;
+ showing = null;
+ photo = null;
+ }
+
+ /** Device pixels across the flat photo's frame (its longer side). */
+ function viewerPixels() {
+ const ratio = globalThis.devicePixelRatio || 1;
+ const element = showing === 'pano' ? canvas : picture;
+ const side = Math.max(
+ element?.clientWidth || 0,
+ element?.clientHeight || 0,
+ );
+ return (side || root?.clientWidth || 0) * ratio;
+ }
+
+ /** A sharper version once the first is on screen, if nothing replaced it. */
+ async function upgrade(target, seq, kind) {
+ // A 360° photo shown flat (no WebGL) keeps its front view.
+ if (kind === 'flat' && target.isPano) return;
+ // Another photo is opening: the one still shown is not worth more bytes.
+ if (openingId !== null && openingId !== target.id) return;
+ const signal = openAbort?.signal;
+ if (kind === 'pano') {
+ const size = panoSizeNow();
+ if (size[0] <= panoWidth) return;
+ // Resizes come in bursts while the panel animates: one load at a time
+ // for this photo, and one more look once it lands.
+ if (panoComing?.seq === seq) {
+ lookAgain = true;
+ return;
+ }
+ const sharp = sources.panoSharp(target, size, {
+ expanded: isExpanded(),
+ });
+ if (!sharp?.url) return;
+ const coming = { seq, width: size[0], controller: new AbortController() };
+ panoComing = coming;
+ lookAgain = false;
+ try {
+ const image = await loadAs(sharp.url, {
+ crossOrigin: true,
+ signal: coming.controller.signal,
+ resize: sharp.resize ?? null,
+ ...(sharp.timeoutMs ? { timeoutMs: sharp.timeoutMs } : {}),
+ });
+ if (seq !== openSeq || photo !== target || showing !== 'pano') {
+ image.close?.();
+ return;
+ }
+ if (!renderer || size[0] <= panoWidth) {
+ image.close?.();
+ return;
+ }
+ renderer.setImage(image);
+ panoWidth = size[0];
+ requestRender();
+ } catch {
+ /* the first version stays */
+ } finally {
+ if (panoComing === coming) {
+ panoComing = null;
+ if (lookAgain && seq === openSeq && photo === target) {
+ lookAgain = false;
+ upgrade(target, seq, 'pano');
+ }
+ }
+ }
+ return;
+ }
+ const url = sources.flatSharp(target, viewerPixels());
+ if (!url || url === flatSharp.shown || url === flatSharp.loading) return;
+ const sharp = flatSharp;
+ sharp.loading = url;
+ try {
+ const image = await loadAs(url, { crossOrigin: false, signal });
+ if (seq !== openSeq || photo !== target || showing !== 'flat') return;
+ picture.src = image.src;
+ sharp.shown = url;
+ requestRender();
+ } catch {
+ /* the first version stays; a later resize may try again */
+ } finally {
+ // Discarded or failed: nothing is on its way, so it may be asked again.
+ if (sharp.loading === url) sharp.loading = null;
+ }
+ }
+
- /** The viewer is the expanded dialog, not docked in the panel. */
++ /** The viewer is expanded (full screen, or the iPhone popover), not docked in the panel. */
+ function isExpanded() {
- return Boolean(root?.closest?.('.sl-viewer-wrap-expanded'));
++ try {
++ return Boolean(root?.closest?.(EXPANDED_SELECTOR));
++ } catch {
++ // A browser without :popover-open has no popover EXPAND either.
++ return Boolean(root?.closest?.('.sl-viewer-wrap:fullscreen'));
++ }
+ }
+
+ /** Another photo, or none: a sharper panorama still on its way is not needed. */
+ function dropSharpPanorama() {
+ panoComing?.controller?.abort();
+ panoComing = null;
+ lookAgain = false;
+ }
+
+ /** The sharp panorama this viewer needs now: 2,048 docked, 4,096 expanded. */
+ function panoSizeNow() {
+ const ratio = Math.min(globalThis.devicePixelRatio || 1, 2);
+ const width = (canvas?.clientWidth || 0) * ratio;
+ return panoSizeFor(width, renderer?.getView().fov ?? PANO_FOV_DEFAULT_DEG);
+ }
+
+ async function showPano(target, seq, keepView, signal) {
+ // If the panorama fails, the caller shows the front view rather than
+ // waiting on it twice.
+ const first = sources.panoFirst(target);
+ if (!first?.url) throw new Error(LOAD_FAILED);
+ const image = await loadAs(first.url, {
+ crossOrigin: true,
+ signal,
+ // Never decoded at more than the texture it becomes.
+ resize: first.resize ?? PANO_MID_SIZE,
+ });
+ if (seq !== openSeq) {
+ image.close?.();
+ return false;
+ }
+ // The context may have been lost while this loaded: build on the new
+ // canvas, or let the caller show the front view.
+ if (!ensureRenderer()) {
+ image.close?.();
+ throw new Error(LOAD_FAILED);
+ }
+ const restore = restoreView?.id === target.id ? restoreView.view : null;
+ restoreView = null;
+ if (restore) renderer.setView(restore);
+ else if (!keepView || showing !== 'pano')
+ renderer.setView({ yaw: 0, pitch: 0, fov: PANO_FOV_DEFAULT_DEG });
+ photo = target;
+ // Shown first: a hidden canvas measures 0 and would be sized 1×1.
+ show('pano');
+ renderer.setImage(image);
+ panoWidth = first.width || 0;
+ // A sharper version of the photo before was dropped by `open`; one of
+ // this photo, asked by a resize meanwhile, is still worth having.
+ return true;
+ }
+
+ async function showFlat(target, seq, signal) {
+ const urls = sources
+ .flatFirst(target, { expanded: isExpanded() })
+ .filter(Boolean);
+ let image;
+ let failure = null;
+ for (const url of urls) {
+ try {
+ image = await loadAs(url, { crossOrigin: false, signal });
+ break;
+ } catch (error) {
+ failure = error;
+ if (seq !== openSeq) return false;
+ }
+ }
+ if (!image) throw failure || new Error(LOAD_FAILED);
+ if (seq !== openSeq) return false;
+ picture.src = image.src;
+ flatSharp = { shown: null, loading: null };
+ photo = target;
+ show('flat');
+ return true;
+ }
+
+ async function openPhoto(id, seq, keepView, signal) {
+ const target = await getPhoto(id, { signal });
+ if (seq !== openSeq) return;
+ let shown = false;
+ if (sources.hasPano(target) && ensureRenderer()) {
+ try {
+ shown = await showPano(target, seq, keepView, signal);
+ } catch {
+ // The panorama failed: its front view is better than nothing.
+ if (seq !== openSeq) return;
+ shown = await showFlat(target, seq, signal);
+ }
+ } else shown = await showFlat(target, seq, signal);
+ if (!shown) return;
+ onShowing(target);
+ emit();
+ onShown(target);
+ upgrade(target, seq, showing);
+ }
+
+ const adapter = {
+ async mount(host) {
+ if (!host) throw new Error('Street Level viewer has no host element');
+ if (root && root.parentNode === host) return;
+ teardown();
+ rendererFailed = false;
+ build(host);
+ },
+
+ /** Resolves once the photo is on screen and its pose was emitted. */
+ async open(imageId) {
+ if (!root) throw new Error(`${name} viewer is not mounted`);
+ const id = String(imageId);
+ const seq = ++openSeq;
+ dropSharpPanorama();
+ // The previous open's downloads stop: only this photo is wanted now.
+ openAbort?.abort();
+ const opening = (openAbort = new AbortController());
+ const keepView = keepViewFor === id;
+ keepViewFor = null;
+ openingId = id;
+ try {
+ await openPhoto(id, seq, keepView, opening.signal);
+ } catch (error) {
+ // A later open, or a close, stopped this one: that is not a failure.
+ if (seq !== openSeq) return;
+ throw error;
+ } finally {
+ if (openingId === id && seq === openSeq) openingId = null;
+ }
+ },
+
+ close() {
+ openSeq++;
+ dropSharpPanorama();
+ openAbort?.abort();
+ openAbort = null;
+ openingId = null;
+ keepViewFor = null;
+ photo = null;
+ flatSharp = { shown: null, loading: null };
+ show(null);
+ if (picture) picture.removeAttribute('src');
+ renderer?.clear?.();
+ },
+
+ unmount() {
+ openSeq++;
+ dropSharpPanorama();
+ openAbort?.abort();
+ openAbort = null;
+ refused.clear();
+ openingId = null;
+ keepViewFor = null;
+ flatSharp = { shown: null, loading: null };
+ teardown();
+ },
+
+ resize() {
+ renderer?.resize();
+ // Expanded: a docked viewer's panorama or flat version is now too soft.
+ if (showing === 'pano' && photo && panoSizeNow()[0] > panoWidth)
+ upgrade(photo, openSeq, 'pano');
+ else if (showing === 'flat' && photo) upgrade(photo, openSeq, 'flat');
+ },
+
+ /** FIT / FILL frame a flat photo; a panorama has no frame to fit. */
+ supportsRenderModes: () => showing !== 'pano',
+
+ setRenderMode(mode) {
+ renderMode = mode === 'fill' ? 'fill' : 'letterbox';
+ applyRenderMode();
+ },
+
+ /** The photo's direction became known (its drive loaded): pose again. */
+ refreshPose() {
+ emit();
+ },
+
+ onPose(listener) {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ };
+ return adapter;
+ }
diff --cc src/layers/streetLevel/photoViewer.test.mjs
index 000000000,09df91c2e..47df455b7
mode 000000,100644..100644
--- a/src/layers/streetLevel/photoViewer.test.mjs
+++ b/src/layers/streetLevel/photoViewer.test.mjs
@@@ -1,0 -1,538 +1,538 @@@
+ import assert from 'node:assert/strict';
+ import test from 'node:test';
+ import { createPhotoViewer } from './photoViewer.js';
+ import { fakeHost, until } from '../../testSupport/kartaViewFakes.mjs';
+
+ const PHOTOS = {
+ a: { id: 'a', sequenceId: 's', lon: 1, lat: 2, heading: 0, isPano: true },
+ b: { id: 'b', sequenceId: 's', lon: 1, lat: 2, heading: 0, isPano: true },
+ f: { id: 'f', sequenceId: 's', lon: 1, lat: 2, heading: 0, isPano: false },
+ g: { id: 'g', sequenceId: 's', lon: 1, lat: 2, heading: 0, isPano: false },
+ };
+
+ /** Sources whose panoramas and sharper flat versions are named after the photo. */
+ const SOURCES = {
+ hasPano: (photo) => photo.isPano,
+ panoFirst: (photo) => ({ url: `${photo.id}-first`, width: 2048 }),
+ panoSharp: (photo) => ({ url: `${photo.id}-sharp` }),
+ flatFirst: (photo) => [`${photo.id}-first`],
+ flatSharp: (photo, pixels) => (pixels > 1000 ? `${photo.id}-sharp` : null),
+ describe: () => ({ externalUrl: 'https://example.org' }),
+ };
+
+ /** A viewer whose loads wait until `release(url)` (or fail with `fail(url)`). */
+ function setup() {
+ const pending = new Map();
+ const loads = [];
+ const images = [];
+ const viewer = createPhotoViewer({
+ providerId: 'test',
+ name: 'Test',
+ sources: SOURCES,
+ getPhoto: async (id) => PHOTOS[id],
+ step: async () => null,
+ onStep() {},
+ load: (url) =>
+ new Promise((resolve, reject) => {
+ loads.push(url);
+ pending.set(url, { resolve, reject });
+ }),
+ createRenderer: () => ({
+ setImage: (image) => images.push(image.src),
+ setView() {},
+ getView: () => ({ yaw: 0, pitch: 0, fov: 80 }),
+ resize() {},
+ clear() {},
+ destroy() {},
+ }),
+ });
+ const release = (url) => {
+ const closed = { value: false };
+ pending.get(url).resolve({ src: url, close: () => (closed.value = true) });
+ pending.delete(url);
+ return closed;
+ };
+ const fail = (url) => {
+ pending.get(url).reject(new Error('gone'));
+ pending.delete(url);
+ };
+ return { viewer, loads, images, release, fail, host: fakeHost() };
+ }
+
+ const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
+ const parts = (host) => {
+ const [picture, canvas] = host.children[0].children;
+ return { picture, canvas };
+ };
+
+ test('a panorama that arrives after another photo opened is released, not shown', async () => {
+ const env = setup();
+ await env.viewer.mount(env.host);
+ const first = env.viewer.open('a');
+ await tick();
+ const second = env.viewer.open('b');
+ await tick();
+ const stale = env.release('a-first');
+ await first;
+ assert.equal(stale.value, true, 'its bitmap is closed');
+ env.release('b-first');
+ await second;
+ assert.deepEqual(env.images, ['b-first']);
+ });
+
+ test('one sharp panorama download per open, even across a quick switch and a burst of resizes', async (t) => {
+ const env = setup();
+ t.after(() => delete globalThis.devicePixelRatio);
+ globalThis.devicePixelRatio = 1;
+ await env.viewer.mount(env.host);
+ const { canvas } = parts(env.host);
+ canvas.clientWidth = 1800;
+ const opening = env.viewer.open('a');
+ await tick();
+ env.release('a-first');
+ await opening;
+ await tick();
+ assert.ok(env.loads.includes('a-sharp'), 'expanded: the sharp one is asked');
+ // Photo b opens while a's sharp version is still on its way.
+ const next = env.viewer.open('b');
+ await tick();
+ env.release('b-first');
+ await next;
+ await tick();
+ assert.ok(env.loads.includes('b-sharp'));
+ // a's download finishes late; resizes must not ask for b's again.
+ env.release('a-sharp');
+ await tick();
+ env.viewer.resize();
+ env.viewer.resize();
+ await tick();
+ assert.equal(env.loads.filter((url) => url === 'b-sharp').length, 1);
+ env.release('b-sharp');
+ await tick();
+ assert.deepEqual(env.images, ['a-first', 'b-first', 'b-sharp']);
+ });
+
+ test('a sharper flat version that failed is tried again on the next resize', async (t) => {
+ const env = setup();
+ t.after(() => delete globalThis.devicePixelRatio);
+ globalThis.devicePixelRatio = 1;
+ await env.viewer.mount(env.host);
+ const { picture } = parts(env.host);
+ picture.clientWidth = 1200;
+ const opening = env.viewer.open('f');
+ await tick();
+ env.release('f-first');
+ await opening;
+ await tick();
+ env.fail('f-sharp');
+ await tick();
+ assert.equal(picture.src, 'f-first');
+ env.viewer.resize();
+ await tick();
+ assert.equal(env.loads.filter((url) => url === 'f-sharp').length, 2);
+ env.release('f-sharp');
+ assert.ok(await until(() => picture.src === 'f-sharp'));
+ });
+
+ test('Esc: the docked viewer offers it to the provider first; expanded, it is the dialog’s', async () => {
+ let asked = 0;
+ const viewer = createPhotoViewer({
+ providerId: 'test',
+ name: 'Test',
+ sources: SOURCES,
+ getPhoto: async (id) => PHOTOS[id],
+ step: async () => null,
+ onStep() {},
+ onEscape: () => ++asked > 0,
+ load: async (url) => ({ src: url }),
+ });
+ const host = fakeHost();
+ await viewer.mount(host);
+ const root = host.children[0];
+ const press = () => {
+ const event = { key: 'Escape', prevented: false, stopped: false };
+ event.preventDefault = () => (event.prevented = true);
+ event.stopPropagation = () => (event.stopped = true);
+ root.fire('keydown', event);
+ return event;
+ };
+ const docked = press();
+ assert.equal(asked, 1);
+ assert.equal(docked.prevented && docked.stopped, true);
+ root.closest = (selector) =>
- selector.includes('sl-viewer-wrap-expanded') ? {} : null;
++ selector.includes('sl-viewer-wrap:fullscreen') ? {} : null;
+ const expanded = press();
+ assert.equal(asked, 1, 'not asked while expanded');
+ assert.equal(expanded.prevented, false);
+ });
+
+ test('a sharp panorama still downloading when another photo opens is aborted', async (t) => {
+ const signals = [];
+ const viewer = createPhotoViewer({
+ providerId: 'test',
+ name: 'Test',
+ sources: SOURCES,
+ getPhoto: async (id) => PHOTOS[id],
+ step: async () => null,
+ onStep() {},
+ load: (url, options) =>
+ url.endsWith('-sharp')
+ ? new Promise((_, reject) => {
+ signals.push(options.signal);
+ options.signal?.addEventListener('abort', () =>
+ reject(new Error('aborted')),
+ );
+ })
+ : Promise.resolve({ src: url }),
+ createRenderer: () => ({
+ setImage() {},
+ setView() {},
+ getView: () => ({ yaw: 0, pitch: 0, fov: 80 }),
+ resize() {},
+ clear() {},
+ destroy() {},
+ }),
+ });
+ t.after(() => delete globalThis.devicePixelRatio);
+ globalThis.devicePixelRatio = 1;
+ const host = fakeHost();
+ await viewer.mount(host);
+ parts(host).canvas.clientWidth = 1800;
+ await viewer.open('a');
+ await tick();
+ assert.equal(signals.length, 1);
+ assert.equal(signals[0].aborted, false);
+ await viewer.open('f');
+ assert.equal(signals[0].aborted, true, 'not needed any more');
+ });
+
+ test('a lost WebGL context while the first panorama loads releases its bitmap', async () => {
+ let closed = false;
+ let built = 0;
+ let land = null;
+ const viewer = createPhotoViewer({
+ providerId: 'test',
+ name: 'Test',
+ sources: SOURCES,
+ getPhoto: async (id) => PHOTOS[id],
+ step: async () => null,
+ onStep() {},
+ load: (url) =>
+ new Promise((resolve) => {
+ land = () => resolve({ src: url, close: () => (closed = true) });
+ }),
+ // The first renderer is lost mid-load; a new one cannot be built.
+ createRenderer: () => {
+ built++;
+ if (built > 1) throw new Error('context lost');
+ return {
+ setImage() {},
+ setView() {},
+ getView: () => ({ yaw: 0, pitch: 0, fov: 80 }),
+ resize() {},
+ clear() {},
+ destroy() {},
+ };
+ },
+ });
+ const host = fakeHost();
+ await viewer.mount(host);
+ const opening = viewer.open('a');
+ assert.ok(await until(() => land !== null), 'the panorama is loading');
+ parts(host).canvas.fire('webglcontextlost', {});
+ const first = land;
+ first();
+ // The panorama failed: the front view is loaded flat instead.
+ assert.ok(await until(() => land !== first), 'the flat fallback loads');
+ land();
+ await opening;
+ assert.equal(built, 2, 'a new renderer was tried');
+ assert.equal(closed, true, 'the bitmap no renderer took is closed');
+ });
+
+ test('docked, Esc anywhere in the viewer’s box (toolbar, caption) is offered to the provider', async () => {
+ let asked = 0;
+ const viewer = createPhotoViewer({
+ providerId: 'test',
+ name: 'Test',
+ sources: SOURCES,
+ getPhoto: async (id) => PHOTOS[id],
+ step: async () => null,
+ onStep() {},
+ onEscape: () => ++asked > 0,
+ load: async (url) => ({ src: url }),
+ });
+ const host = fakeHost();
+ const wrap = fakeHost();
+ host.closest = (selector) => (selector === '.sl-viewer-wrap' ? wrap : null);
+ await viewer.mount(host);
+ const flags = { stopped: false, prevented: false };
+ // Focus back on EXPAND after a shrink: the key reaches the wrap, not the photo.
+ wrap.fire('keydown', {
+ key: 'Escape',
+ stopPropagation: () => (flags.stopped = true),
+ preventDefault: () => (flags.prevented = true),
+ });
+ assert.equal(asked, 1);
+ assert.deepEqual(flags, { stopped: true, prevented: true });
+ viewer.unmount();
+ wrap.fire('keydown', { key: 'Escape' });
+ assert.equal(asked, 1, 'unmounted: the listener is gone');
+ });
+
+ test('a picture file or bitmap past any real photo’s size is refused', async (t) => {
+ const { loadImage, MAX_IMAGE_BYTES, MAX_IMAGE_SIDE } =
+ await import('./photoViewer.js');
+ const saved = {
+ fetch: globalThis.fetch,
+ createImageBitmap: globalThis.createImageBitmap,
+ };
+ t.after(() => Object.assign(globalThis, saved));
+ let closed = 0;
+ const bitmap = (width, height) => ({ width, height, close: () => closed++ });
+ globalThis.createImageBitmap = async (blob) => blob.bitmap;
+ const respond = ({ length, size, width = 100, height = 50 }) =>
+ (globalThis.fetch = async () => ({
+ ok: true,
+ headers: new Map([['content-length', String(length ?? '')]]),
+ blob: async () => ({
+ size: size ?? 10,
+ bitmap: bitmap(width, height),
+ slice: () => ({ arrayBuffer: async () => new ArrayBuffer(0) }),
+ }),
+ }));
+ const refusedForSize = (error) => {
+ assert.match(error.message, /could not be loaded/);
+ assert.equal(error.tooLarge, true, 'marked as a size refusal');
+ return true;
+ };
+ respond({ length: MAX_IMAGE_BYTES + 1 });
+ await assert.rejects(loadImage('https://x/a.jpg'), refusedForSize);
+ respond({ size: MAX_IMAGE_BYTES + 1 });
+ await assert.rejects(loadImage('https://x/a.jpg'), refusedForSize);
+ respond({ width: MAX_IMAGE_SIDE + 1 });
+ await assert.rejects(loadImage('https://x/a.jpg'), refusedForSize);
+ assert.equal(closed, 1, 'the oversize bitmap is released');
+ // No length given, a body that keeps coming: cut off while it streams.
+ let pulled = 0;
+ globalThis.fetch = async () => ({
+ ok: true,
+ headers: new Map(),
+ body: new ReadableStream({
+ pull(controller) {
+ pulled++;
+ controller.enqueue(new Uint8Array(8 * 1024 * 1024));
+ },
+ }),
+ });
+ await assert.rejects(loadImage('https://x/a.jpg'), refusedForSize);
+ assert.ok(pulled * 8 * 1024 * 1024 <= MAX_IMAGE_BYTES + 16 * 1024 * 1024);
+ // Other failures are not size refusals.
+ globalThis.fetch = async () => ({ ok: false, headers: new Map() });
+ await assert.rejects(
+ loadImage('https://x/a.jpg'),
+ (error) => !error.tooLarge,
+ );
+ respond({});
+ assert.equal((await loadImage('https://x/a.jpg')).width, 100);
+ });
+
+ /** A viewer whose loads are held, recording each load's signal by url. */
+ function heldViewer() {
+ const pending = new Map();
+ const signals = new Map();
+ const loads = [];
+ const viewer = createPhotoViewer({
+ providerId: 'test',
+ name: 'Test',
+ sources: SOURCES,
+ getPhoto: async (id) => PHOTOS[id],
+ step: async () => null,
+ onStep() {},
+ load: (url, options = {}) =>
+ new Promise((resolve, reject) => {
+ loads.push(url);
+ signals.set(url, options.signal);
+ options.signal?.addEventListener('abort', () =>
+ reject(new Error('aborted')),
+ );
+ pending.set(url, { resolve, reject });
+ }),
+ });
+ const release = (url) => {
+ pending.get(url).resolve({ src: url });
+ pending.delete(url);
+ };
+ return { viewer, pending, signals, loads, release, host: fakeHost() };
+ }
+
+ test('a new open, a close or an unmount stops the downloads of the open before it', async () => {
+ const env = heldViewer();
+ await env.viewer.mount(env.host);
+ const first = env.viewer.open('f');
+ assert.ok(await until(() => env.signals.has('f-first')));
+ const second = env.viewer.open('g');
+ assert.equal(env.signals.get('f-first').aborted, true, 'f is not wanted now');
+ await first.catch(() => {});
+ assert.ok(await until(() => env.signals.has('g-first')));
+ env.viewer.close();
+ assert.equal(env.signals.get('g-first').aborted, true, 'closed');
+ await second.catch(() => {});
+ const third = env.viewer.open('f');
+ assert.ok(await until(() => env.pending.has('f-first')));
+ env.viewer.unmount();
+ assert.equal(env.signals.get('f-first').aborted, true, 'unmounted');
+ await third.catch(() => {});
+ });
+
+ test('a sharper flat version on its way stops when another photo opens, and is asked again later', async (t) => {
+ t.after(() => delete globalThis.devicePixelRatio);
+ globalThis.devicePixelRatio = 1;
+ const env = heldViewer();
+ await env.viewer.mount(env.host);
+ parts(env.host).picture.clientWidth = 1200;
+ const opening = env.viewer.open('f');
+ assert.ok(await until(() => env.pending.has('f-first')));
+ env.release('f-first');
+ await opening;
+ assert.ok(
+ await until(() => env.pending.has('f-sharp')),
+ 'the 1,200 px viewer asks for more',
+ );
+ // Resizes while it loads (the panel animating) do not ask again.
+ env.viewer.resize();
+ env.viewer.resize();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ assert.equal(env.loads.filter((url) => url === 'f-sharp').length, 1);
+ // g opens (and fails): f's sharp download stops, f stays on screen.
+ const failing = env.viewer.open('g');
+ assert.equal(env.signals.get('f-sharp').aborted, true);
+ assert.ok(await until(() => env.pending.has('g-first')));
+ env.pending.get('g-first').reject(new Error('gone'));
+ env.pending.delete('g-first');
+ await failing.catch(() => {});
+ // The discarded response does not block f's sharp version for good.
+ env.signals.delete('f-sharp');
+ env.viewer.resize();
+ assert.ok(await until(() => env.signals.has('f-sharp')), 'asked again');
+ });
+
+ test('a resize while another photo opens does not upgrade the photo still shown', async (t) => {
+ t.after(() => delete globalThis.devicePixelRatio);
+ globalThis.devicePixelRatio = 1;
+ const env = heldViewer();
+ await env.viewer.mount(env.host);
+ const opening = env.viewer.open('f');
+ assert.ok(await until(() => env.pending.has('f-first')));
+ env.release('f-first');
+ await opening;
+ // g is opening; EXPAND resizes the viewer meanwhile.
+ const next = env.viewer.open('g');
+ assert.ok(await until(() => env.pending.has('g-first')));
+ parts(env.host).picture.clientWidth = 1200;
+ env.viewer.resize();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ assert.equal(env.pending.has('f-sharp'), false, 'f is on its way out');
+ env.release('g-first');
+ await next;
+ assert.ok(await until(() => env.pending.has('g-sharp')), 'g gets it');
+ });
+
+ test('a panorama is always decoded at a bounded size', async () => {
+ const env = heldViewer();
+ const options = [];
+ const viewer = createPhotoViewer({
+ providerId: 'test',
+ name: 'Test',
+ sources: SOURCES,
+ getPhoto: async (id) => PHOTOS[id],
+ step: async () => null,
+ onStep() {},
+ load: async (url, opts) => {
+ options.push(opts);
+ return { src: url };
+ },
+ createRenderer: () => ({
+ setImage() {},
+ setView() {},
+ getView: () => ({ yaw: 0, pitch: 0, fov: 80 }),
+ resize() {},
+ clear() {},
+ destroy() {},
+ }),
+ });
+ await viewer.mount(env.host);
+ await viewer.open('a');
+ // SOURCES' panoFirst names no size: the viewer still bounds it.
+ assert.deepEqual(options[0].resize, [2048, 1024]);
+ });
+
+ test('a header that declares a huge image is refused before anything decodes it', async (t) => {
+ const { loadImage } = await import('./photoViewer.js');
+ const saved = {
+ fetch: globalThis.fetch,
+ createImageBitmap: globalThis.createImageBitmap,
+ };
+ t.after(() => Object.assign(globalThis, saved));
+ let decoded = 0;
+ globalThis.createImageBitmap = async () => {
+ decoded++;
+ return { width: 10, height: 10 };
+ };
+ // A 1 kB PNG that says it is 16,384 × 16,384.
+ const png = new Uint8Array(1024);
+ png.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13]);
+ png.set(
+ [...'IHDR'].map((c) => c.charCodeAt(0)),
+ 12,
+ );
+ png.set([0, 0, 0x40, 0, 0, 0, 0x40, 0], 16);
+ globalThis.fetch = async () => new Response(png);
+ await assert.rejects(
+ loadImage('https://x/bomb.png'),
+ (error) => error.tooLarge === true,
+ );
+ assert.equal(decoded, 0, 'never decoded');
+ });
+
+ test('an <img> that turns out too large is refused and let go', async (t) => {
+ const { loadImage, MAX_IMAGE_SIDE } = await import('./photoViewer.js');
+ const saved = globalThis.Image;
+ t.after(() => (globalThis.Image = saved));
+ let size = [MAX_IMAGE_SIDE + 1, 100];
+ const images = [];
+ globalThis.Image = class {
+ constructor() {
+ images.push(this);
+ }
+ set src(value) {
+ this._src = value;
+ if (value)
+ queueMicrotask(() => {
+ [this.naturalWidth, this.naturalHeight] = size;
+ this.onload?.();
+ });
+ }
+ get src() {
+ return this._src;
+ }
+ };
+ await assert.rejects(
+ loadImage('https://x/a.jpg', { crossOrigin: false }),
+ (error) => error.tooLarge === true,
+ );
+ assert.equal(images.at(-1).src, '', 'its pixels let go');
+ size = [4000, 3000];
+ const ok = await loadImage('https://x/b.jpg', { crossOrigin: false });
+ assert.equal(ok.naturalWidth, 4000);
+ // An aborted <img> load stops and rejects.
+ size = [10, 10];
+ const controller = new AbortController();
+ const aborted = loadImage('https://x/c.jpg', {
+ crossOrigin: false,
+ signal: controller.signal,
+ });
+ controller.abort();
+ await assert.rejects(aborted);
+ assert.equal(images.at(-1).src, '', 'its download stops');
+ });
diff --cc src/layers/streetLevel/policy.js
index 34a9400b6,a5e95d7d8..4bf7f953d
--- a/src/layers/streetLevel/policy.js
+++ b/src/layers/streetLevel/policy.js
@@@ -1,37 -1,23 +1,29 @@@
- /** Identity and tuning for the Street Level layer and its Mapillary provider. */
- export const STREET_LEVEL_LAYER_ID = 'street-level';
- export const MAPILLARY_PROVIDER_ID = 'mapillary';
- export const MAPILLARY_NAME = 'Mapillary';
- export const MAPILLARY_LABEL = 'MAPILLARY';
- export const MAPILLARY_KEY_ID = 'mapillary';
- export const MAPILLARY_GRAPH_HOST = 'https://graph.mapillary.com';
+ // Reached by the providers' source modules (no browser globals, see
+ // check:boundaries), so no i18n import: the text stays English data here.
+ const msg = (text) => text;
- /** What the provider needs from its source (source.js or a stand-in). */
- export const MAPILLARY_SOURCE_METHODS = Object.freeze([
- 'getStatus',
- 'getTile',
- 'getSequenceImages',
- ]);
+ /** Identity and shared tuning for the provider-neutral Street Level layer. */
+ export const STREET_LEVEL_LAYER_ID = 'street-level';
+/**
+ * The pixel window a click picks in: coverage lines are 2.5 px wide and there
+ * is no hover cue, so a click a few pixels off still finds the line.
+ */
+export const CLICK_PICK_WINDOW_PX = 9;
+
- /** Pick id of the viewer position marker. */
+ /** Pick id of the viewer position marker; the core owns it, not a provider. */
export const POSITION_PICK_ID = 'sl:pos';
- /** Stable id prefixes for picked primitives; every one starts with `mly:`. */
- export const PICK_PREFIX = Object.freeze({
- root: 'mly:',
- sequence: 'mly:seq:',
- image: 'mly:img:',
-/** One colour per imagery source: chip, coverage lines, points, cones and legend. */
++/** One colour per imagery source: chip, coverage lines and cones. */
+ export const PROVIDER_COLORS = Object.freeze({
+ mapillary: '#05cb63',
+ google: '#4285f4',
+ kartaview: '#635bff',
+ panoramax: '#ff6f00',
});
- /** Mapillary green for lines and cones, GEV cyan for the selection, amber for the marker. */
+ /** Colours every provider shares: the selection highlight and the marker. */
export const COLORS = Object.freeze({
- coverage: '#05cb63',
selected: '#00d4ff',
position: '#ffb300',
});
@@@ -42,49 -28,25 +34,25 @@@ export const PANO_MODES = Object.freeze
/** Longest "captured since" window the filter accepts, in days (~100 years). */
export const MAX_SINCE_DAYS = 36_500;
- /** Filter the layer starts with: all imagery, any date. */
+ /** Filter every provider starts with: all imagery, any date. */
export const FILTER_DEFAULT = Object.freeze({ pano: 'all', sinceDays: 0 });
- /** Camera-driven coverage refresh. */
- export const COVERAGE_MOVE_DEBOUNCE_MS = 320;
- export const COVERAGE_MAX_TILES = 9;
- /** Shown when Mapillary refuses the server's token (401/403). */
- export const KEY_REJECTED_MESSAGE =
- 'Mapillary rejected MAPILLARY_CLIENT_TOKEN — replace it in Provider Settings';
- /** Shown while Mapillary rate-limits tile requests (429). */
- export const RATE_LIMITED_MESSAGE =
- 'Coverage requests are being rate-limited — they resume on their own';
- /**
- * Street-zoom coverage reaches this far from the camera: camera height times
- * the factor, never below the floor, even when a tilted view sees further.
- */
- export const SEQUENCE_VIEW_RANGE_MIN_M = 2_500;
- export const SEQUENCE_VIEW_RANGE_PER_HEIGHT = 10;
- export const COVERAGE_MAX_SEQUENCES = 6000;
- export const COVERAGE_LINE_WIDTH_PX = 2.5;
-
- /** Per-sequence image cones after a sequence is selected. */
- export const SEQUENCE_IMAGES_LIMIT = 2000;
- export const IMAGE_CONE_SIZE_PX = 26;
- export const IMAGE_CONE_MIN_SPACING_M = 3;
-/** Nearest-image search radius in metres (Mapillary's graph API caps it at 50 m). */
++/** Nearest-image search radius in metres. */
+ export const NEAREST_RADIUS_M = 50;
- /** On-globe credit: Mapillary imagery is CC BY-SA 4.0 and needs attribution. */
- export const MAPILLARY_CREDIT_HTML =
- 'Street Level: imagery © <a href="https://www.mapillary.com" target="_blank" rel="noopener">Mapillary</a> contributors, CC BY-SA 4.0';
-/**
- * The only map stack camera follow is offered on: elsewhere a camera at eye
- * height looks at a smeared texture.
- */
-export const FOLLOW_MAP_STACK_ID = 'photoreal';
-
-/** Eye height above the sampled ground when the globe camera follows the viewer. */
-export const FOLLOW_EYE_HEIGHT_M = 2.4;
++/** The Google 3D map stack: Street View may be shown only on it. */
++export const GOOGLE_3D_MAP_STACK_ID = 'photoreal';
- /** Deep link to an image on mapillary.com, as the web app shares them. */
- export function mapillaryImageUrl(imageId) {
- const id = String(imageId || '').trim();
- if (!id) return 'https://www.mapillary.com/app/';
- return `https://www.mapillary.com/app/?pKey=${encodeURIComponent(id)}&focus=photo`;
- }
+ /** Above this, a ground click is a misclick, not a street. */
+ export const GROUND_CLICK_MAX_HEIGHT_M = 3_000;
- /** Fields requested for a sequence's images. */
- export const SEQUENCE_IMAGE_FIELDS =
- 'id,captured_at,compass_angle,geometry,is_pano';
+ /** English data: the Street Level panel translates it (translateKnown). */
+ export const AIM_AT_GROUND_MESSAGE = msg(
+ 'Aim the middle of the view at a street to look for imagery there',
+ );
+
+/** The key gate's label for the pill and the layer list, or null when the key is fine. */
+export function keyStatusLabel({ keyRequired, keyRejected }) {
- if (keyRejected) return 'KEY REJECTED';
- return keyRequired ? 'KEY REQUIRED' : null;
++ if (keyRejected) return msg('KEY REJECTED');
++ return keyRequired ? msg('KEY REQUIRED') : null;
+}
diff --cc src/layers/streetLevel/providers/google/index.js
index 000000000,5789a9321..d32ee95f6
mode 000000,100644..100644
--- a/src/layers/streetLevel/providers/google/index.js
+++ b/src/layers/streetLevel/providers/google/index.js
@@@ -1,0 -1,185 +1,181 @@@
-import { FOLLOW_MAP_STACK_ID } from '../../policy.js';
++import { GOOGLE_3D_MAP_STACK_ID } from '../../policy.js';
+ import { createMapsLoader } from './mapsLoader.js';
+ import { getLocale } from '../../../../i18n/index.js';
+ import { createGoogleViewer } from './viewer.js';
+ import {
+ COLORS,
+ GOOGLE_CREDIT_HTML,
+ GOOGLE_KEY_ID,
+ GOOGLE_LABEL,
+ GOOGLE_NAME,
+ GOOGLE_PROVIDER_ID,
+ GROUND_CLICK_HINT,
+ KEY_REJECTED_MESSAGE,
+ NEAREST_RADIUS_M,
+ NEAREST_TIMEOUT_MS,
+ NO_ANSWER_MESSAGE,
+ PICK_PREFIX,
+ } from './policy.js';
+
+ /** `promise`, unless it times out, `signal` aborts or Google refuses the key. */
+ function settleWithin(promise, { ms, signal, loader }) {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(
+ () => finish(reject, new Error(NO_ANSWER_MESSAGE)),
+ ms,
+ );
+ const onAbort = () => finish(reject, signal.reason);
+ signal?.addEventListener('abort', onAbort, { once: true });
+ const stopAuthWatch = loader.onAuthFailure(() =>
+ finish(reject, new Error(KEY_REJECTED_MESSAGE)),
+ );
+ promise.then(
+ (value) => finish(resolve, value),
+ (error) => finish(reject, error),
+ );
+ function finish(settle, value) {
+ clearTimeout(timer);
+ signal?.removeEventListener('abort', onAbort);
+ stopAuthWatch();
+ settle(value);
+ }
+ });
+ }
+
+ /**
+ * Google Street View provider: Google's panorama viewer and nearest-panorama
+ * lookups. It draws no coverage; a click on a street opens the panorama.
+ * @returns {import('../../registry.js').StreetLevelProvider}
+ */
+ export function createGoogleProvider({
+ getApiKey,
+ loader = createMapsLoader({ getApiKey, getLanguage: getLocale }),
+ }) {
+ if (typeof getApiKey !== 'function')
+ throw new TypeError('Google Street View needs getApiKey');
+
+ return Object.freeze({
+ id: GOOGLE_PROVIDER_ID,
+ name: GOOGLE_NAME,
+ label: GOOGLE_LABEL,
+ requiresKeyId: GOOGLE_KEY_ID,
+ pickPrefix: PICK_PREFIX.root,
+ colors: COLORS,
+ credit: Object.freeze({ html: GOOGLE_CREDIT_HTML }),
+ groundClick: true,
+ // Google's terms forbid Street View beside non-Google maps.
- requiresMapStack: FOLLOW_MAP_STACK_ID,
++ requiresMapStack: GOOGLE_3D_MAP_STACK_ID,
+ // Every panorama is billed to the Maps key.
+ defaultOn: false,
+ // All 360°, and no coverage for a date filter to thin.
+ filters: [],
+ marker: Object.freeze({ kind: 'view-cone', color: COLORS.coverage }),
+
+ create(context) {
+ let keyRequired = !getApiKey();
+ let active = false;
+ let service = null;
+ async function getService() {
+ const lib = await loader.importLibrary('streetView');
+ service ||= new lib.StreetViewService();
+ return service;
+ }
+ const viewer = createGoogleViewer({
+ loader,
+ getService,
+ render: context.services?.render,
+ });
+ const stopAuthWatch = loader.onAuthFailure(() => {
+ // Switched off: its chip says so.
+ if (context.isActive?.())
+ context.actions.reportError(KEY_REJECTED_MESSAGE);
+ context.notify();
+ });
+
+ return {
+ async status() {
+ keyRequired = !getApiKey();
+ context.notify();
+ return { configured: !keyRequired };
+ },
+
+ init() {},
+
+ activate() {
+ active = true;
+ },
+
+ deactivate() {
+ active = false;
+ },
+
+ destroy() {
+ active = false;
+ stopAuthWatch();
+ },
+
- refreshCoverage() {},
-
+ /** No filter applies to Street View (see `filters`). */
+ setFilter() {},
+
+ coverageStats() {
+ const keyRejected = loader.authFailed();
+ return {
+ count: 0,
- zoom: null,
- kind: null,
+ loading: false,
+ hint:
+ !active || keyRequired || keyRejected ? '' : GROUND_CLICK_HINT,
+ error: keyRejected ? KEY_REJECTED_MESSAGE : null,
+ keyRequired,
+ keyRejected,
+ };
+ },
+
+ handlePick: () => false,
+
+ /**
+ * Nearest Google-collected outdoor panorama, or null. The imagery
+ * filters do not apply (see `filters`).
+ */
+ async nearestImage({ lat, lon }, { signal } = {}) {
+ if (loader.authFailed()) throw new Error(KEY_REJECTED_MESSAGE);
+ signal?.throwIfAborted();
+ // Set once the caller has its answer (aborted, timed out, refused):
+ // a lookup still waiting on Google's script then asks nothing.
+ let settled = false;
+ const lookup = (async () => {
+ const lib = await loader.importLibrary('streetView');
+ await getService();
+ if (settled) return null;
+ const { GOOGLE, OUTDOOR } = lib.StreetViewSource;
+ try {
+ const { data } = await service.getPanorama({
+ location: { lat, lng: lon },
+ radius: NEAREST_RADIUS_M,
+ // Both: Google's own imagery, outdoors (sources intersect).
+ sources: [GOOGLE, OUTDOOR],
+ preference: lib.StreetViewPreference.NEAREST,
+ });
+ return data;
+ } catch (error) {
+ if (error?.code === 'ZERO_RESULTS') return null;
+ throw error;
+ }
+ })();
+ const data = await settleWithin(lookup, {
+ ms: NEAREST_TIMEOUT_MS,
+ signal,
+ loader,
+ }).finally(() => {
+ settled = true;
+ });
+ const panoId = data?.location?.pano;
+ if (!panoId) return null;
+ viewer.remember(panoId, data);
+ return panoId;
+ },
+
+ viewer,
+ };
+ },
+ });
+ }
diff --cc src/layers/streetLevel/providers/kartaview/decode.js
index 000000000,bee93d76c..dabe821f1
mode 000000,100644..100644
--- a/src/layers/streetLevel/providers/kartaview/decode.js
+++ b/src/layers/streetLevel/providers/kartaview/decode.js
@@@ -1,0 -1,176 +1,176 @@@
+ import { MASK_KEEP_SHARE, MASK_SAMPLE_PX } from './policy.js';
+
+ /** More than any real tile holds (a dense z13 tile has ~4,700 segments). */
+ export const MAX_TILE_SEGMENTS = 20_000;
+ /** A chained line stops growing here and the next one starts. */
+ export const MAX_LINE_POINTS = 5_000;
+
+ /**
+ * The way segments of a KartaView coverage tile
+ * (`{lines: [{track: [{lat, lng}]}]}`), as [lon, lat] point lists. Lines
+ * carry no sequence, date or projection: a filter thins them through a mask
+ * (see `maskedSegments`).
+ * @param {object} payload
+ * @returns {Array<Array<[number, number]>>}
+ */
+ export function tileSegments(payload) {
+ // Not cached as empty: an unreadable tile is asked for again.
+ if (!Array.isArray(payload?.lines))
+ throw new Error('KartaView sent an unreadable coverage tile');
+ const segments = [];
+ for (const line of payload.lines) {
+ if (segments.length >= MAX_TILE_SEGMENTS) break;
+ const points = [];
+ for (const point of Array.isArray(line?.track) ? line.track : []) {
+ const lon = Number(point?.lng);
+ const lat = Number(point?.lat);
+ if (!Number.isFinite(lon) || !Number.isFinite(lat)) continue;
+ const last = points[points.length - 1];
+ if (last && last[0] === lon && last[1] === lat) continue;
+ points.push([lon, lat]);
+ }
+ if (points.length >= 2) segments.push(points);
+ }
+ return segments;
+ }
+
+ /**
+ * Segments chained into line records for the shared coverage: segments
+ * that meet end to start are joined, which cuts the line count about
+ * fourfold.
+ * @param {Array<Array<[number, number]>>} segments
+ * @param {{x: number, y: number, z: number}} address
- * @returns {{sequences: Array<{id: string, parts: Array<Array<[number, number]>>, capturedAt: number, isPano: boolean}>, overview: Array<never>}}
++ * @returns {{sequences: Array<{id: string, parts: Array<Array<[number, number]>>, capturedAt: number, isPano: boolean}>}}
+ */
+ export function chainSegments(segments, { x, y, z }) {
+ const key = ([lon, lat]) => `${lon},${lat}`;
+ const startingAt = new Map();
+ segments.forEach((segment, index) => {
+ const at = key(segment[0]);
+ const list = startingAt.get(at);
+ if (list) list.push(index);
+ else startingAt.set(at, [index]);
+ });
+ const used = new Uint8Array(segments.length);
+ // Per start point, how far its list has been used: each segment is looked
+ // at once, so a tile of segments sharing one point stays linear.
+ const cursor = new Map();
+ const nextFrom = (point) => {
+ const at = key(point);
+ const list = startingAt.get(at);
+ if (!list) return undefined;
+ let i = cursor.get(at) ?? 0;
+ while (i < list.length && used[list[i]]) i++;
+ cursor.set(at, i);
+ return list[i];
+ };
+ const sequences = [];
+ segments.forEach((segment, index) => {
+ if (used[index]) return;
+ used[index] = 1;
+ const chain = [...segment];
+ for (;;) {
+ const next = nextFrom(chain[chain.length - 1]);
+ if (next === undefined) break;
+ // Full: the segment starts the next line instead.
+ if (chain.length + segments[next].length - 1 > MAX_LINE_POINTS) break;
+ used[next] = 1;
+ chain.push(...segments[next].slice(1));
+ }
+ sequences.push({
+ id: `${z}/${x}/${y}/${sequences.length}`,
+ parts: [chain],
+ capturedAt: 0,
+ isPano: false,
+ });
+ });
- return { sequences, overview: [] };
++ return { sequences };
+ }
+
+ /** Decode a KartaView coverage tile into the shared coverage's line records. */
+ export function decodeCoverageTile(payload, address) {
+ return chainSegments(tileSegments(payload), address);
+ }
+
+ /**
+ * The segments a filtered PNG tile of the same address draws over. The PNG
+ * draws the same ways a few pixels wide (on a transparent ground): a
+ * segment is kept when at least half the points sampled along it have a
+ * drawn pixel within one pixel. Segments either lie on it or miss it
+ * almost entirely (Jakarta, 360° only: 332 of 1,041 kept, 676 missed, 33
+ * between). A segment with no point on the tile is not this tile's to keep.
+ * @param {Array<Array<[number, number]>>} segments
+ * @param {{width: number, height: number, alpha: ArrayLike<number>}} mask one alpha byte per pixel
+ * @param {{x: number, y: number, z: number}} address
+ */
+ export function maskedSegments(segments, mask, { x, y, z }) {
+ const { width, height, alpha } = mask;
+ const n = 2 ** z;
+ const toPixel = ([lon, lat]) => {
+ const sin = Math.sin((lat * Math.PI) / 180);
+ const my = 0.5 - Math.log((1 + sin) / (1 - sin)) / (4 * Math.PI);
+ return [(((lon + 180) / 360) * n - x) * width, (my * n - y) * height];
+ };
+ const drawnNear = (px, py) => {
+ const cx = Math.floor(px);
+ const cy = Math.floor(py);
+ for (let dy = -1; dy <= 1; dy++)
+ for (let dx = -1; dx <= 1; dx++) {
+ const X = cx + dx;
+ const Y = cy + dy;
+ if (X < 0 || Y < 0 || X >= width || Y >= height) continue;
+ if (alpha[Y * width + X] > 0) return true;
+ }
+ return false;
+ };
+ return segments.filter((segment) => {
+ let on = 0;
+ let tested = 0;
+ let [ax, ay] = toPixel(segment[0]);
+ for (let i = 1; i < segment.length; i++) {
+ const [bx, by] = toPixel(segment[i]);
+ const steps = Math.max(
+ 1,
+ Math.ceil(Math.hypot(bx - ax, by - ay) / MASK_SAMPLE_PX),
+ );
+ // Each point once: a segment's next stretch starts where this one ends.
+ for (let j = i === 1 ? 0 : 1; j <= steps; j++) {
+ const px = ax + ((bx - ax) * j) / steps;
+ const py = ay + ((by - ay) * j) / steps;
+ if (px < 0 || py < 0 || px >= width || py >= height) continue;
+ tested++;
+ if (drawnNear(px, py)) on++;
+ }
+ ax = bx;
+ ay = by;
+ }
+ return tested > 0 && on / tested >= MASK_KEEP_SHARE;
+ });
+ }
+
+ /**
+ * A PNG mask's alpha, one byte per pixel, decoded off the main thread
+ * where the browser can.
+ * @param {Uint8Array} bytes the PNG
+ * @returns {Promise<{width: number, height: number, alpha: Uint8Array}>}
+ */
+ export async function readMaskImage(bytes) {
+ const bitmap = await createImageBitmap(
+ new Blob([bytes], { type: 'image/png' }),
+ );
+ try {
+ const { width, height } = bitmap;
+ const canvas =
+ typeof OffscreenCanvas === 'function'
+ ? new OffscreenCanvas(width, height)
+ : Object.assign(document.createElement('canvas'), { width, height });
+ const context = canvas.getContext('2d', { willReadFrequently: true });
+ context.drawImage(bitmap, 0, 0);
+ const rgba = context.getImageData(0, 0, width, height).data;
+ const alpha = new Uint8Array(width * height);
+ for (let i = 0; i < alpha.length; i++) alpha[i] = rgba[i * 4 + 3];
+ return { width, height, alpha };
+ } finally {
+ bitmap.close?.();
+ }
+ }
diff --cc src/layers/streetLevel/providers/kartaview/decode.test.mjs
index 000000000,619719008..c96fb66a8
mode 000000,100644..100644
--- a/src/layers/streetLevel/providers/kartaview/decode.test.mjs
+++ b/src/layers/streetLevel/providers/kartaview/decode.test.mjs
@@@ -1,0 -1,187 +1,186 @@@
+ import assert from 'node:assert/strict';
+ import test from 'node:test';
+ import {
+ MAX_LINE_POINTS,
+ MAX_TILE_SEGMENTS,
+ chainSegments,
+ decodeCoverageTile,
+ maskedSegments,
+ tileSegments,
+ } from './decode.js';
+
+ const at = (lng, lat) => ({ lat: String(lat), lng: String(lng) });
+ const TILE = { x: 4412, y: 6061, z: 14 };
+
+ test('segments that meet end to start chain into one line', () => {
- const { sequences, overview } = decodeCoverageTile(
++ const { sequences } = decodeCoverageTile(
+ {
+ lines: [
+ { track: [at(1, 1), at(2, 1)], matched: '1' },
+ { track: [at(5, 5), at(6, 6)], matched: '1' },
+ { track: [at(2, 1), at(3, 1), at(4, 2)], matched: '1' },
+ ],
+ },
+ TILE,
+ );
- assert.deepEqual(overview, []);
+ assert.equal(sequences.length, 2);
+ assert.deepEqual(sequences[0].parts, [
+ [
+ [1, 1],
+ [2, 1],
+ [3, 1],
+ [4, 2],
+ ],
+ ]);
+ assert.equal(sequences[0].id, '14/4412/6061/0');
+ assert.equal(sequences[1].id, '14/4412/6061/1');
+ // Nothing to date or project: every line passes as flat and undated.
+ assert.equal(sequences[0].capturedAt, 0);
+ assert.equal(sequences[0].isPano, false);
+ });
+
+ test('a junction continues one way only, and every segment is drawn exactly once', () => {
+ const { sequences } = decodeCoverageTile(
+ {
+ lines: [
+ { track: [at(0, 0), at(1, 0)] },
+ { track: [at(1, 0), at(2, 0)] },
+ { track: [at(1, 0), at(1, 1)] },
+ // A loop back to its own start must end, not spin.
+ { track: [at(9, 9), at(9, 8)] },
+ { track: [at(9, 8), at(9, 9)] },
+ ],
+ },
+ TILE,
+ );
+ const points = sequences.reduce((sum, s) => sum + s.parts[0].length, 0);
+ assert.equal(sequences.length, 3);
+ // 5 segments of 2 points, 2 joins in chains: 10 - 2 = 8 points.
+ assert.equal(points, 8);
+ });
+
+ test('bad points, repeats and one-point tracks are skipped; an empty tile has no lines', () => {
+ const { sequences } = decodeCoverageTile(
+ {
+ lines: [
+ { track: [at(1, 1), at(1, 1), { lat: 'x', lng: '2' }, at(2, 2)] },
+ { track: [at(3, 3)] },
+ { track: null },
+ null,
+ ],
+ },
+ TILE,
+ );
+ assert.equal(sequences.length, 1);
+ assert.deepEqual(sequences[0].parts[0], [
+ [1, 1],
+ [2, 2],
+ ]);
+ assert.deepEqual(decodeCoverageTile({ lines: [] }, TILE).sequences, []);
+ });
+
+ test('a tile that is not a line list fails, so it is asked for again rather than kept empty', () => {
+ for (const payload of [
+ null,
+ {},
+ { lines: 'nope' },
+ { status: { apiCode: 690 } },
+ ])
+ assert.throws(
+ () => decodeCoverageTile(payload, TILE),
+ /unreadable coverage tile/,
+ );
+ });
+
+ test('a tile whose segments all share one point decodes in linear time', () => {
+ // [P, Q_i, P]: every chain step looks at the same start point's list.
+ // 60k: the old quadratic chaining took over a second; capped and linear
+ // decoding takes tens of milliseconds.
+ const lines = Array.from({ length: 60_000 }, (_, i) => ({
+ track: [at(0, 0), at(1 + i * 1e-6, 1), at(0, 0)],
+ }));
+ const started = performance.now();
+ const { sequences } = decodeCoverageTile({ lines }, TILE);
+ const ms = performance.now() - started;
+ assert.ok(
+ ms < 1_000,
+ `${Math.round(ms)} ms (quadratic chaining took ~200 ms per 20k and grows fourfold per doubling)`,
+ );
+ const points = sequences.reduce((sum, s) => sum + s.parts[0].length, 0);
+ assert.ok(sequences.every((s) => s.parts[0].length <= MAX_LINE_POINTS));
+ assert.equal(
+ points,
+ MAX_TILE_SEGMENTS * 2 + sequences.length,
+ 'every segment drawn once',
+ );
+ });
+
+ test('a tile is capped in segments and in points per line', () => {
+ const lines = Array.from({ length: MAX_TILE_SEGMENTS + 500 }, (_, i) => ({
+ track: [at(i, 0), at(i + 1, 0)],
+ }));
+ const { sequences } = decodeCoverageTile({ lines }, TILE);
+ const points = sequences.reduce((sum, s) => sum + s.parts[0].length, 0);
+ // One long chain, cut into lines of at most MAX_LINE_POINTS.
+ assert.ok(sequences.every((s) => s.parts[0].length <= MAX_LINE_POINTS));
+ assert.ok(points <= MAX_TILE_SEGMENTS + sequences.length);
+ assert.ok(
+ sequences.length >= Math.floor(MAX_TILE_SEGMENTS / MAX_LINE_POINTS),
+ );
+ });
+
+ /** [lon, lat] at pixel (px, py) of a 512 px mask of `tile` (Web Mercator). */
+ function lonLatAt(px, py, { x, y, z } = TILE, size = 512) {
+ const n = 2 ** z;
+ const lon = ((x + px / size) / n) * 360 - 180;
+ const my = Math.PI * (1 - (2 * (y + py / size)) / n);
+ const lat = (Math.atan(Math.sinh(my)) * 180) / Math.PI;
+ return [lon, lat];
+ }
+
+ /** A 512 px mask drawn on the given rows. */
+ function rowsMask(rows) {
+ const alpha = new Uint8Array(512 * 512);
+ for (const [from, to] of rows) alpha.fill(255, from * 512, (to + 1) * 512);
+ return { width: 512, height: 512, alpha };
+ }
+
+ test('a mask keeps the segments it draws over, chained as before', () => {
+ const along = (row, from = 40, to = 470) => [
+ lonLatAt(from, row),
+ lonLatAt(to, row),
+ ];
+ const segments = [
+ along(100), // drawn at row 100
+ along(101.6), // a pixel off: still drawn within one pixel
+ along(300), // not drawn
+ // Two thirds along the drawn row, then off it: kept (at least half).
+ [lonLatAt(40, 100), lonLatAt(400, 100), lonLatAt(400, 280)],
+ // A third along it, then off: dropped.
+ [lonLatAt(300, 100), lonLatAt(400, 100), lonLatAt(400, 300)],
+ // Off the tile entirely: not this tile's to keep.
+ [lonLatAt(-200, 100), lonLatAt(-20, 100)],
+ ];
+ const kept = maskedSegments(segments, rowsMask([[99, 100]]), TILE);
+ assert.deepEqual(kept, [segments[0], segments[1], segments[3]]);
+ assert.deepEqual(maskedSegments(segments, rowsMask([]), TILE), []);
+ // A full mask keeps every segment that is on the tile.
+ assert.equal(maskedSegments(segments, rowsMask([[0, 511]]), TILE).length, 5);
+ });
+
+ test('decoding is segments then chaining: the same lines either way', () => {
+ const payload = {
+ lines: [
+ { track: [at(1, 1), at(2, 1)] },
+ { track: [at(2, 1), at(3, 1)] },
+ { track: [at(5, 5), at(6, 6)] },
+ ],
+ };
+ const segments = tileSegments(payload);
+ assert.equal(segments.length, 3);
+ assert.deepEqual(
+ chainSegments(segments, TILE),
+ decodeCoverageTile(payload, TILE),
+ );
+ assert.throws(() => tileSegments({}), /unreadable coverage tile/);
+ });
diff --cc src/layers/streetLevel/providers/kartaview/index.js
index 000000000,1cf2513f3..6e75f967a
mode 000000,100644..100644
--- a/src/layers/streetLevel/providers/kartaview/index.js
+++ b/src/layers/streetLevel/providers/kartaview/index.js
@@@ -1,0 -1,611 +1,578 @@@
-import { createLineCoverage } from '../../lineCoverage.js';
++import { createLineCoverage, freshCoverage } from '../../lineCoverage.js';
+ import { createLru, createTileCache } from '../../tileCache.js';
+
+ export { createTileCache } from '../../tileCache.js';
+ import { createSequenceCones, thinImages } from '../../sequenceCones.js';
+ import { metresBetween } from '../../view.js';
+ import {
+ chainSegments,
+ maskedSegments,
+ readMaskImage,
+ tileSegments,
+ } from './decode.js';
+ import { createKartaViewSource } from './source.js';
+ import { createKartaViewViewer } from './viewer.js';
+ import { msg } from '../../../../i18n/index.js';
+ import {
+ ARCHIVED_MESSAGE,
+ COLORS,
+ COVERAGE_MAX_HEIGHT_M,
+ COVERAGE_NOUN,
+ COVERAGE_STREET_ZOOM_BELOW_M,
+ COVERAGE_TUNING,
+ FILTERED_OUT_MESSAGE,
+ KARTAVIEW_CREDIT_HTML,
+ KARTAVIEW_LABEL,
+ KARTAVIEW_NAME,
+ KARTAVIEW_PROVIDER_ID,
+ LINE_CLICK_HINT,
+ NEAREST_PROBES,
+ NEAREST_RADIUS_M,
+ NO_COVERAGE_HINT,
+ PICK_PREFIX,
+ RATE_LIMITED_MESSAGE,
+ SEQUENCE_PAGE_EDGE,
+ SEQUENCE_PAGE_SIZE,
+ TOO_HIGH_HINT,
+ assignCourses,
+ cameraBearing,
+ normalizePhoto,
+ passesKartaViewFilter,
+ tileFilterQuery,
+ } from './policy.js';
+
+ /** Photos kept in memory by id (sequence pages fill it). */
+ const PHOTO_CACHE_SIZE = 4000;
+ /** Sequence pages kept in memory. */
+ const PAGE_CACHE_SIZE = 12;
+
+ /** z14 near the street, z13 a little higher, nothing above. */
+ export function kartaViewZoomFor(heightM) {
+ if (!Number.isFinite(heightM) || heightM > COVERAGE_MAX_HEIGHT_M) return null;
- return {
- zoom: heightM > COVERAGE_STREET_ZOOM_BELOW_M ? 13 : 14,
- kind: 'sequence',
- };
++ return heightM > COVERAGE_STREET_ZOOM_BELOW_M ? 13 : 14;
+ }
+
+ /** The 1-based page of a sequence that holds `index`, if no photo is missing. */
+ function pageOf(index) {
+ return Math.floor(Math.max(0, index) / SEQUENCE_PAGE_SIZE) + 1;
+ }
+
+ /**
+ * KartaView Street Level provider: keyless coverage lines from KartaView's
+ * tile API, the photos nearest a clicked line, cones along the photo's
+ * sequence, and a flat or 360° viewer with ‹ › along the sequence.
+ * @param {{source?: ReturnType<typeof createKartaViewSource>, viewerOptions?: object, readMask?: typeof readMaskImage}} [options]
+ * @returns {import('../../registry.js').StreetLevelProvider}
+ */
+ export function createKartaViewProvider({
+ source = createKartaViewSource(),
+ viewerOptions = {},
+ readMask = readMaskImage,
+ } = {}) {
+ return Object.freeze({
+ id: KARTAVIEW_PROVIDER_ID,
+ name: KARTAVIEW_NAME,
+ label: KARTAVIEW_LABEL,
+ requiresKeyId: null,
+ pickPrefix: PICK_PREFIX.root,
+ colors: COLORS,
+ // Its own marker, as Street View has: a purple cone that turns with the view.
+ marker: Object.freeze({ kind: 'view-cone', color: COLORS.coverage }),
+ credit: Object.freeze({ html: KARTAVIEW_CREDIT_HTML }),
+ defaultOn: false,
+ // 360° / flat and SINCE, as Mapillary: KartaView filters the lines on
+ // its server (see tileFilterQuery), the photos by their own record.
+ filters: Object.freeze(['pano', 'since']),
+ // SINCE is the upload date for KartaView: the panel notes it.
+ sinceBasis: 'upload',
- // Its lines are streets, not sequences: a selected drive shows as cones.
- highlightsSequence: false,
+ coverageLabel: Object.freeze({
+ noun: COVERAGE_NOUN,
+ action: LINE_CLICK_HINT,
+ }),
+
+ create(context) {
+ const state = {
+ context,
+ services: context.services,
+ viewer: null,
- keyRequired: false,
- keyRejected: false,
- statusKnown: true,
- coverage: {
- zoom: null,
- tiles: new Map(),
- stale: new Map(),
- staleTimer: null,
- pending: new Map(),
- lastError: null,
- holdUntil: 0,
- holdTimer: null,
- debounceTimer: null,
- removeCameraListener: null,
- terrainReady: null,
- hint: '',
- kind: null,
- },
++ coverage: freshCoverage({ keyless: true }),
+ sequence: {
+ selectedId: null,
+ images: [],
- cache: new Map(),
+ collection: null,
+ loading: false,
++ error: null,
+ abort: null,
+ },
+ };
+ const photos = createLru(PHOTO_CACHE_SIZE);
+ const pages = createLru(PAGE_CACHE_SIZE);
+ /** The photo last opened in each sequence: its cones centre on it. */
+ const anchors = new Map();
+ /** The sequence page the cones were drawn from. */
+ let drawnPage = null;
+
+ /** A record as a photo; the one already known keeps its identity (and course). */
+ function remember(record) {
+ const fresh = normalizePhoto(record);
+ if (!fresh) return null;
+ const known = photos.get(fresh.id);
+ const photo = known ? Object.assign(known, fresh) : fresh;
+ photos.set(photo.id, photo);
+ return photo;
+ }
+
+ async function getPhoto(photoId, { signal } = {}) {
+ const cached = photos.get(photoId);
+ if (cached) return cached;
+ const photo = remember(await source.getPhoto(photoId, { signal }));
+ if (!photo)
+ throw new Error(msg('KartaView has no position for this photo'));
+ return photo;
+ }
+
+ /** A page of a sequence's photos, in index order (shared while in flight). */
+ function loadPage(sequenceId, page) {
+ const key = `${sequenceId}:${page}`;
+ let entry = pages.get(key);
+ if (!entry) {
+ entry = source
+ .getSequencePhotos(sequenceId, {
+ page,
+ itemsPerPage: SEQUENCE_PAGE_SIZE,
+ })
+ .then(({ photos: records, hasMore }) => {
+ const list = assignCourses(
+ records
+ .map(remember)
+ .filter(Boolean)
+ .sort(
+ (a, b) => (a.sequenceIndex ?? 0) - (b.sequenceIndex ?? 0),
+ ),
+ metresBetween,
+ );
+ // The open photo may have just learnt which way it looked. The
+ // page is good whatever the viewer is doing.
+ try {
+ viewer.refreshPose?.();
+ } catch {
+ /* the next pose carries the direction */
+ }
+ return { page, hasMore, photos: list };
+ });
+ pages.set(key, entry);
+ entry.catch(() => pages.delete(key));
+ }
+ return entry;
+ }
+
+ /**
+ * The page holding `photo`. Pages follow photo ids, which only roughly
+ * follow the index, and photos go missing, so the page the index
+ * suggests is a first guess: step towards the photo until a page holds
+ * it, or the pages straddle where it would be.
+ */
+ async function homePage(photo) {
+ let number = pageOf(photo.sequenceIndex ?? 0);
+ const index = photo.sequenceIndex ?? 0;
+ let page = await loadPage(photo.sequenceId, number);
+ if (!page.photos.length && number > 1) {
+ // Past the end (many photos deleted): find the last page by halving.
+ let low = 1;
+ let high = number - 1;
+ while (low < high) {
+ const middle = Math.ceil((low + high) / 2);
+ if ((await loadPage(photo.sequenceId, middle)).photos.length)
+ low = middle;
+ else high = middle - 1;
+ }
+ number = low;
+ }
+ const seen = new Set();
+ while (!seen.has(number) && seen.size < 8) {
+ seen.add(number);
+ page = await loadPage(photo.sequenceId, number);
+ if (page.photos.some((p) => p.id === photo.id)) return page;
+ const first = page.photos[0]?.sequenceIndex;
+ const last = page.photos.at(-1)?.sequenceIndex;
+ // Past the last page, or before this page's photos: go back.
+ if ((first === undefined || index < first) && number > 1) number--;
+ else if (last !== undefined && index > last && page.hasMore) number++;
+ else break;
+ }
+ return page;
+ }
+
+ /**
+ * The photos around `photo` in index order: its page, plus a
+ * neighbour page when it sits near an edge (pages overlap in index).
+ * @returns {Promise<{home: number, photos: Array<object>}>}
+ */
+ async function windowOf(photo) {
+ const home = await homePage(photo);
+ const list = home.photos;
+ const found = list.findIndex((p) => p.id === photo.id);
+ // A photo no page lists sits where its index would.
+ const at =
+ found !== -1
+ ? found
+ : list.filter(
+ (p) => (p.sequenceIndex ?? 0) < (photo.sequenceIndex ?? 0),
+ ).length;
+ const parts = [list];
+ if (at < SEQUENCE_PAGE_EDGE && home.page > 1)
+ parts.push((await loadPage(photo.sequenceId, home.page - 1)).photos);
+ if (at >= list.length - SEQUENCE_PAGE_EDGE && home.hasMore)
+ parts.push((await loadPage(photo.sequenceId, home.page + 1)).photos);
+ if (parts.length === 1) return { home: home.page, photos: list };
+ const byId = new Map(parts.flat().map((p) => [p.id, p]));
+ return {
+ home: home.page,
+ photos: [...byId.values()].sort(
+ (a, b) => (a.sequenceIndex ?? 0) - (b.sequenceIndex ?? 0),
+ ),
+ };
+ }
+
+ /**
+ * Photo id → whether its file is there (archived ones are not). Only
+ * a definite answer is kept: a storage hiccup is asked again next
+ * time, and meanwhile the photo is tried. A probe is shared, so it
+ * runs to its own timeout rather than any one caller's abort.
+ */
+ const probes = createLru(PHOTO_CACHE_SIZE);
+ function showable(photo) {
+ if (!photo?.urls?.view) return Promise.resolve(false);
+ let probe = probes.get(photo.id);
+ if (!probe) {
+ probe = source.probeImage(photo.urls.view).then(
+ (answer) => {
+ if (answer === null) probes.delete(photo.id);
+ return answer !== false;
+ },
+ () => {
+ probes.delete(photo.id);
+ return true;
+ },
+ );
+ probes.set(photo.id, probe);
+ }
+ return probe;
+ }
+
+ // A tile's way segments, kept a while: panning back, or a filter
+ // change, asks KartaView nothing more for them.
+ const tiles = createTileCache({
+ load: async (tile, { signal }) =>
+ tileSegments(await source.getTile(tile, { signal })),
+ });
+ // A filtered tile's mask, by filter and tile.
+ const masks = createTileCache({
+ load: async ({ query, ...tile }, { signal }) =>
+ readMask(await source.getTileMask(tile, query, { signal })),
+ keyOf: ({ query, z, x, y }) => `${query}|${z}/${x}/${y}`,
+ });
+ /** The tile's lines under the filter now: all, or the masked ones. */
+ async function fetchTile(tile, options) {
+ const query = tileFilterQuery(context.getFilter());
+ if (!query) return chainSegments(await tiles.get(tile, options), tile);
+ const [segments, mask] = await Promise.all([
+ tiles.get(tile, options),
+ masks.get({ ...tile, query }, options),
+ ]);
+ return chainSegments(maskedSegments(segments, mask, tile), tile);
+ }
+ /** The query the drawn lines were loaded under. */
+ let drawnQuery = tileFilterQuery(context.getFilter());
+
+ /**
+ * The next showable photo `delta` along the sequence, or null at its
+ * end. Archived photos are skipped, a few at most.
+ */
+ async function step(photo, delta) {
+ if (!photo?.sequenceId) return null;
+ let from = photo;
+ for (let skipped = 0; skipped <= NEAREST_PROBES; skipped++) {
+ const { photos: list } = await windowOf(from);
+ let at = list.findIndex((p) => p.id === from.id);
+ if (at === -1) {
+ // Not found anywhere: the nearest index on the right side.
+ const index = from.sequenceIndex ?? 0;
+ const later = list.findIndex((p) => (p.sequenceIndex ?? 0) > index);
+ if (delta > 0 && later === -1) return null;
+ at =
+ delta > 0
+ ? later - 1
+ : later === -1
+ ? list.length
+ : list.findIndex((p) => (p.sequenceIndex ?? 0) >= index);
+ }
+ const next = list[at + delta];
+ if (!next) return null;
+ if (await showable(next)) return next.id;
+ from = next;
+ }
+ return null;
+ }
+
+ const coverage = createLineCoverage({
+ state,
+ fetchTile,
+ zoomFor: kartaViewZoomFor,
+ colors: COLORS,
+ pickPrefix: PICK_PREFIX.line,
+ renderKey: 'kartaview-coverage',
+ tuning: COVERAGE_TUNING,
+ messages: { rateLimited: RATE_LIMITED_MESSAGE, tooHigh: TOO_HIGH_HINT },
+ // Filtered on the way in (fetchTile): a line has no date to test.
+ passes: () => true,
+ });
++ // Its lines are streets, not drives: a selected drive shows as cones
++ // only, so the coverage is never highlighted.
+
+ const cones = createSequenceCones({
+ state,
+ async loadImages(sequenceId, { signal }) {
+ let anchor = anchors.get(sequenceId);
+ if (!anchor) return [];
+ let window = await windowOf(anchor);
+ signal?.throwIfAborted();
+ // Another photo of the drive opened while that page loaded (its
+ // re-centre found nothing drawn yet): centre on the newest one.
+ while (anchors.get(sequenceId) !== anchor) {
+ anchor = anchors.get(sequenceId);
+ window = await windowOf(anchor);
+ signal?.throwIfAborted();
+ }
+ drawnPage = { sequenceId, page: window.home };
+ countPhotos(sequenceId);
+ return thinImages(
+ window.photos.map((photo) => ({
+ id: photo.id,
+ lon: photo.lon,
+ lat: photo.lat,
+ compassAngle: cameraBearing(photo) ?? 0,
+ capturedAt: photo.capturedAt ?? 0,
+ uploadedAt: photo.uploadedAt,
+ isPano: photo.isPano,
+ })),
+ );
+ },
+ colors: COLORS,
+ pickPrefix: PICK_PREFIX.image,
+ spriteId: 'street-level:kartaview-cones',
+ renderKey: 'kartaview-sequence',
+ // By projection and upload date, as the lines.
+ passes: passesKartaViewFilter,
+ });
+
+ /** Sequence id → its photo count from KartaView (asked once). */
+ const counts = new Map();
+ function countPhotos(sequenceId) {
+ if (counts.has(sequenceId) || !source.getSequenceCount) return;
+ counts.set(sequenceId, undefined);
+ source.getSequenceCount(sequenceId).then(
+ (count) => {
+ if (count === null) counts.delete(sequenceId);
+ else {
+ counts.set(sequenceId, count);
+ context.notify();
+ }
+ },
+ () => counts.delete(sequenceId),
+ );
+ }
+
+ /** ‹ › open through the core (loading, errors, cones), camera still. */
+ function openStepped(photoId) {
+ context.actions.openImage(photoId, { frame: false });
+ }
+
+ /**
+ * The cones show one page of a sequence: once a photo of the selected
+ * sequence opens on another page (‹ ›, a cone, a line), re-centre them.
+ */
+ async function recentreCones(photo) {
+ if (!photo?.sequenceId) return;
+ if (state.sequence.selectedId !== photo.sequenceId) return;
+ const drawn = drawnPage;
+ if (drawn?.sequenceId !== photo.sequenceId) return;
+ const window = await windowOf(photo).catch(() => null);
+ // Still the drawn page and the latest photo once the page is in.
+ if (
+ window &&
+ drawnPage === drawn &&
+ window.home !== drawn.page &&
+ anchors.get(photo.sequenceId) === photo
+ )
+ cones.select(photo.sequenceId, { force: true });
+ }
+
+ const viewer = createKartaViewViewer({
+ getPhoto: async (photoId) => {
+ const photo = await getPhoto(photoId);
+ if (photo.sequenceId) anchors.set(photo.sequenceId, photo);
+ return photo;
+ },
+ step,
+ onStep: openStepped,
+ onShown: recentreCones,
+ // After a GPU reset the same photo is drawn again by the viewer
+ // itself: going through the core would cancel a lookup the user
+ // started. A failure still shows.
+ onReopen: (photoId) =>
+ viewer
+ .open(photoId)
+ .catch((error) =>
+ context.actions.reportError(
+ error?.message ||
+ msg('The KartaView photo could not be loaded'),
+ ),
+ ),
+ // Esc in the viewer clears the selected drive, as the panel says.
+ onEscape: () => {
+ if (!state.sequence.selectedId) return false;
+ cones.clearSelection();
+ drawnPage = null;
+ return true;
+ },
+ render: context.services?.render,
+ ...viewerOptions,
+ });
+
+ return {
+ async status() {
+ return { configured: true };
+ },
+
+ init(cesiumViewer) {
+ state.viewer = cesiumViewer;
+ cones.ensureCollections(cesiumViewer);
+ cones.setVisible(false);
+ },
+
+ activate(cesiumViewer) {
+ state.viewer = cesiumViewer;
+ cones.setVisible(true);
+ coverage.attach(cesiumViewer);
+ },
+
+ deactivate() {
+ coverage.detach();
+ coverage.clear();
- coverage.resetErrors();
++ coverage.unblock();
+ cones.clearSelection();
+ cones.setVisible(false);
+ drawnPage = null;
+ // Tens of MB of decoded lines are not kept for a source left off.
+ tiles.clear();
+ masks.clear();
+ },
+
+ destroy(cesiumViewer) {
+ coverage.detach();
+ coverage.clear();
- coverage.resetErrors();
++ coverage.unblock();
+ cones.destroy(cesiumViewer);
+ tiles.clear();
+ masks.clear();
+ },
+
- refreshCoverage: () => coverage.refresh(),
-
+ /**
+ * The filter changed: the lines come from KartaView again under it
- * (the old ones show meanwhile), the cones are drawn again.
++ * (cleared until they come), the cones are drawn again.
+ */
+ setFilter() {
+ const query = tileFilterQuery(context.getFilter());
+ if (query !== drawnQuery) {
+ drawnQuery = query;
+ coverage.reload();
+ }
+ cones.rerender();
+ },
+
- setSurface() {
- coverage.setSurface();
- cones.rerender();
- },
-
++ /** Keyless; an empty view that has loaded says there is nothing here. */
+ coverageStats() {
- const { hint } = state.coverage;
- const count = coverage.sequenceCount();
- const loading = state.coverage.pending.size > 0;
++ const stats = coverage.stats();
+ const empty =
+ state.coverage.zoom !== null &&
- !loading &&
- count === 0 &&
- !state.coverage.lastError;
++ !stats.loading &&
++ stats.count === 0 &&
++ !stats.error;
+ return {
- count,
- zoom: state.coverage.zoom,
- kind: state.coverage.kind,
- loading,
- hint: hint || (empty ? NO_COVERAGE_HINT : ''),
- error: state.coverage.lastError,
- keyRequired: false,
- keyRejected: false,
++ ...stats,
++ hint: stats.hint || (empty ? NO_COVERAGE_HINT : ''),
+ };
+ },
+
+ /** A line opens the photo nearest the click; a cone opens its photo. */
+ handlePick(pickId, { groundPoint } = {}) {
+ if (pickId.startsWith(PICK_PREFIX.image)) {
+ context.actions.openImage(pickId.slice(PICK_PREFIX.image.length));
+ return true;
+ }
+ if (pickId.startsWith(PICK_PREFIX.line)) {
+ const point = groundPoint?.();
+ if (point) context.actions.openNearest(point);
+ return true;
+ }
+ return false;
+ },
+
- // Never from the cache: it is keyed by sequence, the cones by page.
++ // Always loaded afresh: the cones show the page of the photo open now.
+ selectSequence: (sequenceId) =>
+ cones.select(sequenceId, { force: true }),
+ clearSequence: () => {
+ cones.clearSelection();
+ drawnPage = null;
+ },
+ // The drive's own count, not the thinned page of it the cones show.
+ sequenceStats: () => ({
+ selectedId: state.sequence.selectedId,
+ images:
+ counts.get(state.sequence.selectedId) ??
+ state.sequence.images.length,
+ loading: state.sequence.loading,
++ error: state.sequence.error,
+ }),
+
+ /**
+ * The nearest photo within the search radius that can be shown, or
+ * null. Many photos are archived (their files answer 409) or have no
+ * file at all, so the nearest few are tried in turn.
+ */
+ async nearestImage({ lat, lon }, { signal } = {}) {
+ const filter = context.getFilter();
+ const records = await source.nearestPhotos(
+ { lat, lon, filter },
+ { signal },
+ );
+ const near = [];
+ let filteredOut = 0;
+ for (const record of records) {
+ const photo = remember(record);
+ if (!photo?.urls.view) continue;
+ const metres = metresBetween({ lat, lon }, photo);
+ if (metres > NEAREST_RADIUS_M) continue;
+ if (!passesKartaViewFilter(photo, filter)) filteredOut++;
+ else near.push({ photo, metres });
+ }
+ near.sort((a, b) => a.metres - b.metres);
+ // Probed side by side (photo storage is not the API host): the
+ // nearest one that answers wins.
+ const candidates = near.slice(0, NEAREST_PROBES);
+ const answers = await Promise.all(
+ candidates.map(({ photo }) => showable(photo, { signal })),
+ );
+ const hit = candidates.find((_, i) => answers[i]);
+ if (hit) return hit.photo.id;
+ if (near.length) throw new Error(ARCHIVED_MESSAGE);
+ if (filteredOut) throw new Error(FILTERED_OUT_MESSAGE);
+ return null;
+ },
+
+ viewer,
+ };
+ },
+ });
+ }
diff --cc src/layers/streetLevel/providers/kartaview/policy.js
index 000000000,137b9cc78..184d1ceb8
mode 000000,100644..100644
--- a/src/layers/streetLevel/providers/kartaview/policy.js
+++ b/src/layers/streetLevel/providers/kartaview/policy.js
@@@ -1,0 -1,399 +1,398 @@@
+ import { COLORS as SHARED_COLORS, PROVIDER_COLORS } from '../../policy.js';
+ import { msg } from '../../../../i18n/index.js';
+
+ export { NEAREST_RADIUS_M } from '../../policy.js';
+
+ /** Identity and tuning for the KartaView street-level provider (keyless). */
+ export const KARTAVIEW_PROVIDER_ID = 'kartaview';
+ export const KARTAVIEW_NAME = 'KartaView';
+ export const KARTAVIEW_LABEL = 'KARTAVIEW';
+
+ /**
+ * The public API. Its documented twin, api.openstreetcam.org, still answers
+ * but serves empty coverage tiles.
+ */
+ export const KARTAVIEW_API_HOST = 'https://api.kartaview.org';
+ /** KartaView's image proxy: resizes a photo given its base64url address. */
+ export const KARTAVIEW_CDN_HOST = 'https://cdn.kartaview.org';
+
+ /** Stable id prefixes for picked primitives; every one starts with `kv:`. */
+ export const PICK_PREFIX = Object.freeze({
+ root: 'kv:',
+ line: 'kv:line:',
+ image: 'kv:img:',
+ });
+
+ export const COLORS = Object.freeze({
+ coverage: PROVIDER_COLORS.kartaview,
+ selected: SHARED_COLORS.selected,
+ });
+
+ /**
+ * Coverage lines are OSM ways with photos, from z13–14 JSON tiles. Lower
+ * zooms take seconds per tile (z10 does not answer), so higher up the panel
+ * asks the user to zoom in.
+ */
+ export const COVERAGE_STREET_ZOOM_BELOW_M = 2_500;
+ export const COVERAGE_MAX_HEIGHT_M = 6_000;
+ export const COVERAGE_TUNING = Object.freeze({
+ maxTiles: 9,
- overviewMaxTiles: 0,
+ // Chained ways are short: a dense downtown z13 tile holds ~1,500, so each
+ // tile may draw 1,600 (a frame stays at 16.7 ms with 4,400 drawn).
+ maxSequences: 14_400,
+ lineWidthPx: 2.5,
- overviewPointPx: 2.5,
+ moveDebounceMs: 320,
+ viewRangeMinM: 2_500,
+ viewRangePerHeight: 10,
- viewNearM: 1_000,
++ // Lines carry no date to sort by: keep KartaView's order.
++ keepOrder: true,
+ });
+ export const TOO_HIGH_HINT = msg('zoom in to see KartaView coverage');
+ export const NO_COVERAGE_HINT = msg('no KartaView photos in view');
+ export const RATE_LIMITED_MESSAGE = msg(
+ 'KartaView is rate-limiting requests — they resume on their own',
+ );
+
+ /**
+ * The photo API answers 429 to more than about three requests at once, so
+ * at most two are in flight; a 429 is retried after a short wait.
+ */
+ export const PHOTO_API_CONCURRENCY = 2;
+ export const PHOTO_API_RETRIES = 3;
+ export const PHOTO_API_RETRY_BASE_MS = 800;
+ /** A Retry-After longer than this is not waited out. */
+ export const PHOTO_API_RETRY_MAX_MS = 10_000;
+ /** The API is HTTP/1.1 (six connections): tiles 3, lookups 2, pages 1. */
+ export const TILE_CONCURRENCY = 3;
+ export const PAGE_CONCURRENCY = 1;
+ export const TILE_TIMEOUT_MS = 20_000;
+ export const PHOTO_API_TIMEOUT_MS = 15_000;
+ /**
+ * The first try of a lookup: KartaView sometimes sits on a lookup for 11 s
+ * and more, then answers the same one again in 3 s.
+ */
+ export const PHOTO_API_FIRST_TIMEOUT_MS = 8_000;
+ /** A sequence page is about 650 kB of JSON. */
+ export const PAGE_TIMEOUT_MS = 30_000;
+ /** Real tiles are under 1 MB; refuse anything absurd before parsing it. */
+ export const MAX_RESPONSE_BYTES = 16 * 1024 * 1024;
+ /** A photo download (tens of kilobytes to a few megabytes). */
+ export const IMAGE_TIMEOUT_MS = 15_000;
+ /** Whether a photo file is there (not archived): headers only. */
+ export const IMAGE_PROBE_TIMEOUT_MS = 8_000;
+ /** Nearest photos probed (at once) before giving up on archived ones; ‹ › skip this many. */
+ export const NEAREST_PROBES = 6;
+ export const ARCHIVED_MESSAGE = msg(
+ 'KartaView’s photos here are archived and cannot be shown',
+ );
+
+ /** Photos asked for around a point; the API returns them nearest first. */
+ export const NEAREST_LIMIT = 10;
+ /** The photo API's search zoom: 18 searches the few tens of metres around the point. */
+ export const NEAREST_SEARCH_ZOOM = 18;
+
+ /**
+ * Photos of a sequence fetched at once, around the open one. Records are
+ * ~2.6 kB each, so a page is ~650 kB; the cones and ‹ › use it. Pages are in
+ * photo-id order, which only roughly follows the sequence index.
+ */
+ export const SEQUENCE_PAGE_SIZE = 250;
+ /** Within this many photos of a page's edge, its neighbour page joins it. */
+ export const SEQUENCE_PAGE_EDGE = 12;
+
+ /** Equirectangular panorama sizes: a quick preview, then the sharp one. */
+ export const PANO_PREVIEW_SIZE = Object.freeze([1024, 512]);
+ /** A flat photo's first version, then its sharp one. */
+ export const FLAT_VIEW_SIZE = Object.freeze([1280, 1280]);
+ export const FLAT_FULL_SIZE = Object.freeze([2560, 2560]);
+
+ /** On-globe credit: KartaView imagery is CC BY-SA 4.0 and needs attribution. */
+ export const KARTAVIEW_CREDIT_HTML =
+ 'Street Level: imagery © <a href="https://kartaview.org" target="_blank" rel="noopener">KartaView</a> contributors, CC BY-SA 4.0';
+
+ /**
+ * The imagery filter (360° or flat, SINCE). KartaView filters coverage on
+ * its server only in its PNG tiles: its JSON tiles come back empty once a
+ * filter is asked for. So a filtered PNG tile is a mask, and a JSON line is
+ * kept where it lies on the mask's drawn pixels.
+ *
+ * KartaView's date filter is the upload date, and SINCE goes by it
+ * throughout (lines, the photo a click opens, the cones), as KartaView's own
+ * map does; the panel says so under the slider.
+ */
+ export const MASK_TIMEOUT_MS = 20_000;
+ /**
+ * A filtered PNG tile is drawn on demand and a dense one can outlast
+ * KartaView's own 60 s (504); it keeps drawing, and has the tile a few
+ * seconds later. A timeout or a 5xx is asked again this many times in all.
+ */
+ export const MASK_ATTEMPTS = 4;
+ export const MASK_RETRY_WAIT_MS = 4_000;
+ /** Real masks are tens of kilobytes. */
+ export const MASK_MAX_BYTES = 2 * 1024 * 1024;
+ /** A segment is kept when this share of the points along it lies on the mask. */
+ export const MASK_KEEP_SHARE = 0.5;
+ /** Points along a segment are tested this many mask pixels apart. */
+ export const MASK_SAMPLE_PX = 2;
+ export const MASK_SLOW_MESSAGE = msg(
+ 'KartaView did not filter this area in time — move the map to ask again',
+ );
+ export const FILTERED_OUT_MESSAGE = msg(
+ 'None of KartaView’s photos here pass the imagery filter',
+ );
+ /** Under the SINCE slider while KartaView is lit. */
+ export const SINCE_NOTE = 'KartaView: by upload date';
+
+ /** The UTC calendar day of `ms`, as KartaView's startDate reads it. */
+ function utcDay(ms) {
+ return new Date(ms).toISOString().slice(0, 10);
+ }
+
+ const filtersSince = (filter) =>
+ Number.isFinite(filter?.sinceMs) && filter.sinceMs > 0;
+
+ const DAY_MS = 86_400_000;
+
+ /**
+ * Whether a photo passes the resolved imagery filter by its projection and
+ * upload date, the cut-off taken as its UTC day, as KartaView's startDate.
+ * @param {{isPano: boolean, uploadedAt: number|null}} photo
+ * @param {{pano: string, sinceMs: number|null}|null} filter
+ */
+ export function passesKartaViewFilter(photo, filter) {
+ if (!filter) return true;
+ if (filter.pano === 'pano' && !photo.isPano) return false;
+ if (filter.pano === 'flat' && photo.isPano) return false;
+ if (!filtersSince(filter)) return true;
+ const day = Math.floor(filter.sinceMs / DAY_MS) * DAY_MS;
+ return (photo.uploadedAt ?? 0) >= day;
+ }
+
+ /**
+ * The query of a filtered PNG coverage tile, or '' when nothing is
+ * filtered. The day, not the instant, so it is stable for a day (and keys
+ * the mask cache).
+ * @param {{pano: string, sinceMs: number|null}|null} filter resolved
+ */
+ export function tileFilterQuery(filter) {
+ const params = new URLSearchParams();
+ if (filter?.pano === 'pano') params.set('fieldOfView', '360');
+ else if (filter?.pano === 'flat') params.set('fieldOfView', 'plane');
+ if (filtersSince(filter)) params.set('startDate', utcDay(filter.sinceMs));
+ return params.toString();
+ }
+
+ /**
+ * The photo search's own filter: projection and upload date (its
+ * `fieldOfView` is ignored).
+ * @param {{pano: string, sinceMs: number|null}|null} filter resolved
+ * @returns {Record<string, string>}
+ */
+ export function photoFilterParams(filter) {
+ const params = {};
+ if (filter?.pano === 'pano') params.projection = 'SPHERE';
+ else if (filter?.pano === 'flat') params.projection = 'PLANE';
+ if (filtersSince(filter)) params.startDate = utcDay(filter.sinceMs);
+ return params;
+ }
+
+ /** The cone and coverage noun: a line is a street with photos, not a sequence. */
+ export const COVERAGE_NOUN = 'streets';
+ export const LINE_CLICK_HINT = 'click a line for its nearest photo';
+
+ /** Base64url of a string, as the image proxy reads addresses. */
+ function base64Url(text) {
+ const bytes = new TextEncoder().encode(text);
+ let binary = '';
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ return btoa(binary)
+ .replace(/\+/g, '-')
+ .replace(/\//g, '_')
+ .replace(/=+$/, '');
+ }
+
+ /** A photo resized by KartaView's image proxy to fit `width`×`height`. */
+ export function resizedImageUrl(url, [width, height]) {
+ if (!url) return null;
+ return `${KARTAVIEW_CDN_HOST}/pr:sharp/rs:fit:${width}:${height}/${base64Url(url)}`;
+ }
+
+ /** Epoch ms for a KartaView timestamp ('2016-02-19 15:28:18.000', UTC), or null. */
+ export function kartaViewTimeMs(value) {
+ const match =
+ /^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?/.exec(
+ String(value ?? ''),
+ );
+ if (!match) return null;
+ const [, y, mo, d, h = '0', mi = '0', s = '0'] = match;
+ if (Number(y) < 1990) return null;
+ const ms = Date.UTC(+y, +mo - 1, +d, +h, +mi, +s);
+ return Number.isFinite(ms) ? ms : null;
+ }
+
+ /** Initial great-circle bearing from `a` to `b`, degrees clockwise from north. */
+ export function bearingBetween(a, b) {
+ const rad = Math.PI / 180;
+ const dLon = (b.lon - a.lon) * rad;
+ const y = Math.sin(dLon) * Math.cos(b.lat * rad);
+ const x =
+ Math.cos(a.lat * rad) * Math.sin(b.lat * rad) -
+ Math.sin(a.lat * rad) * Math.cos(b.lat * rad) * Math.cos(dLon);
+ return (Math.atan2(y, x) / rad + 360) % 360;
+ }
+
+ /** Photos closer than this say nothing about the direction of travel. */
+ const COURSE_MIN_STEP_M = 2;
+ /** How many photos along to look for one far enough away. */
+ const COURSE_SEARCH = 5;
+
+ /**
+ * Give each photo of a drive (in index order) its `course`: the direction
+ * of travel from it to the next photo a few metres on (from the previous one
+ * at the end). KartaView is dashcam imagery, so this is where the camera
+ * looks; its `heading` is the device compass, which reads 0 without one and
+ * can sit 110° off inside a car.
+ * @param {Array<{lon: number, lat: number, course?: number|null}>} photos
+ * @param {(a: object, b: object) => number} metres
+ */
+ export function assignCourses(photos, metres) {
+ photos.forEach((photo, i) => {
+ let course = null;
+ for (let j = i + 1; j <= i + COURSE_SEARCH && j < photos.length; j++)
+ if (metres(photo, photos[j]) >= COURSE_MIN_STEP_M) {
+ course = bearingBetween(photo, photos[j]);
+ break;
+ }
+ for (
+ let k = i - 1;
+ course === null && k >= i - COURSE_SEARCH && k >= 0;
+ k--
+ )
+ if (metres(photos[k], photo) >= COURSE_MIN_STEP_M)
+ course = bearingBetween(photos[k], photo);
+ photo.course = course;
+ });
+ return photos;
+ }
+
+ /** Where the camera looked: the direction of travel, else the compass, else unknown. */
+ export function cameraBearing(photo) {
+ return photo?.course ?? photo?.heading ?? null;
+ }
+
+ /** A coordinate pair as numbers; the road-matched one when KartaView has it. */
+ function positionOf(record) {
+ const matchLat = Number(record.matchLat);
+ const matchLon = Number(record.matchLng);
+ if (
+ Number.isFinite(matchLat) &&
+ Number.isFinite(matchLon) &&
+ (matchLat !== 0 || matchLon !== 0)
+ )
+ return { lat: matchLat, lon: matchLon };
+ return { lat: Number(record.lat), lon: Number(record.lng) };
+ }
+
+ const STORAGE_HOST = /^storage\d+$/;
+
+ /** A KartaView photo-storage address, or null for anything else. */
+ function storageUrl(value) {
+ try {
+ const url = new URL(String(value));
+ return url.protocol === 'https:' &&
+ /^storage\d+\.openstreetcam\.org$/.test(url.hostname)
+ ? url.href
+ : null;
+ } catch {
+ return null;
+ }
+ }
+
+ /**
+ * A photo file's address. The API's `fileurl*` fields always name storage1,
+ * but a photo whose `storage` is another host (storage2…) is only there, so
+ * the address is built from `storage` and the relative `filepath*`. A
+ * `fileurl*` fallback must itself be on KartaView's storage.
+ */
+ function fileUrl(record, pathKey, urlKey) {
+ const path = record[pathKey];
+ if (STORAGE_HOST.test(record.storage || '') && path)
+ return storageUrl(
+ `https://${record.storage}.openstreetcam.org/files/photo/${path}`,
+ );
+ return storageUrl(record[urlKey]);
+ }
+
+ /** A storage URL with its `{{sizeprefix}}` placeholder filled. */
+ function sized(record, prefix) {
+ const fill = (value) =>
+ typeof value === 'string' && value.includes('{{sizeprefix}}')
+ ? value.replace('{{sizeprefix}}', prefix)
+ : null;
+ const path = fill(record.filepath);
+ return fileUrl(
+ { ...record, filepath: path, fileurl: fill(record.fileurl) },
+ 'filepath',
+ 'fileurl',
+ );
+ }
+
+ /**
+ * A photo API record in the shape the provider uses, or null without an id
+ * or a position.
+ * @returns {{id: string, sequenceId: string|null, sequenceIndex: number|null, lon: number, lat: number, heading: number|null, isPano: boolean, capturedAt: number|null, urls: {view: string|null, full: string|null, pano: string|null}}|null}
+ */
+ export function normalizePhoto(record) {
+ if (!record || record.id == null) return null;
+ const { lat, lon } = positionOf(record);
+ if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null;
+ // 0,0 is a missing fix, not a photo in the Gulf of Guinea.
+ if (lat === 0 && lon === 0) return null;
+ if (Math.abs(lat) > 90 || Math.abs(lon) > 180) return null;
+ // An exact 0 is a device without a compass (whole drives read 0), not north.
+ const heading =
+ record.heading === '' || record.heading == null
+ ? NaN
+ : Number(record.heading) || NaN;
+ const isPano =
+ record.projection === 'SPHERE' || Number(record.fieldOfView) >= 360;
+ const full =
+ fileUrl(record, 'filepathProc', 'fileurlProc') || sized(record, 'proc');
+ const index = Number(record.sequenceIndex);
+ return {
+ id: String(record.id),
+ sequenceId: record.sequenceId != null ? String(record.sequenceId) : null,
+ sequenceIndex: Number.isFinite(index) ? index : null,
+ lon,
+ lat,
+ heading: Number.isFinite(heading) ? heading : null,
+ isPano,
+ capturedAt:
+ kartaViewTimeMs(record.shotDate) ?? kartaViewTimeMs(record.dateAdded),
+ // KartaView's SINCE goes by this (its server filters by upload date).
+ uploadedAt: kartaViewTimeMs(record.dateAdded),
+ urls: {
+ // A 1280 px rendition; for a 360° photo it is the front view only.
+ view:
+ fileUrl(record, 'filepathLTh', 'fileurlLTh') ||
+ sized(record, 'lth') ||
+ full,
+ full,
+ // A 360° photo's equirectangular image ('wrapped_proc').
+ pano: isPano && /wrapped/.test(full || '') ? full : null,
+ },
+ };
+ }
+
+ /**
+ * Where the image link goes. KartaView's photo pages fail for signed-out
+ * visitors ("Sequence cannot be loaded"), so it is the full-size photo
+ * through KartaView's image proxy, which also serves photos whose storage
+ * host answers 502 directly.
+ */
+ export function kartaViewPhotoUrl(photo) {
+ const url = photo?.urls?.full || photo?.urls?.view;
+ return url
+ ? `${KARTAVIEW_CDN_HOST}/pr:sharp/${base64Url(url)}`
+ : 'https://kartaview.org';
+ }
diff --cc src/layers/streetLevel/providers/kartaview/provider.test.mjs
index 000000000,a043063fa..d992313bb
mode 000000,100644..100644
--- a/src/layers/streetLevel/providers/kartaview/provider.test.mjs
+++ b/src/layers/streetLevel/providers/kartaview/provider.test.mjs
@@@ -1,0 -1,1129 +1,1124 @@@
+ import assert from 'node:assert/strict';
+ import test from 'node:test';
+ import {
+ createKartaViewProvider,
+ createTileCache,
+ kartaViewZoomFor,
+ } from './index.js';
+ import {
++ COVERAGE_TUNING,
+ FILTERED_OUT_MESSAGE,
+ NO_COVERAGE_HINT,
+ SEQUENCE_PAGE_SIZE,
+ TOO_HIGH_HINT,
+ } from './policy.js';
+ import { validateProviders } from '../../registry.js';
+ import { fakeHost, until } from '../../../../testSupport/kartaViewFakes.mjs';
+ import {
+ coverageViewer,
+ tileCentre,
+ } from '../../../../testSupport/streetLevelFakes.mjs';
+
+ /** A photo record `metres` east of (42.3314, -83.0458), in sequence `seq` at `index`. */
+ function photoRecord(id, { metres = 0, seq = '14010', index = 0 } = {}) {
+ const lon = -83.0458 + metres / 82_300;
+ return {
+ id: String(id),
+ sequenceId: seq,
+ sequenceIndex: String(index),
+ lat: '42.3314',
+ lng: String(lon),
+ heading: '90',
+ projection: 'PLANE',
+ fieldOfView: '0',
+ shotDate: '2016-08-23 20:17:47.000',
+ storage: 'storage2',
+ filepathLTh: `2016/8/24/lth/${id}.jpg`,
+ filepathProc: `2016/8/24/proc/${id}.jpg`,
+ };
+ }
+
+ /** KartaView's shotDate for `ms` ago. */
+ const shotAgo = (ms) =>
+ new Date(Date.now() - ms).toISOString().replace('T', ' ').slice(0, 23);
+
+ /**
+ * A source over `sequences` (id → indexes present, in page order: KartaView
+ * pages follow photo ids, which only roughly follow the index), recording
+ * calls. Photos whose id is in `archived` answer 409.
+ */
+ function fakeSource({ nearest = [], sequences = {}, archived = [] } = {}) {
+ const calls = {
+ nearest: 0,
+ nearestFilters: [],
+ photo: [],
+ pages: [],
+ probes: [],
+ };
+ return {
+ calls,
+ probeImage: async (url) => {
+ calls.probes.push(url);
+ return !archived.some((id) => url.includes(`/${id}.jpg`));
+ },
+ getTile: async () => ({ lines: [] }),
+ nearestPhotos: async ({ filter }) => {
+ calls.nearest++;
+ calls.nearestFilters.push(filter);
+ return nearest;
+ },
+ getPhoto: async (id) => {
+ calls.photo.push(id);
+ for (const [seq, indexes] of Object.entries(sequences))
+ for (const index of indexes)
+ if (`${seq}-${index}` === id)
+ return photoRecord(id, { seq, index, metres: index * 5 });
+ throw new Error('KartaView has no such photo');
+ },
+ getSequencePhotos: async (seq, { page, itemsPerPage }) => {
+ calls.pages.push(`${seq}:${page}`);
+ const indexes = sequences[seq] || [];
+ const rows = indexes.slice(
+ (page - 1) * itemsPerPage,
+ page * itemsPerPage,
+ );
+ return {
+ photos: rows.map((index) =>
+ photoRecord(`${seq}-${index}`, { seq, index, metres: index * 5 }),
+ ),
+ hasMore: page * itemsPerPage < indexes.length,
+ };
+ },
+ };
+ }
+
+ function fakeContext({ filter = { pano: 'all', sinceMs: null } } = {}) {
+ // `actions.filter` is the resolved filter now; a test may change it.
+ const actions = { opened: [], nearest: [], instance: null, filter };
+ return {
+ actions,
+ context: {
+ services: {},
+ getFilter: () => actions.filter,
+ isActive: () => true,
- groundCaster: null,
- meshSampler: null,
- getSurface: () => 'draped',
+ notify() {},
+ actions: {
+ // As the core does: the provider's own viewer opens it.
+ openImage: async (id, options) => {
+ actions.opened.push({ id, options });
+ await actions.instance?.viewer.open(id);
+ return true;
+ },
+ openNearest: (point) => actions.nearest.push(point),
+ reportError() {},
+ },
+ },
+ };
+ }
+
+ function setup(sourceOptions, contextOptions, { readMask } = {}) {
+ const source = fakeSource(sourceOptions);
+ const loads = [];
+ const definition = createKartaViewProvider({
+ source,
+ readMask,
+ viewerOptions: {
+ load: async (url) => {
+ loads.push(url);
+ return { src: url };
+ },
+ createRenderer: () => {
+ throw new Error('no WebGL in Node');
+ },
+ },
+ });
+ const { context, actions } = fakeContext(contextOptions);
+ const instance = definition.create(context);
+ actions.instance = instance;
+ return { definition, instance, source, actions, loads };
+ }
+
+ const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+ test('KartaView registers keyless, off by default, with Mapillary’s filters and its own wording', () => {
+ const { definition } = setup();
+ assert.equal(definition.id, 'kartaview');
+ assert.equal(definition.requiresKeyId, null);
+ assert.equal(definition.defaultOn, false);
+ assert.deepEqual(definition.filters, ['pano', 'since']);
+ assert.equal(
+ definition.sinceBasis,
+ 'upload',
+ 'SINCE is KartaView’s upload date',
+ );
- assert.equal(
- definition.highlightsSequence,
- false,
- 'its lines are streets: a selected drive shows as cones',
- );
+ assert.match(
+ definition.credit.html,
+ /KartaView<\/a> contributors, CC BY-SA 4\.0/,
+ );
+ assert.equal(definition.colors.coverage, '#635bff');
+ assert.deepEqual(definition.coverageLabel, {
+ noun: 'streets',
+ action: 'click a line for its nearest photo',
+ });
+ // Its prefix fits beside the others.
+ validateProviders([
+ { ...definition, id: 'mapillary', pickPrefix: 'mly:' },
+ { ...definition, id: 'google', pickPrefix: 'gsv:' },
+ definition,
+ ]);
+ });
+
+ test('coverage is drawn from z14 near the street and z13 a little higher; never from orbit', () => {
- assert.deepEqual(kartaViewZoomFor(300), { zoom: 14, kind: 'sequence' });
- assert.deepEqual(kartaViewZoomFor(2_500), { zoom: 14, kind: 'sequence' });
- assert.deepEqual(kartaViewZoomFor(4_000), { zoom: 13, kind: 'sequence' });
- assert.deepEqual(
- kartaViewZoomFor(6_000),
- { zoom: 13, kind: 'sequence' },
- 'the top of the range still draws',
- );
++ assert.equal(kartaViewZoomFor(300), 14);
++ assert.equal(kartaViewZoomFor(2_500), 14);
++ assert.equal(kartaViewZoomFor(4_000), 13);
++ assert.equal(kartaViewZoomFor(6_000), 13, 'the top of the range still draws');
+ assert.equal(kartaViewZoomFor(6_001), null);
+ assert.equal(kartaViewZoomFor(NaN), null);
+ });
+
+ test('the nearest photo is the closest within 50 m, and opening it asks nothing more', async () => {
+ const { instance, source, loads } = setup({
+ nearest: [
+ photoRecord('far', { metres: 80 }),
+ photoRecord('mid', { metres: 30 }),
+ photoRecord('near', { metres: 12 }),
+ ],
+ });
+ const id = await instance.nearestImage({ lat: 42.3314, lon: -83.0458 });
+ assert.equal(id, 'near');
+ const host = fakeHost();
+ await instance.viewer.mount(host);
+ await instance.viewer.open(id);
+ assert.deepEqual(source.calls.photo, [], 'the lookup filled the cache');
+ assert.equal(
+ Buffer.from(loads[0].split('/').at(-1), 'base64url').toString(),
+ 'https://storage2.openstreetcam.org/files/photo/2016/8/24/proc/near.jpg',
+ 'the proxy shrinks the photo on its real storage host',
+ );
+ const none = setup({ nearest: [photoRecord('far', { metres: 80 })] });
+ assert.equal(
+ await none.instance.nearestImage({ lat: 42.3314, lon: -83.0458 }),
+ null,
+ );
+ });
+
+ test('the nearest photo passes the imagery filter by its upload date, as KartaView filters; none passing says so', async () => {
+ const since = Date.now() - 86_400_000;
+ const filter = { pano: 'pano', sinceMs: since };
+ const pano = (id, metres, uploaded) => ({
+ ...photoRecord(id, { metres }),
+ projection: 'SPHERE',
+ fieldOfView: '360',
+ shotDate: '2016-08-23 20:17:47.000',
+ dateAdded: uploaded,
+ });
+ // Both taken in 2016; only the second was uploaded since yesterday.
+ const { instance, source } = setup(
+ {
+ nearest: [
+ pano('stale', 5, '2016-08-24 04:01:07'),
+ pano('fresh', 20, shotAgo(3_600_000).slice(0, 19)),
+ ],
+ },
+ { filter },
+ );
+ const at = { lat: 42.3314, lon: -83.0458 };
+ assert.equal(await instance.nearestImage(at), 'fresh');
+ assert.deepEqual(source.calls.nearestFilters, [filter]);
+ const stale = setup(
+ { nearest: [pano('stale', 5, '2016-08-24 04:01:07')] },
+ { filter },
+ );
+ await assert.rejects(stale.instance.nearestImage(at), {
+ message: FILTERED_OUT_MESSAGE,
+ });
+ // Uploaded earlier on the cut-off's UTC day: KartaView's startDate keeps
+ // it, and so does the check.
+ const day = new Date(since).toISOString().slice(0, 10);
+ const sameDay = setup(
+ { nearest: [pano('early', 5, `${day} 00:00:01`)] },
+ { filter },
+ );
+ assert.equal(await sameDay.instance.nearestImage(at), 'early');
+ });
+
+ test('a cone opens its photo; a line opens the photo nearest the click', () => {
+ const { instance, actions } = setup();
+ actions.instance = null;
+ assert.equal(instance.handlePick('kv:img:123'), true);
+ assert.deepEqual(actions.opened, [{ id: '123', options: undefined }]);
+ const point = { lon: -83.0458, lat: 42.3314 };
+ assert.equal(
+ instance.handlePick('kv:line:14/1/2/3', { groundPoint: () => point }),
+ true,
+ );
+ assert.deepEqual(actions.nearest, [point]);
+ // Over the sky the line is still ours, but there is nowhere to look.
+ assert.equal(
+ instance.handlePick('kv:line:14/1/2/3', { groundPoint: () => null }),
+ true,
+ );
+ assert.equal(actions.nearest.length, 1);
+ assert.equal(instance.handlePick('mly:seq:1'), false);
+ });
+
+ test('coverage stats report KartaView as configured and key-free', async () => {
+ const { instance } = setup();
+ assert.deepEqual(await instance.status(), { configured: true });
+ const stats = instance.coverageStats();
+ assert.equal(stats.keyRequired, false);
+ assert.equal(stats.keyRejected, false);
+ assert.equal(stats.count, 0);
+ });
+
+ /** Press a step button and wait until it has opened a photo (`opened` grew). */
+ const press = async (button, opened) => {
+ const before = opened.length;
+ button.fire('click');
+ await until(() => opened.length > before);
+ await settle();
+ };
+
+ async function mounted(sourceOptions, contextOptions) {
+ const env = setup(sourceOptions, contextOptions);
+ const host = fakeHost();
+ await env.instance.viewer.mount(host);
+ const poses = [];
+ env.instance.viewer.onPose((pose) => poses.push(pose.imageId));
+ const [, , prev, next] = host.children[0].children;
+ return { ...env, poses, prev, next };
+ }
+
+ test('› walks across sequence pages without moving the camera; ‹ walks back; the ends stop', async () => {
+ const size = SEQUENCE_PAGE_SIZE;
+ const indexes = Array.from({ length: size + 5 }, (_, i) => i);
+ const { instance, actions, source, poses, prev, next } = await mounted({
+ sequences: { s: indexes },
+ });
+ await instance.viewer.open(`s-${size - 1}`);
+ await press(next, poses);
+ assert.equal(poses.at(-1), `s-${size}`, 'onto the second page');
+ assert.deepEqual(actions.opened.at(-1), {
+ id: `s-${size}`,
+ options: { frame: false },
+ });
+ assert.ok(source.calls.pages.includes('s:2'));
+ await press(prev, poses);
+ assert.equal(poses.at(-1), `s-${size - 1}`);
+ await instance.viewer.open('s-0');
+ assert.ok(await until(() => prev.disabled), 'nothing before the first photo');
+ // ‹ at the start opens nothing: presses run in turn, so once a later ›
+ // has opened its photo, a ‹ that opened one would show before it.
+ const before = actions.opened.length;
+ prev.fire('click');
+ await press(next, poses);
+ assert.deepEqual(
+ actions.opened.slice(before).map((open) => open.id),
+ ['s-1'],
+ );
+ });
+
+ test('pages that overlap in index (id order) step one photo at a time across the edge', async () => {
+ const size = SEQUENCE_PAGE_SIZE;
+ // As KartaView pages by id: page 1 holds 0…size+2 less two, page 2 starts
+ // with those two (size-2, size) before the rest.
+ const first = Array.from({ length: size + 3 }, (_, i) => i).filter(
+ (i) => i !== size - 2 && i !== size,
+ );
+ const second = [
+ size - 2,
+ size,
+ ...Array.from({ length: 50 }, (_, i) => size + 3 + i),
+ ];
+ const { instance, poses, next } = await mounted({
+ sequences: { s: [...first, ...second] },
+ });
+ await instance.viewer.open(`s-${size - 5}`);
+ for (let k = 1; k <= 8; k++) await press(next, poses);
+ assert.deepEqual(
+ poses.slice(-9).map((id) => Number(id.slice(2))),
+ Array.from({ length: 9 }, (_, i) => size - 5 + i),
+ 'no photo skipped at the page edge',
+ );
+ });
+
+ test('a photo whose index outruns the page count is found, and its neighbours are real', async () => {
+ // 1,000 photos with 500–1499 deleted: index 1500 is on page 2, not 4.
+ const indexes = [
+ ...Array.from({ length: 500 }, (_, i) => i),
+ ...Array.from({ length: 500 }, (_, i) => 1500 + i),
+ ];
+ const { instance, poses, prev, next } = await mounted({
+ sequences: { s: indexes },
+ });
+ await instance.viewer.open('s-1500');
+ await press(next, poses);
+ assert.equal(poses.at(-1), 's-1501');
+ await press(prev, poses);
+ await press(prev, poses);
+ assert.equal(poses.at(-1), 's-499', 'back across the gap');
+ await instance.viewer.open('s-1999');
+ assert.ok(await until(() => next.disabled), 'the last photo');
+ });
+
+ test('archived photos are skipped: by the nearest lookup, and by › and ‹', async () => {
+ const { instance, poses, next } = await mounted({
+ nearest: [
+ photoRecord('gone', { metres: 3 }),
+ photoRecord('kept', { metres: 9 }),
+ ],
+ archived: ['gone', 's-2', 's-3'],
+ sequences: { s: [0, 1, 2, 3, 4] },
+ });
+ assert.equal(
+ await instance.nearestImage({ lat: 42.3314, lon: -83.0458 }),
+ 'kept',
+ );
+ await instance.viewer.open('s-1');
+ await press(next, poses);
+ assert.equal(poses.at(-1), 's-4', 'two archived photos stepped over');
+ const allGone = setup({
+ nearest: [photoRecord('gone', { metres: 3 })],
+ archived: ['gone'],
+ });
+ await assert.rejects(
+ allGone.instance.nearestImage({ lat: 42.3314, lon: -83.0458 }),
+ /archived and cannot be shown/,
+ );
+ const noFiles = setup({
+ nearest: [
+ {
+ ...photoRecord('bare', { metres: 2 }),
+ filepathLTh: '',
+ filepathProc: '',
+ },
+ ],
+ });
+ assert.equal(
+ await noFiles.instance.nearestImage({ lat: 42.3314, lon: -83.0458 }),
+ null,
+ 'a record with no file is not a photo',
+ );
+ });
+
+ /** A stand-in Cesium viewer the cones can draw on; `cones()` lists their photo indexes. */
+ async function withCones(t, env) {
+ const Cesium = await import('cesium');
+ const drawing = new Proxy({}, { get: () => () => {}, set: () => true });
+ const saved = globalThis.document;
+ globalThis.document = {
+ createElement: () => ({ getContext: () => drawing }),
+ };
+ t.after(() => (globalThis.document = saved));
+ let collection = null;
+ env.instance.init({
+ scene: {
+ frameState: { mode: Cesium.SceneMode.SCENE3D },
+ updateHeight: () => () => {},
+ getHeight: () => undefined,
+ primitives: { add: (c) => (collection = c), remove() {} },
+ preRender: { addEventListener: () => () => {} },
+ },
+ camera: { positionWC: new Cesium.Cartesian3(0, 0, 1e8) },
+ });
+ const cones = () => {
+ const indexes = [];
+ for (let i = 0; i < collection.length; i++)
+ indexes.push(Number(collection.get(i).id.split('-').at(-1)));
+ return [Math.min(...indexes), Math.max(...indexes)];
+ };
+ cones.count = () => collection?.length ?? 0;
+ return cones;
+ }
+
+ test('the cones follow the open photo to another page of a long sequence, cached or not', async (t) => {
+ const size = SEQUENCE_PAGE_SIZE;
+ const env = await mounted({
+ sequences: { s: Array.from({ length: size * 5 }, (_, i) => i) },
+ });
+ const cones = await withCones(t, env);
+ const drawnAround = (index) =>
+ until(
+ () =>
+ !env.instance.sequenceStats().loading &&
+ cones.count() > 0 &&
+ cones()[0] <= index &&
+ cones()[1] >= index,
+ );
+ await env.instance.viewer.open('s-10');
+ await env.instance.selectSequence('s');
+ assert.ok(await drawnAround(10));
+ assert.ok(cones()[1] < size, `first page: ${cones()}`);
+ // A line click further along the same drive: the core does not reselect.
+ await env.instance.viewer.open(`s-${size * 4 + 10}`);
+ assert.ok(await drawnAround(size * 4 + 10), `re-centred: ${cones()}`);
+ assert.ok(cones()[0] >= size * 3, `re-centred: ${cones()}`);
+ // Closed and reopened on another page: not the sequence's cached cones.
+ env.instance.clearSequence();
+ await env.instance.viewer.open(`s-${size * 2 + 10}`);
+ await env.instance.selectSequence('s');
+ assert.ok(await drawnAround(size * 2 + 10), `around the photo: ${cones()}`);
+ });
+
+ test('a storage hiccup is not remembered as an archived photo', async () => {
+ const env = setup({ nearest: [photoRecord('near', { metres: 3 })] });
+ let answer = null;
+ env.source.probeImage = async () => answer;
+ // No answer: the photo is tried rather than called archived.
+ assert.equal(
+ await env.instance.nearestImage({ lat: 42.3314, lon: -83.0458 }),
+ 'near',
+ );
+ answer = false;
+ await assert.rejects(
+ env.instance.nearestImage({ lat: 42.3314, lon: -83.0458 }),
+ /archived/,
+ 'asked again, and now it is gone',
+ );
+ });
+
+ test('a photo far past a run of deleted photos still finds its page and neighbours', async () => {
+ const indexes = [
+ ...Array.from({ length: 1000 }, (_, i) => i),
+ ...Array.from({ length: 20 }, (_, i) => 6000 + i),
+ ];
+ const { instance, poses, next, prev, source } = await mounted({
+ sequences: { s: indexes },
+ });
+ await instance.viewer.open('s-6005');
+ // Both ends checks have found a neighbour (and probed it) before the look.
+ const probed = (id) =>
+ source.calls.probes.some((url) => url.endsWith(`/${id}.jpg`));
+ assert.ok(await until(() => probed('s-6004') && probed('s-6006')));
+ await settle();
+ assert.equal(next.disabled, false);
+ assert.equal(prev.disabled, false);
+ await press(next, poses);
+ assert.equal(poses.at(-1), 's-6006');
+ });
+
+ test('coverage tiles are kept for a while: panning back asks KartaView nothing', async () => {
+ let now = 0;
+ const asked = [];
+ const tiles = createTileCache({
+ load: async (tile) => {
+ asked.push(`${tile.z}/${tile.x}/${tile.y}`);
- return { sequences: [], overview: [] };
++ return { sequences: [] };
+ },
+ size: 2,
+ ttlMs: 1000,
+ now: () => now,
+ });
+ const a = { x: 1, y: 2, z: 14 };
+ const b = { x: 2, y: 2, z: 14 };
+ const c = { x: 3, y: 2, z: 14 };
+ const first = await tiles.get(a, {});
+ assert.equal(await tiles.get(a, {}), first, 'the same decoded tile');
+ await tiles.get(b, {});
+ await tiles.get(c, {});
+ await tiles.get(a, {});
+ assert.deepEqual(
+ asked,
+ ['14/1/2', '14/2/2', '14/3/2', '14/1/2'],
+ 'oldest dropped',
+ );
+ now = 2000;
+ await tiles.get(a, {});
+ assert.equal(asked.length, 5, 'stale after the TTL');
+ // The same x/y at another zoom is another tile.
+ await tiles.get({ ...a, z: 13 }, {});
+ assert.deepEqual(asked.at(-1), '13/1/2');
+ assert.equal(asked.length, 6);
+ // A failed load is not kept.
+ const failing = createTileCache({
+ load: async () => {
+ throw new Error('KartaView did not answer in time — try again');
+ },
+ size: 2,
+ ttlMs: 1000,
+ });
+ await assert.rejects(failing.get(a, {}), /did not answer/);
+ });
+
+ test('a page in id order, its indexes out of order, still steps in index order', async () => {
+ const { instance, poses, next, prev } = await mounted({
+ sequences: { s: [0, 2, 1, 3, 4] },
+ });
+ await instance.viewer.open('s-0');
+ await press(next, poses);
+ assert.equal(poses.at(-1), 's-1');
+ await press(next, poses);
+ assert.equal(poses.at(-1), 's-2');
+ await press(prev, poses);
+ assert.equal(poses.at(-1), 's-1');
+ });
+
+ test('a sequence page that failed once is asked again: › then reaches the next photo', async () => {
+ const env = await mounted({ sequences: { s: [0, 1, 2, 3] } });
+ const real = env.source.getSequencePhotos;
+ let fail = true;
+ env.source.getSequencePhotos = async (...args) => {
+ env.source.calls.pages.push('failing');
+ if (fail) throw new Error('KartaView did not answer in time — try again');
+ return real(...args);
+ };
+ await env.instance.viewer.open('s-1');
+ // The ends checks ask for the page and get no answer.
+ assert.ok(await until(() => env.source.calls.pages.includes('failing')));
+ await settle();
+ fail = false;
+ await press(env.next, env.poses);
+ assert.equal(env.poses.at(-1), 's-2');
+ });
+
+ test('a lookup overtaken while it probes shares the probe with the next one, which finds the photo', async () => {
+ const env = setup({ nearest: [photoRecord('kept', { metres: 9 })] });
+ let answer;
+ env.source.probeImage = (url) => {
+ env.source.calls.probes.push(url);
+ return new Promise((resolve) => (answer = resolve));
+ };
+ env.source.nearestPhotos = async (point, { signal } = {}) => {
+ signal?.throwIfAborted();
+ return [photoRecord('kept', { metres: 9 })];
+ };
+ const point = { lat: 42.3314, lon: -83.0458 };
+ const controller = new AbortController();
+ const first = env.instance.nearestImage(point, { signal: controller.signal });
+ assert.ok(await until(() => env.source.calls.probes.length === 1));
+ controller.abort(new Error('overtaken'));
+ const second = env.instance.nearestImage(point);
+ await settle();
+ answer(true);
+ assert.equal(await second, 'kept');
+ await first.catch(() => {});
+ assert.equal(env.source.calls.probes.length, 1, 'one probe, shared');
+ // A definite answer is kept: the next lookup asks storage nothing.
+ assert.equal(await env.instance.nearestImage(point), 'kept');
+ assert.equal(env.source.calls.probes.length, 1);
+ // A lookup aborted before KartaView answers gives up.
+ const late = new AbortController();
+ late.abort(new Error('closed'));
+ await assert.rejects(
+ env.instance.nearestImage(point, { signal: late.signal }),
+ /closed/,
+ );
+ });
+
+ test('a probe that fails outright is tried, and asked again next time', async () => {
+ const env = setup({ nearest: [photoRecord('near', { metres: 3 })] });
+ let probe = async () => {
+ throw new TypeError('Failed to fetch');
+ };
+ env.source.probeImage = (url) => probe(url);
+ const point = { lat: 42.3314, lon: -83.0458 };
+ assert.equal(await env.instance.nearestImage(point), 'near');
+ probe = async () => false;
+ await assert.rejects(env.instance.nearestImage(point), /archived/);
+ });
+
+ test('a photo past the last page asks for no page beyond it', async () => {
+ const env = await mounted({
+ sequences: { s: Array.from({ length: 10 }, (_, i) => i) },
+ });
+ // KartaView knows photo 12, but no page lists it (moved or re-indexed).
+ const getPhoto = env.source.getPhoto;
+ env.source.getPhoto = async (id) =>
+ id === 's-12'
+ ? photoRecord('s-12', { seq: 's', index: 12, metres: 60 })
+ : getPhoto(id);
+ await env.instance.viewer.open('s-12');
+ await press(env.prev, env.poses);
+ assert.equal(env.poses.at(-1), 's-9');
+ assert.deepEqual([...new Set(env.source.calls.pages)], ['s:1']);
+ });
+
+ test('the cones re-centre when ‹ › walk off the page they were drawn from', async (t) => {
+ const size = SEQUENCE_PAGE_SIZE;
+ const env = await mounted({
+ sequences: { s: Array.from({ length: size * 3 }, (_, i) => i) },
+ });
+ const cones = await withCones(t, env);
+ const settled = () =>
+ until(() => !env.instance.sequenceStats().loading && cones.count() > 0);
+ // Near the start of page 2: the cones show page 2 alone.
+ await env.instance.viewer.open(`s-${size + 12}`);
+ await env.instance.selectSequence('s');
+ assert.ok(await settled());
+ assert.deepEqual(cones(), [size, size * 2 - 1]);
+ // ‹ back across the edge onto page 1.
+ for (let k = 0; k < 13; k++) await press(env.prev, env.poses);
+ assert.equal(env.poses.at(-1), `s-${size - 1}`);
+ assert.ok(
+ await until(() => cones()[0] < size),
+ `drawn around page 1 now: ${cones()}`,
+ );
+ // › forward, off the far end of page 2.
+ await env.instance.viewer.open(`s-${size * 2 - 13}`);
+ assert.ok(await until(() => cones()[0] >= size), `${cones()}`);
+ for (let k = 0; k < 13; k++) await press(env.next, env.poses);
+ assert.equal(env.poses.at(-1), `s-${size * 2}`);
+ assert.ok(
+ await until(() => cones()[1] >= size * 2),
+ `drawn around page 3 now: ${cones()}`,
+ );
+ });
+
+ test('the imagery filter thins the cones by each photo’s upload date and projection', async (t) => {
+ const env = await mounted(
+ { sequences: { s: [0, 1, 2, 3] } },
+ { filter: { pano: 'pano', sinceMs: Date.now() - 86_400_000 } },
+ );
+ // 0 and 1: 360° photos uploaded an hour ago (taken in 2016, as all);
+ // 2 and 3: flat ones uploaded in 2016.
+ const shaped = (record) =>
+ Number(record.sequenceIndex) < 2
+ ? {
+ ...record,
+ projection: 'SPHERE',
+ fieldOfView: '360',
+ dateAdded: shotAgo(3_600_000).slice(0, 19),
+ }
+ : { ...record, dateAdded: '2016-08-24 04:01:07' };
+ const getPhoto = env.source.getPhoto;
+ env.source.getPhoto = async (id) => shaped(await getPhoto(id));
+ const getPage = env.source.getSequencePhotos;
+ env.source.getSequencePhotos = async (...args) => {
+ const page = await getPage(...args);
+ return { ...page, photos: page.photos.map(shaped) };
+ };
+ const cones = await withCones(t, env);
+ await env.instance.viewer.open('s-1');
+ await env.instance.selectSequence('s');
+ assert.ok(await until(() => !env.instance.sequenceStats().loading));
+ assert.equal(env.instance.sequenceStats().images, 4, 'the drive is whole');
+ assert.equal(cones.count(), 2, 'the 360° photos uploaded since yesterday');
+ assert.deepEqual(cones(), [0, 1]);
+ env.actions.filter = { pano: 'flat', sinceMs: null };
+ env.instance.setFilter();
+ assert.deepEqual(cones(), [2, 3], 'the flat ones');
+ env.actions.filter = { pano: 'all', sinceMs: null };
+ env.instance.setFilter();
+ assert.equal(cones.count(), 4, 'every cone, unfiltered');
+ });
+
+ /**
+ * The provider drawing coverage on a stand-in viewer above one z14 tile.
+ * `lines` are the tile's tracks as [lon, lat] pairs; `getTile` may be held.
+ */
+ function coverageSetup(
+ t,
+ { lines = [], filter, height = 900, drawnRows = () => [] } = {},
+ ) {
+ // A filtered tile's mask: 512 px square, drawn on the rows
+ // `drawnRows(query)` lists as [from, to].
+ const env = setup(
+ {},
+ { filter },
+ {
+ readMask: async ({ query }) => {
+ const alpha = new Uint8Array(512 * 512);
+ for (const [from, to] of drawnRows(query))
+ alpha.fill(255, from * 512, (to + 1) * 512);
+ return { width: 512, height: 512, alpha };
+ },
+ },
+ );
+ const masks = [];
+ let maskHold = null;
+ env.source.getTileMask = async (tile, query) => {
+ masks.push(query);
+ await maskHold;
+ return { query };
+ };
+ const centre = tileCentre(-83.0458, 42.3314);
+ const viewer = coverageViewer(
+ { lon: centre.lon, lat: centre.lat, height },
+ t,
+ );
+ const tiles = [];
+ let hold = null;
+ env.source.getTile = (tile) => {
+ tiles.push(`${tile.z}/${tile.x}/${tile.y}`);
+ const answer = {
+ lines: lines.map((track) => ({
+ track: track.map(([lon, lat]) => ({
+ lat: String(lat),
+ lng: String(lon),
+ })),
+ })),
+ };
+ return hold ? hold.then(() => answer) : Promise.resolve(answer);
+ };
+ env.instance.init(viewer);
+ t.after(() => env.instance.destroy(viewer));
+ return {
+ ...env,
+ viewer,
+ centre,
+ tiles,
+ masks,
+ holdMasks() {
+ let release;
+ maskHold = new Promise((resolve) => (release = resolve));
+ return () => {
+ maskHold = null;
+ release();
+ };
+ },
+ holdTiles() {
+ let release;
+ hold = new Promise((resolve) => (release = resolve));
+ return () => {
+ hold = null;
+ release();
+ };
+ },
+ };
+ }
+
++/** The camera came to rest: coverage refreshes once its debounce is over. */
++async function moved(viewer) {
++ viewer.camera.moveEnd.raiseEvent();
++ await new Promise((resolve) =>
++ setTimeout(resolve, COVERAGE_TUNING.moveDebounceMs + 20),
++ );
++}
++
+ test('a filter thins the lines to those its PNG mask draws; without one they all show', async (t) => {
+ const { lon, lat } = tileCentre(-83.0458, 42.3314);
+ // Across the tile's middle row (mask row ~256), and a quarter up (~130).
+ const across = (at) => [
+ [lon - 0.001, at],
+ [lon + 0.001, at],
+ ];
+ const env = coverageSetup(t, {
+ filter: { pano: 'pano', sinceMs: null },
+ lines: [across(lat), across(lat + 0.004)],
+ // 360° photos lie on the middle line only.
+ drawnRows: (query) => (query === 'fieldOfView=360' ? [[254, 258]] : []),
+ });
+ env.instance.activate(env.viewer);
+ assert.ok(await until(() => env.instance.coverageStats().count === 1));
+ assert.deepEqual(env.masks, ['fieldOfView=360']);
+ // Unfiltered: every line, and the tile's lines are not asked for again.
+ env.actions.filter = { pano: 'all', sinceMs: null };
+ env.instance.setFilter();
+ assert.ok(await until(() => env.instance.coverageStats().count === 2));
+ assert.equal(env.tiles.length, 1, 'the segments are kept');
+ // SINCE a day: uploaded since yesterday (UTC) — none here. The lines
- // drawn now stay on the globe while KartaView draws the filtered tile.
++ // drawn now go while KartaView draws the filtered tile.
+ const since = Date.now() - 86_400_000;
+ const release = env.holdMasks();
+ env.actions.filter = { pano: 'all', sinceMs: since };
+ env.instance.setFilter();
+ assert.ok(await until(() => env.instance.coverageStats().loading));
- assert.ok(
- env.viewer.scene.groundPrimitives.items.size > 0,
- 'the unfiltered lines show meanwhile',
++ assert.equal(
++ env.viewer.scene.groundPrimitives.items.size,
++ 0,
++ 'the unfiltered lines are not shown as filtered ones',
+ );
+ release();
+ assert.ok(
+ await until(
+ () =>
+ !env.instance.coverageStats().loading &&
+ env.instance.coverageStats().count === 0,
+ ),
+ );
+ assert.equal(
+ env.masks.at(-1),
+ `startDate=${new Date(since).toISOString().slice(0, 10)}`,
+ );
+ assert.equal(env.instance.coverageStats().hint, NO_COVERAGE_HINT);
- assert.ok(
- await until(() => env.viewer.scene.groundPrimitives.items.size === 0),
- 'and go once it is in',
- );
++ assert.equal(env.viewer.scene.groundPrimitives.items.size, 0);
+ // The same filter again asks KartaView for nothing.
+ env.instance.setFilter();
+ for (let i = 0; i < 5; i++) await settle();
+ assert.equal(env.masks.length, 2);
+ });
+
+ test('coverage hints: zoom in from too high, “no photos” only once an empty view has loaded', async (t) => {
+ const env = coverageSetup(t, { height: 7_000 });
+ env.instance.activate(env.viewer);
+ assert.equal(env.instance.coverageStats().hint, TOO_HIGH_HINT);
+ assert.deepEqual(env.tiles, [], 'nothing asked from up there');
+ const release = env.holdTiles();
+ env.viewer.view.height = 900;
- env.instance.refreshCoverage();
++ await moved(env.viewer);
+ assert.ok(await until(() => env.instance.coverageStats().loading));
+ assert.equal(env.instance.coverageStats().hint, '', 'not while it loads');
+ release();
+ assert.ok(await until(() => !env.instance.coverageStats().loading));
+ assert.equal(env.instance.coverageStats().count, 0);
+ assert.equal(env.instance.coverageStats().hint, NO_COVERAGE_HINT);
+ });
+
+ test('coverage tiles are kept while KartaView is on and dropped once it is switched off', async (t) => {
+ const env = coverageSetup(t, {
+ lines: [
+ [
+ [-83.0458 - 0.001, 42.3314],
+ [-83.0458 + 0.001, 42.3314],
+ ],
+ ],
+ });
+ env.instance.activate(env.viewer);
+ assert.ok(await until(() => env.instance.coverageStats().count === 1));
- env.instance.refreshCoverage();
++ await moved(env.viewer);
+ assert.ok(await until(() => env.instance.coverageStats().count === 1));
+ assert.equal(env.tiles.length, 1, 'kept while on');
+ // Switched off: the decoded lines are not kept, so on again asks again.
+ env.instance.deactivate();
+ env.instance.activate(env.viewer);
+ assert.ok(await until(() => env.instance.coverageStats().count === 1));
+ assert.equal(env.tiles.length, 2);
+ });
+
+ test('a photo no page lists steps to the photos either side of its index', async () => {
+ const env = await mounted({ sequences: { s: [0, 1, 2, 3, 4, 6, 7, 8, 9] } });
+ const getPhoto = env.source.getPhoto;
+ env.source.getPhoto = async (id) =>
+ id === 's-5'
+ ? photoRecord('s-5', { seq: 's', index: 5, metres: 25 })
+ : getPhoto(id);
+ await env.instance.viewer.open('s-5');
+ await press(env.next, env.poses);
+ assert.equal(env.poses.at(-1), 's-6');
+ await env.instance.viewer.open('s-5');
+ await press(env.prev, env.poses);
+ assert.equal(env.poses.at(-1), 's-4');
+ });
+
+ test('Esc in the docked viewer clears the selected drive and is consumed; with none, it goes on to the panel', async (t) => {
+ const env = await mounted({ sequences: { s: [0, 1, 2, 3] } });
+ await withCones(t, env);
+ await env.instance.viewer.open('s-1');
+ await env.instance.selectSequence('s');
+ assert.ok(await until(() => env.instance.sequenceStats().images === 4));
+ const root = env.next.parentNode;
+ const press = () => {
+ const flags = { stopped: false, prevented: false };
+ root.fire('keydown', {
+ key: 'Escape',
+ stopPropagation: () => (flags.stopped = true),
+ preventDefault: () => (flags.prevented = true),
+ });
+ return flags;
+ };
+ assert.deepEqual(press(), { stopped: true, prevented: true });
+ assert.equal(env.instance.sequenceStats().selectedId, null, 'drive cleared');
+ assert.deepEqual(press(), { stopped: false, prevented: false });
+ });
+
+ test('the panel counts the drive’s photos, not the thinned page of them the cones show', async (t) => {
+ const env = await mounted({
+ sequences: { s: Array.from({ length: 40 }, (_, i) => i) },
+ });
+ const asked = [];
+ env.source.getSequenceCount = async (id) => {
+ asked.push(id);
+ return 2385;
+ };
+ await withCones(t, env);
+ await env.instance.viewer.open('s-3');
+ await env.instance.selectSequence('s');
+ assert.ok(
+ await until(() => env.instance.sequenceStats().images === 2385),
+ `images: ${env.instance.sequenceStats().images}`,
+ );
+ // Asked once per drive.
+ env.instance.clearSequence();
+ await env.instance.viewer.open('s-30');
+ await env.instance.selectSequence('s');
+ assert.ok(await until(() => env.instance.sequenceStats().images === 2385));
+ assert.deepEqual(asked, ['s']);
+ });
+
+ test('after a GPU reset the photo is drawn again by the viewer, not through the core; a failure is reported', async () => {
+ const source = fakeSource();
+ const record = {
+ ...photoRecord('pano', { seq: 'p', index: 0 }),
+ projection: 'SPHERE',
+ fieldOfView: '360',
+ filepathProc: '2022/10/6/wrapped_proc/pano.jpg',
+ };
+ source.getPhoto = async () => record;
+ const view = { yaw: 0, pitch: 0, fov: 80 };
+ let failLoads = false;
+ const definition = createKartaViewProvider({
+ source,
+ viewerOptions: {
+ load: async (url) => {
+ if (failLoads)
+ throw new Error('The KartaView photo could not be loaded');
+ return { src: url };
+ },
+ createRenderer: () => ({
+ setImage() {},
+ setView: (next) => Object.assign(view, next),
+ getView: () => ({ ...view }),
+ resize() {},
+ clear() {},
+ destroy() {},
+ }),
+ },
+ });
+ const { context, actions } = fakeContext();
+ const errors = [];
+ context.actions.reportError = (message) => errors.push(message);
+ const instance = definition.create(context);
+ actions.instance = instance;
+ const host = fakeHost();
+ await instance.viewer.mount(host);
+ const poses = [];
+ instance.viewer.onPose((pose) => poses.push(pose.imageId));
+ await instance.viewer.open('pano');
+ const canvas = () => host.children[0].children[1];
+ const kind = () => host.children[0].dataset.kind;
+ canvas().fire('webglcontextlost');
+ assert.equal(kind(), '', 'cleared while it is drawn again');
+ assert.ok(await until(() => kind() === 'pano'), 'drawn again');
+ assert.ok(poses.length >= 2);
+ assert.deepEqual(actions.opened, [], 'the core (and its lookup) left alone');
+ failLoads = true;
+ canvas().fire('webglcontextlost');
+ assert.ok(await until(() => errors.length === 1));
+ assert.match(errors[0], /could not be loaded/);
+ });
+
+ test('the marker is KartaView’s own cone, and it points along the drive, not at a wrong compass', async () => {
+ const env = setup({
+ sequences: { s: Array.from({ length: 10 }, (_, i) => i) },
+ });
+ assert.deepEqual(env.definition.marker, {
+ kind: 'view-cone',
+ color: '#635bff',
+ });
+ // Photos run east (photoRecord puts index i at 5·i m east); the compass says 200°.
+ const getPhoto = env.source.getPhoto;
+ env.source.getPhoto = async (id) => ({
+ ...(await getPhoto(id)),
+ heading: '200',
+ });
+ const getPage = env.source.getSequencePhotos;
+ env.source.getSequencePhotos = async (...args) => {
+ const page = await getPage(...args);
+ return {
+ ...page,
+ photos: page.photos.map((record) => ({ ...record, heading: '200' })),
+ };
+ };
+ const host = fakeHost();
+ await env.instance.viewer.mount(host);
+ const bearings = [];
+ env.instance.viewer.onPose((pose) => bearings.push(pose.bearing));
+ await env.instance.viewer.open('s-4');
+ assert.equal(bearings[0], 200, 'the compass until the drive is known');
+ assert.ok(
+ await until(() => Math.abs(bearings.at(-1) - 90) < 1),
+ `then along the drive: ${bearings}`,
+ );
+ });
+
+ /** Hold `seq`'s page `page` until the returned function is called. */
+ function holdPage(source, seq, page) {
+ const getPage = source.getSequencePhotos;
+ let release;
+ const gate = new Promise((resolve) => (release = resolve));
+ source.getSequencePhotos = async (id, options) => {
+ if (id === seq && options.page === page) await gate;
+ return getPage(id, options);
+ };
+ return () => release();
+ }
+
+ test('a photo opened while the cones first load is the one they centre on', async (t) => {
+ const size = SEQUENCE_PAGE_SIZE;
+ const env = await mounted({
+ sequences: { s: Array.from({ length: size * 5 }, (_, i) => i) },
+ });
+ const cones = await withCones(t, env);
+ const release = holdPage(env.source, 's', 1);
+ await env.instance.viewer.open('s-10');
+ const selected = env.instance.selectSequence('s');
+ // A line click further along the drive while page 1 is still loading:
+ // nothing is drawn yet for its re-centre to move.
+ await env.instance.viewer.open(`s-${size * 4 + 10}`);
+ release();
+ await selected;
+ assert.ok(
+ await until(
+ () => !env.instance.sequenceStats().loading && cones.count() > 0,
+ ),
+ );
+ assert.ok(
+ cones()[0] <= size * 4 + 10 && cones()[1] >= size * 4 + 10,
+ `around the newer photo, not the first: ${cones()}`,
+ );
+ });
+
+ test('a sequence page that lands while a lost GPU context recovers still draws its cones', async (t) => {
+ const env = setup({ sequences: { p: [0, 1, 2, 3] } });
+ const sphere = (record) => ({
+ ...record,
+ projection: 'SPHERE',
+ fieldOfView: '360',
+ filepathProc: `2022/10/6/wrapped_proc/${record.id}.jpg`,
+ });
+ const getPhoto = env.source.getPhoto;
+ env.source.getPhoto = async (id) => sphere(await getPhoto(id));
+ const getPage = env.source.getSequencePhotos;
+ env.source.getSequencePhotos = async (...args) => {
+ const page = await getPage(...args);
+ return { ...page, photos: page.photos.map(sphere) };
+ };
+ const release = holdPage(env.source, 'p', 1);
+ let holdImages = false;
+ let releaseImage = null;
+ const view = { yaw: 0, pitch: 0, fov: 80 };
+ const definition = createKartaViewProvider({
+ source: env.source,
+ viewerOptions: {
+ load: async (url) => {
+ if (holdImages) await new Promise((r) => (releaseImage = r));
+ return { src: url };
+ },
+ createRenderer: () => ({
+ setImage() {},
+ setView: (next) => Object.assign(view, next),
+ getView: () => ({ ...view }),
+ resize() {},
+ clear() {},
+ destroy() {},
+ }),
+ },
+ });
+ const { context, actions } = fakeContext();
+ const errors = [];
+ context.actions.reportError = (message) => errors.push(message);
+ const instance = definition.create(context);
+ actions.instance = instance;
+ const cones = await withCones(t, { instance });
+ const host = fakeHost();
+ await instance.viewer.mount(host);
+ await instance.viewer.open('p-0');
+ // › to the next panorama; the GPU resets while it loads.
+ holdImages = true;
+ const opening = instance.viewer.open('p-1');
+ assert.ok(await until(() => releaseImage !== null));
+ host.children[0].children[1].fire('webglcontextlost');
+ const selected = instance.selectSequence('p');
+ release();
+ await selected;
+ assert.ok(
+ await until(() => !instance.sequenceStats().loading && cones.count() > 0),
+ 'the page is drawn, not dropped',
+ );
+ releaseImage();
+ await opening;
+ assert.equal(host.children[0].dataset.kind, 'pano', 'p-1 shows');
+ // reportError(null) clears; nothing was reported.
+ assert.deepEqual(errors.filter(Boolean), []);
+ });
diff --cc src/layers/streetLevel/providers/mapillary/coverageFixture.mjs
index b7b738056,9f9f0fa2f..9c506ea45
--- a/src/layers/streetLevel/providers/mapillary/coverageFixture.mjs
+++ b/src/layers/streetLevel/providers/mapillary/coverageFixture.mjs
@@@ -1,9 -1,9 +1,9 @@@
import { PbfWriter } from 'pbf';
- const zigzag = (value) => (value << 1) ^ (value >> 31);
+ export const zigzag = (value) => (value << 1) ^ (value >> 31);
/** Tile-local [x, y] (0..extent) of a lon/lat inside tile (x, y, z). */
-export function lonLatToTileLocal([lon, lat], { x, y, z }, extent = 4096) {
+function lonLatToTileLocal([lon, lat], { x, y, z }, extent = 4096) {
const n = 2 ** z;
const rad = (lat * Math.PI) / 180;
const tx = ((lon + 180) / 360) * n;
diff --cc src/layers/streetLevel/providers/mapillary/decode.js
index e610489a4,b4381dbad..ac2538b34
--- a/src/layers/streetLevel/providers/mapillary/decode.js
+++ b/src/layers/streetLevel/providers/mapillary/decode.js
@@@ -1,10 -1,10 +1,10 @@@
import { PbfReader } from 'pbf';
import { VectorTile } from '@mapbox/vector-tile';
- import { tileLocalToLonLat } from './tileMath.js';
+ import { tileLocalToLonLat } from '../../tileMath.js';
/**
- * Decode a `mly1_public` coverage tile into sequences and (z0–5) overview
- * points. The z14 `image` layer, which can hold >150k points, is skipped.
+ * Decode a `mly1_public` coverage tile (z11–14) into sequences. The z14
+ * `image` layer, which can hold >150k points, is skipped.
* @param {Uint8Array} bytes
* @param {{x:number,y:number,z:number}} address
*/
diff --cc src/layers/streetLevel/providers/mapillary/index.js
index 7bd726460,1cbe887a6..928922195
--- a/src/layers/streetLevel/providers/mapillary/index.js
+++ b/src/layers/streetLevel/providers/mapillary/index.js
@@@ -1,27 -1,52 +1,47 @@@
- import { freshCoverage } from './state.js';
--import { createCoverage, sequenceIdFromPick } from './coverage.js';
--import { createSequences } from './sequences.js';
++import {
++ createLineCoverage,
++ freshCoverage,
++ sequenceIdFromPick,
++} from '../../lineCoverage.js';
++import { createSequenceCones, thinImages } from '../../sequenceCones.js';
++import { coverageZoomForHeight } from '../../tileMath.js';
++import { decodeCoverageTile } from './decode.js';
import { createMapillaryViewer } from './viewer.js';
-import { passesImageryFilter } from '../../filter.js';
-import { metresBetween } from '../../view.js';
import {
COLORS,
++ COVERAGE_TUNING,
++ KEY_REJECTED_MESSAGE,
MAPILLARY_CREDIT_HTML,
MAPILLARY_KEY_ID,
MAPILLARY_LABEL,
MAPILLARY_NAME,
MAPILLARY_PROVIDER_ID,
MAPILLARY_SOURCE_METHODS,
- NEAREST_LIMIT,
- NEAREST_RADIUS_M,
PICK_PREFIX,
++ RATE_LIMITED_MESSAGE,
} from './policy.js';
- /** Per-provider mutable state; coverage and sequences share it. */
-/** Per-provider mutable state, created once per `create()`. */
++/** Normalize a graph image record into the shape the cones use. */
++function normalizeSequenceImage(record) {
++ const coordinates = record?.geometry?.coordinates;
++ if (!Array.isArray(coordinates) || coordinates.length < 2) return null;
++ return {
++ id: String(record.id),
++ lon: Number(coordinates[0]),
++ lat: Number(coordinates[1]),
++ compassAngle: Number(record.compass_angle) || 0,
++ capturedAt: Number(record.captured_at) || 0,
++ isPano: record.is_pano === true,
++ };
++}
++
++/** Per-provider mutable state; coverage and cones share it. */
function createProviderState(context) {
return {
+ context,
services: context.services,
- getFilter: context.getFilter,
- isActive: context.isActive,
- notify: context.notify,
viewer: null,
- keyRequired: false,
- /** Coverage waits for the first status: no tile requests without a key. */
- statusKnown: false,
- /** Mapillary refused the token: request nothing until re-enabled. */
- keyRejected: false,
- status: null,
- coverage: {
- zoom: null,
- /** Current zoom's tiles by `z/x/y` key. */
- tiles: new Map(),
- /** Previous zoom's tiles, kept on screen until replacements land. */
- stale: new Map(),
- staleTimer: null,
- /** Tile key → its request's controller; any entry means LOADING. */
- pending: new Map(),
- lastError: null,
- /** While Mapillary rate-limits: no requests before this time (ms). */
- holdUntil: 0,
- holdTimer: null,
- debounceTimer: null,
- removeCameraListener: null,
- terrainReady: null,
- hint: '',
- kind: null,
- },
+ coverage: freshCoverage(),
sequence: {
selectedId: null,
images: [],
@@@ -35,13 -60,11 +55,13 @@@
}
/**
- * Mapillary Street Level provider: tile coverage, Graph API image cones and
- * the MapillaryJS viewer. `source` is ./source.js or a stand-in.
+ * The Mapillary provider: coverage lines from vector tiles, image cones from
+ * the Graph API and the MapillaryJS viewer.
+ * @param {{source: object, photoViewer?: object}} options `source` is
+ * source.js or a stand-in; `photoViewer` stands in for the viewer adapter.
- * @returns {import('./registry.js').StreetLevelProvider}
+ * @returns {import('../../registry.js').StreetLevelProvider}
*/
-export function createMapillaryProvider({ source }) {
+export function createMapillaryProvider({ source, photoViewer = null }) {
if (
!MAPILLARY_SOURCE_METHODS.every(
(method) => typeof source?.[method] === 'function',
@@@ -61,26 -84,33 +81,62 @@@
create(context) {
const state = createProviderState(context);
const parts = {};
- parts.coverage = createCoverage({ state, source });
- parts.coverage = createCoverage({ state, source, parts });
-- parts.sequences = createSequences({ state, source, parts });
- const viewer = createMapillaryViewer({
- source,
- render: context.services?.render,
++ parts.coverage = createLineCoverage({
++ state,
++ fetchTile: async (tile, { signal }) =>
++ decodeCoverageTile(
++ await source.getTile('coverage', tile.z, tile.x, tile.y, {
++ signal,
++ }),
++ tile,
++ ),
++ zoomFor: coverageZoomForHeight,
++ colors: COLORS,
++ pickPrefix: PICK_PREFIX.sequence,
++ renderKey: 'mapillary-coverage',
++ tuning: COVERAGE_TUNING,
++ messages: {
++ keyRejected: KEY_REJECTED_MESSAGE,
++ rateLimited: RATE_LIMITED_MESSAGE,
++ },
++ });
++ parts.sequences = createSequenceCones({
++ state,
++ async loadImages(sequenceId, { signal }) {
++ const records = await source.getSequenceImages(sequenceId, {
++ signal,
++ });
++ return thinImages(
++ records
++ .map(normalizeSequenceImage)
++ .filter(Boolean)
++ .sort((a, b) => a.capturedAt - b.capturedAt),
++ );
++ },
++ colors: COLORS,
++ pickPrefix: PICK_PREFIX.image,
++ spriteId: 'street-level:mapillary-cones',
++ renderKey: 'mapillary-sequence',
++ onHighlight: (sequenceId) => parts.coverage.highlight(sequenceId),
+ });
return {
- async status() {
+ /** Coverage waits for the answer: no tile requests without a key. */
+ async status({ signal } = {}) {
+ let configured;
try {
- state.status = await source.getStatus();
- state.keyRequired = state.status?.configured !== true;
+ configured =
+ (await source.getStatus({ signal }))?.configured === true;
} catch {
- state.status = null;
- state.keyRequired = !source.hasToken();
+ configured = source.hasToken?.() === true;
}
- const first = !state.statusKnown;
- state.statusKnown = true;
- // Coverage held back until now: draw it if the layer is on.
- if (first) parts.coverage.refresh();
- context.notify();
- return { configured: !state.keyRequired };
+ parts.coverage.setKeyStatus(configured);
+ return { configured };
},
- init(cesiumViewer) {
- state.viewer = cesiumViewer;
- parts.sequences.ensureCollections(cesiumViewer);
+ init(viewer) {
+ state.viewer = viewer;
+ parts.sequences.ensureCollections(viewer);
parts.sequences.setVisible(false);
},
@@@ -111,11 -143,27 +167,11 @@@
parts.sequences.rerender();
},
- /** Core surface mode changed: redraw lines and cones draped or cast. */
- setSurface() {
- parts.coverage.setSurface();
- parts.sequences.rerender();
- },
-
- coverageStats() {
- return {
- count: parts.coverage.sequenceCount(),
- zoom: state.coverage.zoom,
- kind: state.coverage.kind,
- loading: state.coverage.pending.size > 0,
- hint: state.coverage.hint,
- error: state.coverage.lastError,
- keyRequired: state.keyRequired,
- keyRejected: state.keyRejected,
- };
- },
+ coverageStats: () => parts.coverage.stats(),
+ /** A line selects its sequence; a cone opens its image. */
handlePick(pickId) {
-- const sequenceId = sequenceIdFromPick(pickId);
++ const sequenceId = sequenceIdFromPick(pickId, PICK_PREFIX.sequence);
if (sequenceId) {
parts.sequences.select(sequenceId);
return true;
diff --cc src/layers/streetLevel/providers/mapillary/mapillary.test.mjs
index 3dcd43b12,000000000..a0f96138f
mode 100644,000000..100644
--- a/src/layers/streetLevel/providers/mapillary/mapillary.test.mjs
+++ b/src/layers/streetLevel/providers/mapillary/mapillary.test.mjs
@@@ -1,36 -1,0 +1,36 @@@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { mapillaryImageUrl } from './policy.js';
- import { sequenceIdFromPick } from './coverage.js';
- import { thinImages } from './sequences.js';
++import { sequenceIdFromPick } from '../../lineCoverage.js';
++import { thinImages } from '../../sequenceCones.js';
+
+test('image deep links match the mapillary.com share format', () => {
+ assert.equal(
+ mapillaryImageUrl(1814275685699406),
+ 'https://www.mapillary.com/app/?pKey=1814275685699406&focus=photo',
+ );
+ assert.equal(mapillaryImageUrl(' '), 'https://www.mapillary.com/app/');
+});
+
+test('a sequence line pick names its sequence; other picks do not', () => {
- assert.equal(sequenceIdFromPick('mly:seq:abc'), 'abc');
- assert.equal(sequenceIdFromPick('mly:img:abc'), null);
- assert.equal(sequenceIdFromPick(null), null);
++ assert.equal(sequenceIdFromPick('mly:seq:abc', 'mly:seq:'), 'abc');
++ assert.equal(sequenceIdFromPick('mly:img:abc', 'mly:seq:'), null);
++ assert.equal(sequenceIdFromPick(null, 'mly:seq:'), null);
+});
+
+test('cone thinning across the date line drops images metres apart', () => {
+ const image = (id, lon) => ({ id, lon, lat: 0 });
+ // A sequence driving east over ±180° with images ~1 m apart, then ~11 m on.
+ const kept = thinImages(
+ [
+ image('a', 179.99999),
+ image('b', -179.99999), // ~2 m from a, across the date line
+ image('c', -179.9999), // ~11 m from a
+ ],
+ 3,
+ );
+ assert.deepEqual(
+ kept.map(({ id }) => id),
+ ['a', 'c'],
+ );
+});
diff --cc src/layers/streetLevel/providers/mapillary/policy.js
index 000000000,4689f3688..183082934
mode 000000,100644..100644
--- a/src/layers/streetLevel/providers/mapillary/policy.js
+++ b/src/layers/streetLevel/providers/mapillary/policy.js
@@@ -1,0 -1,83 +1,74 @@@
+ import { COLORS as SHARED_COLORS, PROVIDER_COLORS } from '../../policy.js';
+
+ // Reached by source.js (no browser globals, see check:boundaries), so no
+ // i18n import: the messages stay English data, translated where shown.
+ const msg = (text) => text;
+
-export { NEAREST_RADIUS_M } from '../../policy.js';
-
+ /** Identity and tuning for the Mapillary street-level provider. */
+ export const MAPILLARY_PROVIDER_ID = 'mapillary';
+ export const MAPILLARY_NAME = 'Mapillary';
+ export const MAPILLARY_LABEL = 'MAPILLARY';
+ export const MAPILLARY_KEY_ID = 'mapillary';
+ export const MAPILLARY_GRAPH_HOST = 'https://graph.mapillary.com';
+
-/** Methods a source (./source.js or a stand-in) must have for the provider. */
++/** What the provider needs from its source (source.js or a stand-in). */
+ export const MAPILLARY_SOURCE_METHODS = Object.freeze([
+ 'getStatus',
+ 'getTile',
+ 'getSequenceImages',
- 'nearestImages',
+ ]);
+
+ /** Stable id prefixes for picked primitives; every one starts with `mly:`. */
+ export const PICK_PREFIX = Object.freeze({
+ root: 'mly:',
+ sequence: 'mly:seq:',
+ image: 'mly:img:',
+ });
+
-/** Mapillary green for lines, points and cones; GEV cyan for selection. */
++/** Mapillary green for lines and cones; GEV cyan for the selection. */
+ export const COLORS = Object.freeze({
+ coverage: PROVIDER_COLORS.mapillary,
+ selected: SHARED_COLORS.selected,
+ });
+
-/** Camera-driven coverage refresh. */
-export const COVERAGE_MOVE_DEBOUNCE_MS = 320;
-export const COVERAGE_MAX_TILES = 9;
-/** Overview (z0–5) coverage points seen from orbit. */
-export const COVERAGE_OVERVIEW_MAX_TILES = 16;
+ /** Shown when Mapillary refuses the server's token (401/403). */
+ export const KEY_REJECTED_MESSAGE = msg(
+ 'Mapillary rejected MAPILLARY_CLIENT_TOKEN — replace it in Provider Settings',
+ );
+ /** Shown while Mapillary rate-limits tile requests (429). */
+ export const RATE_LIMITED_MESSAGE = msg(
+ 'Coverage requests are being rate-limited — they resume on their own',
+ );
-/**
- * Street-zoom coverage reaches this far from the camera: camera height times
- * the factor, never below the floor, even when a tilted view sees further.
- */
-export const SEQUENCE_VIEW_RANGE_MIN_M = 2_500;
-export const SEQUENCE_VIEW_RANGE_PER_HEIGHT = 10;
-/** Ground always covered around the camera at street zooms, in metres. */
-export const SEQUENCE_VIEW_NEAR_M = 1_000;
-export const COVERAGE_OVERVIEW_POINT_PX = 2.5;
-export const COVERAGE_MAX_SEQUENCES = 6000;
-export const COVERAGE_LINE_WIDTH_PX = 2.5;
++
++/** Coverage tuning (see LineCoverageTuning in lineCoverage.js). */
++export const COVERAGE_TUNING = Object.freeze({
++ maxTiles: 9,
++ maxSequences: 6000,
++ lineWidthPx: 2.5,
++ moveDebounceMs: 320,
++ /**
++ * Street-zoom coverage reaches this far from the camera: camera height
++ * times the factor, never below the floor, even when a tilted view sees
++ * further.
++ */
++ viewRangeMinM: 2_500,
++ viewRangePerHeight: 10,
++});
+
+ /** Per-sequence image cones after a sequence is selected. */
+ export const SEQUENCE_IMAGES_LIMIT = 2000;
+
-/** Images asked for in a nearest-image search (radius: NEAREST_RADIUS_M). */
-export const NEAREST_LIMIT = 8;
-
+ /** On-globe credit: Mapillary imagery is CC BY-SA 4.0 and needs attribution. */
+ export const MAPILLARY_CREDIT_HTML =
+ 'Street Level: imagery © <a href="https://www.mapillary.com" target="_blank" rel="noopener">Mapillary</a> contributors, CC BY-SA 4.0';
+
+ /** Deep link to an image on mapillary.com, as the web app shares them. */
+ export function mapillaryImageUrl(imageId) {
+ const id = String(imageId || '').trim();
+ if (!id) return 'https://www.mapillary.com/app/';
+ return `https://www.mapillary.com/app/?pKey=${encodeURIComponent(id)}&focus=photo`;
+ }
+
-/** Fields requested from the graph API. */
-export const IMAGE_FIELDS =
- 'id,captured_at,compass_angle,computed_compass_angle,geometry,computed_geometry,computed_altitude,is_pano,sequence,thumb_256_url,creator,quality_score';
++/** Fields requested for a sequence's images. */
+ export const SEQUENCE_IMAGE_FIELDS =
- 'id,captured_at,compass_angle,geometry,is_pano,computed_altitude';
++ 'id,captured_at,compass_angle,geometry,is_pano';
diff --cc src/layers/streetLevel/providers/mapillary/provider.test.mjs
index 4996d8828,35e8593bf..ce2f0bb0c
--- a/src/layers/streetLevel/providers/mapillary/provider.test.mjs
+++ b/src/layers/streetLevel/providers/mapillary/provider.test.mjs
@@@ -1,15 -1,24 +1,15 @@@
import assert from 'node:assert/strict';
import test from 'node:test';
+import * as Cesium from 'cesium';
- import { createMapillaryProvider } from './mapillaryProvider.js';
+ import { createMapillaryProvider } from './index.js';
import { mapillaryImageUrl } from './policy.js';
--import { sequenceIdFromPick } from './coverage.js';
--import { thinImages } from './sequences.js';
- import { validateProviders } from './registry.js';
++import { sequenceIdFromPick } from '../../lineCoverage.js';
++import { thinImages } from '../../sequenceCones.js';
+ import { validateProviders } from '../../registry.js';
-import { PROVIDER_COLORS } from '../../policy.js';
-import { resolveFilter } from '../../filter.js';
-import * as Cesium from 'cesium';
-import { rayCamera } from '../../../../testSupport/streetLevelFakes.mjs';
-
-function fakeSource({ nearest = [] } = {}) {
- return {
- hasToken: () => true,
- getStatus: async () => ({ configured: true }),
- getTile: async () => new Uint8Array(0),
- getSequenceImages: async () => [],
- nearestImages: async () => nearest,
- };
-}
+import {
+ fakeMapillarySource,
+ rayCamera,
- } from '../../testSupport/streetLevelFakes.mjs';
++} from '../../../../testSupport/streetLevelFakes.mjs';
function fakeContext(filter = { pano: 'all', sinceMs: null }) {
const opened = [];
@@@ -60,10 -75,96 +60,10 @@@ test('picks route sequences to selectio
});
});
-test('nearestImage honours the imagery filter and reports key status', async () => {
- const nearest = [
- { id: 1, is_pano: false, captured_at: 10 },
- { id: 2, is_pano: true, captured_at: 20 },
- ];
- const source = fakeSource({ nearest });
- const flat = createMapillaryProvider({ source }).create(fakeContext());
- assert.equal(await flat.nearestImage({ lat: 1, lon: 2 }), '1');
- const pano = createMapillaryProvider({ source }).create(
- fakeContext({ pano: 'pano', sinceMs: null }),
- );
- assert.equal(await pano.nearestImage({ lat: 1, lon: 2 }), '2');
- const none = createMapillaryProvider({ source }).create(
- fakeContext({ pano: 'all', sinceMs: 100 }),
- );
- assert.equal(await none.nearestImage({ lat: 1, lon: 2 }), null);
- assert.deepEqual(await flat.status(), { configured: true });
- assert.equal(flat.coverageStats().keyRequired, false);
-});
-
-test('any part of a multi-part sequence picks the whole sequence', () => {
- assert.equal(sequenceIdFromPick('mly:seq:abc'), 'abc');
- assert.equal(sequenceIdFromPick('mly:seq:abc~2'), 'abc');
- assert.equal(sequenceIdFromPick('mly:img:abc'), null);
- assert.equal(sequenceIdFromPick(null), null);
-});
-
-test('nearestImage picks the closest image, not the first the API returned', async () => {
- const at = (id, lon, lat) => ({
- id,
- is_pano: false,
- captured_at: 10,
- geometry: { type: 'Point', coordinates: [lon, lat] },
- });
- const source = fakeSource({
- nearest: [
- at('far', 2.0004, 1), // ~45 m east
- at('near', 2.00005, 1), // ~5 m east
- at('mid', 2, 1.0002), // ~22 m north
- ],
- });
- const instance = createMapillaryProvider({ source }).create(fakeContext());
- assert.equal(await instance.nearestImage({ lat: 1, lon: 2 }), 'near');
-});
-
-test('a "since N days" window follows the clock in a long-open tab', async (t) => {
- t.mock.timers.enable({ apis: ['Date'], now: Date.UTC(2026, 9, 1) });
- const day = 86_400_000;
- const capturedAt = Date.now() - day / 2;
- const source = fakeSource({
- nearest: [{ id: 'recent', is_pano: false, captured_at: capturedAt }],
- });
- // The core's context resolves the stored filter whenever it is asked.
- const instance = createMapillaryProvider({ source }).create(
- fakeContext(() => resolveFilter({ pano: 'all', sinceDays: 1 })),
- );
- assert.equal(await instance.nearestImage({ lat: 1, lon: 2 }), 'recent');
- t.mock.timers.tick(2 * day);
- assert.equal(
- await instance.nearestImage({ lat: 1, lon: 2 }),
- null,
- 'two days on, the image is older than the window',
- );
-});
-
-test('nearestImage measures the short way round the date line', async () => {
- const at = (id, lon, lat) => ({
- id,
- is_pano: false,
- captured_at: 10,
- geometry: { type: 'Point', coordinates: [lon, lat] },
- });
- const source = fakeSource({
- nearest: [
- at('same-side', 179.9995, 0), // ~45 m west, on the camera's side
- at('across', -179.9999, 0), // ~11 m east, across ±180°
- ],
- });
- const instance = createMapillaryProvider({ source }).create(fakeContext());
- assert.equal(
- await instance.nearestImage({ lat: 0, lon: 179.9999 }),
- 'across',
- );
- // And from the other side.
- const west = createMapillaryProvider({
- source: fakeSource({
- nearest: [at('same-side', -179.9995, 0), at('across', 179.9999, 0)],
- }),
- }).create(fakeContext());
- assert.equal(await west.nearestImage({ lat: 0, lon: -179.9999 }), 'across');
+test('a line pick names its sequence; anything else is not a sequence', () => {
- assert.equal(sequenceIdFromPick('mly:seq:abc'), 'abc');
- assert.equal(sequenceIdFromPick('mly:img:abc'), null);
- assert.equal(sequenceIdFromPick(null), null);
++ assert.equal(sequenceIdFromPick('mly:seq:abc', 'mly:seq:'), 'abc');
++ assert.equal(sequenceIdFromPick('mly:img:abc', 'mly:seq:'), null);
++ assert.equal(sequenceIdFromPick(null, 'mly:seq:'), null);
});
test('cone thinning across the date line drops images metres apart', () => {
diff --cc src/layers/streetLevel/providers/panoramax/decode.js
index 000000000,b8cbfeacc..288433d46
mode 000000,100644..100644
--- a/src/layers/streetLevel/providers/panoramax/decode.js
+++ b/src/layers/streetLevel/providers/panoramax/decode.js
@@@ -1,0 -1,291 +1,238 @@@
+ import { PbfReader } from 'pbf';
+ import { VectorTile } from '@mapbox/vector-tile';
+ import { tileLocalToLonLat } from '../../tileMath.js';
+ import {
+ DECODE_SLICE_MS,
- OVERVIEW_BINS_PER_AXIS,
+ SIMPLIFY_TOLERANCE_UNITS,
+ panoramaxTimeMs,
+ } from './policy.js';
+
+ /**
+ * Douglas–Peucker in tile units: the points of `line` ({x, y}) that keep
+ * it within `tolerance` of the original (measured to each segment, so
+ * dead ends and U-turns stay), first and last always kept.
+ * Iterative, so a long track cannot overflow the stack.
+ */
+ export function simplifyLine(line, tolerance) {
+ if (line.length < 3 || !(tolerance > 0)) return line;
+ const keep = new Uint8Array(line.length);
+ keep[0] = 1;
+ keep[line.length - 1] = 1;
+ const spans = [[0, line.length - 1]];
+ while (spans.length) {
+ const [from, to] = spans.pop();
+ const a = line[from];
+ const b = line[to];
+ const dx = b.x - a.x;
+ const dy = b.y - a.y;
+ const span2 = dx * dx + dy * dy;
+ let far = -1;
+ let farthest = tolerance;
+ for (let i = from + 1; i < to; i++) {
+ const p = line[i];
+ // Distance to the segment, not the infinite line: a dead end or a
+ // U-turn (a point beyond the chord's ends) is kept.
+ const t = span2
+ ? Math.max(
+ 0,
+ Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / span2),
+ )
+ : 0;
+ const d = Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy));
+ if (d > farthest) {
+ farthest = d;
+ far = i;
+ }
+ }
+ if (far === -1) continue;
+ keep[far] = 1;
+ spans.push([from, far], [far, to]);
+ }
+ return line.filter((_, i) => keep[i]);
+ }
+
+ /** Epoch ms of a sequence's day ('2025-08-11'), or 0 when undated. */
+ function dayMs(value) {
+ return panoramaxTimeMs(typeof value === 'string' ? value : '') ?? 0;
+ }
+
+ /**
+ * Decode a Panoramax coverage tile (`/api/map/{z}/{x}/{y}.mvt`).
+ *
+ * - `sequences` (z7–15): one line per sequence, its parts kept apart so no
+ * segment is drawn across a gap, with its day and camera type; longest
+ * first, so a cap on lines drawn drops the shortest.
- * - `grid` (z0–6): picture-density cells, as overview points binned to at
- * most OVERVIEW_BINS_PER_AXIS² a tile (a z0 tile holds ~70,000 cells). A
- * cell has 360° and flat counts but no date.
++ * - `grid` (z0–6, density cells) is not read: nothing is drawn from orbit.
+ * - `pictures` (z15) is left for `decodePictures`.
+ *
+ * In one go; `decodeCoverageTileSliced` gives the page a turn between
+ * slices.
+ * @param {Uint8Array} bytes
+ * @param {{x: number, y: number, z: number}} address
- * @returns {{sequences: Array<{id: string, parts: Array<Array<[number, number]>>, capturedAt: number, isPano: boolean}>, overview: Array<{id: string, lon: number, lat: number, capturedAt: null, isPano: boolean, hasPano: boolean, hasFlat: boolean, weight: number}>}}
++ * @returns {{sequences: Array<{id: string, parts: Array<Array<[number, number]>>, capturedAt: number, isPano: boolean}>}}
+ */
+ export function decodeCoverageTile(bytes, address) {
+ const steps = coverageSteps(bytes, address);
+ let step = steps.next();
+ while (!step.done) step = steps.next();
+ return step.value;
+ }
+
+ /** Give the page a turn: input and rendering run before the next slice. */
+ function nextTask() {
+ if (typeof globalThis.scheduler?.yield === 'function')
+ return globalThis.scheduler.yield();
+ return new Promise((resolve) => setTimeout(resolve, 0));
+ }
+
+ /**
+ * `decodeCoverageTile` in slices of about `sliceMs`, the page getting a
+ * turn between them: a 2 MB z10 tile over Paris is ~200 ms of decoding on
+ * a fast laptop, more on a phone, and would freeze the globe while the
+ * camera approaches. Stops at the next slice once `signal` aborts.
+ * @param {Uint8Array} bytes
+ * @param {{x: number, y: number, z: number}} address
+ * @param {{signal?: AbortSignal, sliceMs?: number, pause?: () => Promise<void>, now?: () => number}} [options]
+ */
+ export async function decodeCoverageTileSliced(
+ bytes,
+ address,
+ {
+ signal,
+ sliceMs = DECODE_SLICE_MS,
+ pause = nextTask,
+ now = () => performance.now(),
+ } = {},
+ ) {
+ const steps = coverageSteps(bytes, address);
+ let started = now();
+ let step = steps.next();
+ while (!step.done) {
+ if (now() - started >= sliceMs) {
+ await pause();
+ signal?.throwIfAborted();
+ started = now();
+ }
+ step = steps.next();
+ }
+ return step.value;
+ }
+
+ /** The decode, a step a feature (see `decodeCoverageTile`). */
+ function* coverageSteps(bytes, address) {
- const result = { sequences: [], overview: [] };
++ const result = { sequences: [] };
+ if (!bytes || !bytes.length) return result;
+ const tile = new VectorTile(new PbfReader(bytes));
+ const { x, y, z } = address;
+
+ const sequences = tile.layers.sequences;
+ if (sequences) {
+ const measured = [];
+ for (let i = 0; i < sequences.length; i++) {
+ const feature = sequences.feature(i);
+ const props = feature.properties || {};
+ const parts = [];
+ let length = 0;
+ const tolerance = (SIMPLIFY_TOLERANCE_UNITS * sequences.extent) / 4096;
+ for (const line of feature.loadGeometry()) {
+ if (line.length < 2) continue;
+ for (let k = 1; k < line.length; k++)
+ length += Math.hypot(
+ line[k].x - line[k - 1].x,
+ line[k].y - line[k - 1].y,
+ );
+ // Simplified before anything else: GPS tracks carry a point every
+ // few metres, and each becomes ~8 ground-line vertices on the GPU.
+ parts.push(
+ simplifyLine(line, tolerance).map((point) =>
+ tileLocalToLonLat(point.x, point.y, sequences.extent, x, y, z),
+ ),
+ );
+ }
+ if (!parts.length || props.id == null) continue;
+ const sequence = {
+ id: String(props.id),
+ parts,
+ capturedAt: dayMs(props.date),
+ // A sequence with no camera type is neither (the filters keep it).
+ isPano:
+ props.type === 'equirectangular'
+ ? true
+ : props.type === 'flat'
+ ? false
+ : null,
+ };
+ measured.push({ sequence, length });
+ yield;
+ }
+ // A turn before the sort: over a city it is thousands of lines.
+ yield;
+ measured.sort((a, b) => b.length - a.length);
+ result.sequences = measured.map(({ sequence }) => sequence);
+ }
+
- const grid = tile.layers.grid;
- if (grid) {
- const bins = new Map();
- const size = grid.extent / OVERVIEW_BINS_PER_AXIS;
- for (let i = 0; i < grid.length; i++) {
- const feature = grid.feature(i);
- const props = feature.properties || {};
- const point = feature.loadGeometry()?.[0]?.[0];
- if (i % 64 === 63) yield;
- if (!point) continue;
- const pano = Number(props.nb_360_pictures) || 0;
- const flat = Number(props.nb_flat_pictures) || 0;
- const weight = Number(props.nb_pictures) || pano + flat;
- if (weight <= 0) continue;
- const key = `${Math.floor(point.x / size)}:${Math.floor(point.y / size)}`;
- const bin = bins.get(key);
- if (!bin) {
- bins.set(key, { point, weight, pano, flat, top: weight });
- continue;
- }
- // The bin sits on its busiest cell and counts them all.
- bin.weight += weight;
- bin.pano += pano;
- bin.flat += flat;
- if (weight > bin.top) {
- bin.top = weight;
- bin.point = point;
- }
- }
- for (const [key, bin] of bins) {
- const [lon, lat] = tileLocalToLonLat(
- bin.point.x,
- bin.point.y,
- grid.extent,
- x,
- y,
- z,
- );
- result.overview.push({
- id: `${z}/${x}/${y}/${key}`,
- lon,
- lat,
- capturedAt: null,
- isPano: bin.pano > bin.flat,
- hasPano: bin.pano > 0,
- hasFlat: bin.flat > 0,
- weight: bin.weight,
- });
- }
- }
+ return result;
+ }
+
+ /** A picture's sequence ids: the tile stores them as a JSON array in a string. */
+ function sequenceIdsOf(props) {
+ const raw = props.sequences;
+ if (typeof raw === 'string' && raw.startsWith('[')) {
+ try {
+ const ids = JSON.parse(raw);
+ if (Array.isArray(ids)) return ids.map(String);
+ } catch {
+ /* fall through to the first sequence */
+ }
+ }
+ return props.first_sequence != null ? [String(props.first_sequence)] : [];
+ }
+
+ /**
+ * The pictures of a z15 tile that belong to `sequenceId`, as cones draw
+ * them (unsorted).
+ * @param {Uint8Array} bytes
+ * @param {{x: number, y: number, z: number}} address
+ * @param {string} sequenceId
+ * @returns {Array<{id: string, lon: number, lat: number, compassAngle: number, capturedAt: number, isPano: boolean}>}
+ */
+ export function decodePictures(bytes, address, sequenceId) {
+ if (!bytes || !bytes.length) return [];
+ const tile = new VectorTile(new PbfReader(bytes));
+ const layer = tile.layers.pictures;
+ if (!layer) return [];
+ const { x, y, z } = address;
+ const wanted = String(sequenceId);
+ const out = [];
+ for (let i = 0; i < layer.length; i++) {
+ const feature = layer.feature(i);
+ const props = feature.properties || {};
+ // A cheap test first: most pictures in a tile are other sequences'.
+ if (
+ typeof props.sequences === 'string' &&
+ !props.sequences.includes(wanted)
+ )
+ continue;
+ if (!sequenceIdsOf(props).includes(wanted) || props.id == null) continue;
+ const point = feature.loadGeometry()?.[0]?.[0];
+ if (!point) continue;
+ const [lon, lat] = tileLocalToLonLat(
+ point.x,
+ point.y,
+ layer.extent,
+ x,
+ y,
+ z,
+ );
+ const heading = Number(props.heading);
+ out.push({
+ id: String(props.id),
+ lon,
+ lat,
+ compassAngle: Number.isFinite(heading) ? heading : 0,
+ capturedAt: panoramaxTimeMs(String(props.ts ?? '')) ?? 0,
+ isPano: props.type === 'equirectangular',
+ });
+ }
+ return out;
+ }
diff --cc src/layers/streetLevel/providers/panoramax/decode.test.mjs
index 000000000,7caa25a63..b4beb1b88
mode 000000,100644..100644
--- a/src/layers/streetLevel/providers/panoramax/decode.test.mjs
+++ b/src/layers/streetLevel/providers/panoramax/decode.test.mjs
@@@ -1,0 -1,317 +1,275 @@@
+ import assert from 'node:assert/strict';
+ import test from 'node:test';
+ import {
+ decodeCoverageTile,
+ decodeCoverageTileSliced,
+ decodePictures,
+ simplifyLine,
+ } from './decode.js';
-import { OVERVIEW_BINS_PER_AXIS } from './policy.js';
+ import { encodePanoramaxTile } from '../../../../testSupport/panoramaxFixtures.mjs';
+ import { tileCentre } from '../../../../testSupport/streetLevelFakes.mjs';
+
+ const near = (a, b, eps = 1e-4) => Math.abs(a - b) < eps;
+
+ test('sequence lines keep their parts apart, with their day and camera type', () => {
+ const { tile, lon, lat } = tileCentre(2.35, 48.85);
+ const bytes = encodePanoramaxTile(tile, {
+ sequences: [
+ {
+ id: 'pano-seq',
+ type: 'equirectangular',
+ date: '2024-03-05',
+ parts: [
+ [
+ [lon - 0.001, lat],
+ [lon, lat],
+ ],
+ [
+ [lon + 0.0005, lat],
+ [lon + 0.001, lat],
+ ],
+ ],
+ },
+ {
+ id: 'flat-seq',
+ parts: [
+ [
+ [lon, lat - 0.001],
+ [lon, lat],
+ ],
+ ],
+ },
+ ],
+ });
- const { sequences, overview } = decodeCoverageTile(bytes, tile);
- assert.equal(overview.length, 0);
++ const { sequences } = decodeCoverageTile(bytes, tile);
+ assert.equal(sequences.length, 2);
+ const pano = sequences.find((s) => s.id === 'pano-seq');
+ const flat = sequences.find((s) => s.id === 'flat-seq');
+ assert.equal(pano.isPano, true);
+ assert.equal(pano.capturedAt, Date.UTC(2024, 2, 5));
+ assert.equal(pano.parts.length, 2, 'the gap is not bridged');
+ assert.ok(near(pano.parts[1][1][0], lon + 0.001));
+ assert.equal(flat.isPano, false);
+ const untyped = decodeCoverageTile(
+ encodePanoramaxTile(tile, {
+ sequences: [
+ {
+ id: 'u',
+ type: '',
+ parts: [
+ [
+ [lon, lat],
+ [lon + 0.001, lat],
+ ],
+ ],
+ },
+ ],
+ }),
+ tile,
+ ).sequences[0];
+ assert.equal(untyped.isPano, null, 'no camera type: neither');
+ });
+
-test('density cells bin to a bounded number of points that keep the counts and kinds', () => {
++test('the density grid is not read: nothing is drawn from orbit', () => {
+ const tile = { x: 0, y: 0, z: 0 };
- // Two cells in one bin (3.75° wide at z0) far enough apart to tell
- // which it sits on, one far away, one empty.
- const grid = [
- { lon: 0.3, lat: 48.85, pano: 0, flat: 5 },
- { lon: 3.4, lat: 48.85, pano: 30, flat: 0 },
- { lon: -73.9, lat: 40.7, pano: 1, flat: 0 },
- { lon: 10, lat: 10, pano: 0, flat: 0 },
- ];
- const { overview } = decodeCoverageTile(
- encodePanoramaxTile(tile, { grid }),
- tile,
- );
- assert.equal(overview.length, 2, 'Paris cells share a bin; empty cells go');
- const paris = overview.find((p) => p.lon > 0);
- assert.equal(paris.weight, 35);
- assert.equal(paris.hasPano, true);
- assert.equal(paris.hasFlat, true);
- assert.equal(paris.isPano, true, 'mostly 360°');
- assert.equal(paris.capturedAt, null, 'cells are undated');
- assert.ok(
- near(paris.lon, 3.4, 0.2),
- `sits on the busiest cell: ${paris.lon}`,
++ const grid = [{ lon: 2.35, lat: 48.85, pano: 3, flat: 5 }];
++ assert.deepEqual(
++ decodeCoverageTile(encodePanoramaxTile(tile, { grid }), tile),
++ { sequences: [] },
+ );
- const nyc = overview.find((p) => p.lon < 0);
- assert.deepEqual([nyc.hasPano, nyc.hasFlat, nyc.weight], [true, false, 1]);
+ });
+
+ test('lines come longest first, so a cap on lines drawn drops the shortest', () => {
+ const { tile, lon, lat } = tileCentre(2.35, 48.85);
+ const span = (id, metres) => ({
+ id,
+ parts: [
+ [
+ [lon, lat],
+ [lon + metres / 73_000, lat],
+ ],
+ ],
+ });
+ const { sequences } = decodeCoverageTile(
+ encodePanoramaxTile(tile, {
+ sequences: [span('short', 20), span('long', 900), span('mid', 300)],
+ }),
+ tile,
+ );
+ assert.deepEqual(
+ sequences.map((s) => s.id),
+ ['long', 'mid', 'short'],
+ );
+ });
+
-test('a dense grid tile never draws more than the bins allow', () => {
- const tile = { x: 0, y: 0, z: 0 };
- const grid = [];
- for (let i = 0; i < 300; i++)
- for (let j = 0; j < 60; j++)
- grid.push({ lon: -170 + i * 1.1, lat: -60 + j * 2 });
- const { overview } = decodeCoverageTile(
- encodePanoramaxTile(tile, { grid }),
- tile,
- );
- assert.ok(overview.length <= OVERVIEW_BINS_PER_AXIS ** 2);
- assert.ok(overview.length > 1000);
- assert.equal(
- overview.reduce((sum, p) => sum + p.weight, 0),
- grid.length,
- 'every picture is still counted',
- );
-});
-
+ /** A tile with many lines and a dense grid, for the sliced decode. */
+ function busyTile() {
+ const { tile, lon, lat } = tileCentre(2.35, 48.85);
+ const sequences = Array.from({ length: 200 }, (_, i) => ({
+ id: `s${i}`,
+ parts: [
+ [
+ [lon, lat + i / 1e6],
+ [lon + (i + 1) / 73_000, lat + i / 1e6],
+ ],
+ ],
+ }));
+ const grid = Array.from({ length: 500 }, (_, i) => ({
+ lon: lon + (i % 25) / 1e4,
+ lat: lat + Math.floor(i / 25) / 1e4,
+ }));
+ return { tile, bytes: encodePanoramaxTile(tile, { sequences, grid }) };
+ }
+
+ test('a sliced decode gives the page turns and decodes the same as one in one go', async () => {
+ const { tile, bytes } = busyTile();
+ let clock = 0;
+ let pauses = 0;
+ const sliced = await decodeCoverageTileSliced(bytes, tile, {
+ sliceMs: 8,
+ // Each step "takes" a millisecond: a turn every eight features.
+ now: () => clock++,
+ pause: async () => {
+ pauses++;
+ },
+ });
+ assert.ok(pauses > 20, `${pauses} turns`);
+ assert.deepEqual(sliced, decodeCoverageTile(bytes, tile));
+ });
+
+ test('a sliced decode stops at the next turn once aborted', async () => {
+ const { tile, bytes } = busyTile();
+ const controller = new AbortController();
+ let clock = 0;
+ let pauses = 0;
+ await assert.rejects(
+ decodeCoverageTileSliced(bytes, tile, {
+ signal: controller.signal,
+ now: () => (clock += 10),
+ pause: async () => {
+ if (++pauses === 2) controller.abort();
+ },
+ }),
+ { name: 'AbortError' },
+ );
+ assert.equal(pauses, 2, 'no work after the abort');
+ });
+
+ test('a fast sliced decode takes no turns', async () => {
+ const { tile, bytes } = busyTile();
+ let pauses = 0;
+ await decodeCoverageTileSliced(bytes, tile, {
+ now: () => 0,
+ pause: async () => {
+ pauses++;
+ },
+ });
+ assert.equal(pauses, 0);
+ });
+
+ test('an empty tile decodes to nothing', () => {
+ for (const bytes of [new Uint8Array(0), null, undefined])
+ assert.deepEqual(decodeCoverageTile(bytes, { x: 0, y: 0, z: 0 }), {
+ sequences: [],
- overview: [],
+ });
+ assert.deepEqual(
+ decodePictures(new Uint8Array(0), { x: 0, y: 0, z: 15 }, 's'),
+ [],
+ );
+ });
+
+ test('a z15 tile’s pictures of one sequence become cones; other sequences’ are skipped', () => {
+ const { tile, lon, lat } = tileCentre(2.35, 48.85, 15);
+ const bytes = encodePanoramaxTile(tile, {
+ pictures: [
+ {
+ id: 'a',
+ lon,
+ lat,
+ sequenceId: 's1',
+ heading: 45,
+ type: 'equirectangular',
+ ts: '2023-12-12 07:56:37+00',
+ },
+ { id: 'b', lon: lon + 0.0001, lat, sequenceId: 's2' },
+ { id: 'c', lon: lon + 0.0002, lat, sequenceId: 's1' },
+ ],
+ });
+ const images = decodePictures(bytes, tile, 's1');
+ assert.deepEqual(
+ images.map((i) => i.id),
+ ['a', 'c'],
+ );
+ assert.equal(images[0].compassAngle, 45);
+ assert.equal(images[0].isPano, true);
+ assert.equal(images[0].capturedAt, Date.UTC(2023, 11, 12, 7, 56, 37));
+ assert.ok(near(images[1].lon, lon + 0.0002));
+ assert.deepEqual(decodePictures(bytes, tile, 'nope'), []);
+ // A tile without pictures (below z15) has none to give.
+ const lines = encodePanoramaxTile(tile, {
+ sequences: [
+ {
+ id: 's1',
+ parts: [
+ [
+ [lon, lat],
+ [lon + 0.001, lat],
+ ],
+ ],
+ },
+ ],
+ });
+ assert.deepEqual(decodePictures(lines, tile, 's1'), []);
+ });
+
+ test('lines are simplified within a few tile units, ends and corners kept', () => {
+ const zigzag = Array.from({ length: 1000 }, (_, i) => ({
+ x: i,
+ y: i % 2 ? 1 : 0,
+ }));
+ assert.deepEqual(
+ simplifyLine(zigzag, 4),
+ [zigzag[0], zigzag.at(-1)],
+ 'a 1-unit wobble goes',
+ );
+ const corner = [
+ { x: 0, y: 0 },
+ { x: 50, y: 1 },
+ { x: 100, y: 0 },
+ { x: 100, y: 100 },
+ ];
+ assert.deepEqual(simplifyLine(corner, 4), [corner[0], corner[2], corner[3]]);
+ assert.equal(simplifyLine(corner.slice(0, 2), 4).length, 2);
+ // A loop back to its start (no chord) keeps its far point.
+ const loop = [
+ { x: 0, y: 0 },
+ { x: 40, y: 0 },
+ { x: 0, y: 0 },
+ ];
+ assert.equal(simplifyLine(loop, 4).length, 3);
+ assert.equal(simplifyLine(zigzag, 0).length, 1000, 'no tolerance, no change');
+ // A dead end: out to 100 and back to 50 keeps its far end.
+ const deadEnd = [
+ { x: 0, y: 0 },
+ { x: 100, y: 0 },
+ { x: 50, y: 0 },
+ ];
+ assert.deepEqual(simplifyLine(deadEnd, 4), deadEnd);
+ });
+
+ test('a decoded GPS track keeps a fraction of its points', () => {
+ const { tile, lon, lat } = tileCentre(2.35, 48.85);
+ const track = Array.from({ length: 500 }, (_, i) => [
+ lon - 0.004 + i * 0.000016,
+ lat + Math.sin(i / 40) * 0.0004,
+ ]);
+ const [sequence] = decodeCoverageTile(
+ encodePanoramaxTile(tile, { sequences: [{ id: 'gps', parts: [track] }] }),
+ tile,
+ ).sequences;
+ assert.ok(
+ sequence.parts[0].length < 100,
+ `${sequence.parts[0].length} points`,
+ );
+ assert.ok(sequence.parts[0].length > 5);
+ });
diff --cc src/layers/streetLevel/providers/panoramax/index.js
index 000000000,d3a3c7922..4dfa023ef
mode 000000,100644..100644
--- a/src/layers/streetLevel/providers/panoramax/index.js
+++ b/src/layers/streetLevel/providers/panoramax/index.js
@@@ -1,0 -1,644 +1,578 @@@
-import { createLineCoverage, sequenceIdFromPick } from '../../lineCoverage.js';
++import {
++ createLineCoverage,
++ freshCoverage,
++ sequenceIdFromPick,
++} from '../../lineCoverage.js';
+ import { createSequenceCones, thinImages } from '../../sequenceCones.js';
+ import { passesImageryFilter } from '../../filter.js';
-import {
- lonToTileX,
- latToTileY,
- overviewZoomForHeight,
- tileBounds,
-} from '../../tileMath.js';
++import { lonToTileX, latToTileY, tileBounds } from '../../tileMath.js';
+ import { metresBetween } from '../../view.js';
+ import { createLru, createTileCache } from '../../tileCache.js';
+ import { decodeCoverageTileSliced, decodePictures } from './decode.js';
+ import { createPanoramaxSource } from './source.js';
+ import { createPanoramaxViewer } from './viewer.js';
+ import { msg } from '../../../../i18n/index.js';
+ import {
+ COLORS,
+ COVERAGE_LINES_BELOW_M,
+ COVERAGE_TUNING,
+ COVERAGE_Z11_BELOW_M,
+ COVERAGE_Z12_BELOW_M,
+ COVERAGE_Z13_BELOW_M,
+ COVERAGE_Z14_BELOW_M,
+ GONE_MESSAGE,
+ LINE_CLICK_HINT,
+ LINE_CLICK_RADIUS_MAX_M,
+ LINE_CLICK_RADIUS_PER_HEIGHT,
+ NEAREST_LIMIT,
+ NEAREST_RADIUS_M,
+ FILTERED_HINT,
+ NO_COVERAGE_HINT,
- OVERVIEW_HINT,
+ PANORAMAX_CREDIT_HTML,
+ PANORAMAX_LABEL,
+ PANORAMAX_NAME,
+ PANORAMAX_PROVIDER_ID,
+ PICK_PREFIX,
+ PICTURE_TILE_EDGE_M,
+ PICTURE_TILE_ZOOM,
+ RATE_LIMITED_MESSAGE,
+ UNREADABLE_TILE_MESSAGE,
++ ZOOM_IN_HINT,
+ normalizeItem,
+ } from './policy.js';
+
+ export { PANORAMAX_PROVIDER_ID } from './policy.js';
+
+ /**
+ * A tile's bytes decoded by `decode`; a body that is not a vector tile
+ * (an HTML error page, a cut-off answer) reads as such, not as a parser's
+ * "Unimplemented type: 4".
+ */
+ async function readable(decode) {
+ try {
+ return await decode();
+ } catch (error) {
+ if (error?.name === 'AbortError' || error?.status !== undefined)
+ throw error;
+ throw new Error(UNREADABLE_TILE_MESSAGE);
+ }
+ }
+
-/**
- * A density dot's size: busier places draw bigger (2.5 px for one picture,
- * 8 px from a few hundred thousand), so a city does not read like farmland.
- */
-export function overviewPointSize(point) {
- const weight = Math.max(1, Number(point?.weight) || 1);
- return Math.min(8, 2.5 + Math.log10(weight));
-}
-
+ /** Pictures kept in memory by id (lookups and ‹ › fill it). */
+ const PHOTO_CACHE_SIZE = 2000;
+ /** Sequences whose cone centre is remembered. */
+ const ANCHOR_CACHE_SIZE = 50;
+ /** Decoded coverage tiles kept (a simplified dense z10 tile is ~4 MB). */
+ const COVERAGE_TILE_CACHE_SIZE = 16;
+ /** One sequence's pictures in a z15 tile, kept for re-centring. */
+ const PICTURE_LIST_CACHE_SIZE = 32;
+
+ /**
- * Sequence lines at z10–14 below 60 km; above, the density grid at z5 and
- * coarser.
++ * Sequence lines at z10–14 below 60 km; above, nothing is drawn (the hint
++ * says to zoom in).
+ */
+ export function panoramaxZoomFor(heightM) {
- if (!Number.isFinite(heightM)) return null;
- if (heightM <= COVERAGE_LINES_BELOW_M) {
- const zoom =
- heightM <= COVERAGE_Z14_BELOW_M
- ? 14
- : heightM <= COVERAGE_Z13_BELOW_M
- ? 13
- : heightM <= COVERAGE_Z12_BELOW_M
- ? 12
- : heightM <= COVERAGE_Z11_BELOW_M
- ? 11
- : 10;
- return { zoom, kind: 'sequence' };
- }
- return {
- zoom: Math.min(5, overviewZoomForHeight(heightM) ?? 5),
- kind: 'overview',
- };
++ if (!Number.isFinite(heightM) || heightM > COVERAGE_LINES_BELOW_M)
++ return null;
++ return heightM <= COVERAGE_Z14_BELOW_M
++ ? 14
++ : heightM <= COVERAGE_Z13_BELOW_M
++ ? 13
++ : heightM <= COVERAGE_Z12_BELOW_M
++ ? 12
++ : heightM <= COVERAGE_Z11_BELOW_M
++ ? 11
++ : 10;
+ }
+
+ /**
- * The imagery filter for lines and grid cells. A cell (undated, with 360°
- * and flat counts) stays while it holds pictures of the kind asked for. A
- * line is dated by its sequence's first day, so a sequence still growing
- * may hide under "since" while its newer pictures can be opened; a line
- * with no camera type or no day is kept (a click finds out).
++ * The imagery filter for lines. A line is dated by its sequence's first
++ * day, so a sequence still growing may hide under "since" while its newer
++ * pictures can be opened; a line with no camera type or no day is kept (a
++ * click finds out).
+ */
+ export function passesCoverage(record, filter) {
+ if (!filter) return true;
- if ('hasPano' in record) {
- if (filter.pano === 'pano') return record.hasPano;
- if (filter.pano === 'flat') return record.hasFlat;
- return true;
- }
+ return passesImageryFilter(record, {
+ pano: typeof record.isPano === 'boolean' ? filter.pano : 'all',
+ sinceMs: record.capturedAt ? filter.sinceMs : null,
+ });
+ }
+
+ /** The z15 tile holding a point. */
+ function pictureTileOf({ lon, lat }) {
+ const z = PICTURE_TILE_ZOOM;
+ return { x: lonToTileX(lon, z), y: latToTileY(lat, z), z };
+ }
+
+ /**
+ * The z15 tiles whose pictures surround a point: its own first, and the
+ * neighbours it sits within PICTURE_TILE_EDGE_M of (at most nine).
+ */
+ export function pictureTilesAround(point) {
+ const home = pictureTileOf(point);
+ const box = tileBounds(home.x, home.y, home.z);
+ const near = (lon, lat) =>
+ metresBetween(point, { lon, lat }) <= PICTURE_TILE_EDGE_M;
+ // Near both edges at once where tiles are narrow (high latitudes).
+ const dxs = [0];
+ if (near(box.west, point.lat)) dxs.push(-1);
+ if (near(box.east, point.lat)) dxs.push(1);
+ const dys = [0];
+ if (near(point.lon, box.north)) dys.push(-1);
+ if (near(point.lon, box.south)) dys.push(1);
+ const max = 2 ** home.z;
+ const tiles = [];
+ for (const dy of dys)
+ for (const dx of dxs) {
+ const y = home.y + dy;
+ if (y < 0 || y >= max) continue;
+ tiles.push({ x: (home.x + dx + max) % max, y, z: home.z });
+ }
+ return tiles;
+ }
+
+ const tileKey = ({ x, y, z }) => `${z}/${x}/${y}`;
+
+ /**
+ * Panoramax Street Level provider: the federated, keyless, open
- * street-level commons. Coverage from its vector tiles (density points
- * from orbit, sequence lines near the ground); a click on a line opens that
++ * street-level commons. Coverage from its vector tiles (sequence lines
++ * near the ground, nothing from orbit); a click on a line opens that
+ * sequence's picture nearest the click, with cones along the sequence
+ * around it and ‹ › to step through it. Flat pictures show as photos, 360°
+ * ones on the shared WebGL panorama.
+ * @param {{source?: ReturnType<typeof createPanoramaxSource>, viewerOptions?: object}} [options]
+ * @returns {import('../../registry.js').StreetLevelProvider}
+ */
+ export function createPanoramaxProvider({
+ source = createPanoramaxSource(),
+ viewerOptions = {},
+ } = {}) {
+ return Object.freeze({
+ id: PANORAMAX_PROVIDER_ID,
+ name: PANORAMAX_NAME,
+ label: PANORAMAX_LABEL,
+ requiresKeyId: null,
+ pickPrefix: PICK_PREFIX.root,
+ colors: COLORS,
+ credit: Object.freeze({ html: PANORAMAX_CREDIT_HTML }),
+ defaultOn: false,
+ coverageLabel: Object.freeze({
+ noun: 'sequences',
+ action: LINE_CLICK_HINT,
+ }),
+
+ create(context) {
+ const state = {
+ context,
+ services: context.services,
+ viewer: null,
- keyRequired: false,
- keyRejected: false,
- statusKnown: true,
- coverage: {
- zoom: null,
- tiles: new Map(),
- stale: new Map(),
- staleTimer: null,
- pending: new Map(),
- lastError: null,
- holdUntil: 0,
- holdTimer: null,
- debounceTimer: null,
- removeCameraListener: null,
- terrainReady: null,
- hint: '',
- kind: null,
- },
++ coverage: freshCoverage({ keyless: true }),
+ sequence: {
+ selectedId: null,
+ images: [],
- cache: new Map(),
+ collection: null,
+ loading: false,
++ error: null,
+ abort: null,
+ },
+ };
+ const photos = createLru(PHOTO_CACHE_SIZE);
+ /** Where each sequence's cones centre: the picture last opened in it, or a click. */
+ const anchors = createLru(ANCHOR_CACHE_SIZE);
+ /** The z15 tiles the cones were drawn from. */
+ let drawn = null;
+ /** A line click: its sequence's pictures win the next nearest lookup there. */
+ let preferred = null;
+
+ function remember(item) {
+ const photo = normalizeItem(item);
+ if (photo) photos.set(photo.id, photo);
+ return photo;
+ }
+
+ /**
+ * Lookups in flight, shared: ‹ › and the viewer ask for the same
+ * picture. A lookup stops once every caller waiting on it has given up
+ * (its search would hold one of the two API connections for nothing).
+ */
+ const inflight = new Map();
+ function getPhoto(photoId, { signal } = {}) {
+ const id = String(photoId);
+ const cached = photos.get(id);
+ if (cached) return Promise.resolve(cached);
+ if (signal?.aborted) return Promise.reject(signal.reason);
+ let lookup = inflight.get(id);
+ if (!lookup) {
+ const controller = new AbortController();
+ lookup = { controller, waiting: 0 };
+ lookup.promise = source
+ .getItem(id, { signal: controller.signal })
+ .catch((error) => {
+ // Ids are UUIDs: the API answers 400 to anything else.
+ if (error?.status === 400) return null;
+ throw error;
+ })
+ .then((item) => {
+ const photo = item && remember(item);
+ if (!photo) throw new Error(GONE_MESSAGE);
+ return photo;
+ })
+ .finally(() => {
+ if (inflight.get(id) === lookup) inflight.delete(id);
+ });
+ lookup.promise.catch(() => {});
+ inflight.set(id, lookup);
+ }
+ const shared = lookup;
+ shared.waiting++;
+ if (!signal) shared.waiting = Infinity;
+ return new Promise((resolve, reject) => {
+ const leave = () => {
+ reject(signal.reason);
+ shared.waiting--;
+ // A caller in the same tick (the same photo opened again) may
+ // still join: stop only if nobody has.
+ queueMicrotask(() => {
+ if (shared.waiting > 0) return;
+ shared.controller.abort(signal.reason);
+ if (inflight.get(id) === shared) inflight.delete(id);
+ });
+ };
+ signal?.addEventListener('abort', leave, { once: true });
+ shared.promise.then(
+ (photo) => {
+ signal?.removeEventListener('abort', leave);
+ resolve(photo);
+ },
+ (error) => {
+ signal?.removeEventListener('abort', leave);
+ reject(error);
+ },
+ );
+ });
+ }
+
+ /**
+ * How far from a line click its sequence's pictures are looked for:
+ * from high up the click may land tens of metres off the line.
+ */
+ function lineClickRadius() {
+ const height = state.viewer?.camera?.positionCartographic?.height;
+ if (!Number.isFinite(height)) return NEAREST_RADIUS_M;
+ return Math.min(
+ LINE_CLICK_RADIUS_MAX_M,
+ Math.max(NEAREST_RADIUS_M, height * LINE_CLICK_RADIUS_PER_HEIGHT),
+ );
+ }
+
+ /** The picture `delta` along its sequence, from its own links (null at an end). */
+ async function step(photo, delta) {
+ if (!photo?.sequenceId) return null;
+ return (delta < 0 ? photo.prevId : photo.nextId) || null;
+ }
+
+ // Decoded tiles, kept a while: panning back, or across a zoom band and
+ // back, neither fetches nor decodes them again.
+ const coverageTiles = createTileCache({
+ size: COVERAGE_TILE_CACHE_SIZE,
+ load: (tile, { signal }) =>
+ readable(async () =>
+ decodeCoverageTileSliced(
+ await source.getTile(tile, { signal }),
+ tile,
+ { signal },
+ ),
+ ),
+ });
+ /** A z15 tile's pictures of one sequence, by `z/x/y:sequence`. */
+ const pictureLists = createLru(PICTURE_LIST_CACHE_SIZE);
+ /**
+ * Only finished lists are kept: a load in flight belongs to its own
+ * selection, whose abort (a re-centre) must not empty the next one's.
+ */
+ async function picturesIn(tile, sequenceId, signal) {
+ const key = `${tileKey(tile)}:${sequenceId}`;
+ const kept = pictureLists.get(key);
+ if (kept) return kept;
+ const list = await readable(async () =>
+ decodePictures(
+ await source.getTile(tile, { signal, lane: 'pictures' }),
+ tile,
+ sequenceId,
+ ),
+ );
+ pictureLists.set(key, list);
+ return list;
+ }
+
+ const coverage = createLineCoverage({
+ state,
+ fetchTile: (tile, options) => coverageTiles.get(tile, options),
+ zoomFor: panoramaxZoomFor,
+ colors: COLORS,
+ pickPrefix: PICK_PREFIX.sequence,
+ renderKey: 'panoramax-coverage',
+ tuning: COVERAGE_TUNING,
- messages: { rateLimited: RATE_LIMITED_MESSAGE },
++ messages: { rateLimited: RATE_LIMITED_MESSAGE, tooHigh: ZOOM_IN_HINT },
+ passes: passesCoverage,
- overviewPointSize,
+ });
+
+ const cones = createSequenceCones({
+ state,
+ async loadImages(sequenceId, { signal }) {
+ const anchor = anchors.get(sequenceId);
+ if (!anchor) return [];
+ const tiles = pictureTilesAround(anchor);
+ // Known from the start: a picture opening while these load is
+ // judged against them (re-centred if outside, left alone inside).
+ const covering = { sequenceId, tiles: new Set(tiles.map(tileKey)) };
+ drawn = covering;
+ const conesOf = (lists) =>
+ thinImages(
+ [
+ ...new Map(
+ lists.flat().map((image) => [image.id, image]),
+ ).values(),
+ ].sort((a, b) => a.capturedAt - b.capturedAt),
+ );
+ const keyOf = (tile) => `${tileKey(tile)}:${sequenceId}`;
+ // The home tile is needed now (it holds the open picture).
+ const home = await picturesIn(tiles[0], sequenceId, signal);
+ signal?.throwIfAborted();
+ // Neighbours already read draw with it; the rest (each up to
+ // 1.4 MB in central Paris) join the cones as they arrive.
+ const neighbours = tiles.slice(1);
+ const kept = neighbours
+ .map((tile) => pictureLists.get(keyOf(tile)))
+ .filter(Boolean);
+ const missing = neighbours.filter(
+ (tile) => !pictureLists.get(keyOf(tile)),
+ );
+ if (missing.length)
+ Promise.allSettled(
+ missing.map((tile) => picturesIn(tile, sequenceId, signal)),
+ ).then((lists) => {
+ if (signal?.aborted || drawn !== covering) return;
+ dropFailed(covering, missing, lists);
+ // Only a tile that arrived now redraws (no loop on failures).
+ if (lists.some((list) => list.status === 'fulfilled'))
+ cones.select(sequenceId, { force: true });
+ });
+ return conesOf([home, ...kept]);
+ },
+ colors: COLORS,
+ pickPrefix: PICK_PREFIX.image,
+ spriteId: 'street-level:panoramax-cones',
+ renderKey: 'panoramax-sequence',
- onHighlight: (sequenceId, selected) =>
- coverage.recolorSequence(sequenceId, selected),
++ onHighlight: (sequenceId) => coverage.highlight(sequenceId),
+ });
+
+ /**
+ * A tile that failed is not covered: a picture opening in it later
+ * re-centres the cones there (and asks for the tile again).
+ */
+ function dropFailed(covering, tiles, lists) {
+ lists.forEach((list, i) => {
+ if (list.status === 'rejected')
+ covering.tiles.delete(tileKey(tiles[i]));
+ });
+ }
+
+ /**
+ * The cones show the z15 tiles around one picture: once a picture of
+ * the selected sequence opens outside them (‹ ›, a cone), re-centre.
+ */
+ function recentreCones(photo) {
+ if (!photo?.sequenceId) return;
+ if (state.sequence.selectedId !== photo.sequenceId) return;
+ if (drawn?.sequenceId !== photo.sequenceId) return;
+ if (drawn.tiles.has(tileKey(pictureTileOf(photo)))) return;
+ cones.select(photo.sequenceId, { force: true });
+ }
+
+ const viewer = createPanoramaxViewer({
+ getPhoto,
+ // The cones centre on the picture actually shown, never on a
+ // lookup that came back after the user moved on.
+ onShowing: (photo) => {
+ if (photo.sequenceId) anchors.set(photo.sequenceId, photo);
+ },
+ // After a GPU reset the same picture is drawn again by the viewer
+ // itself: through the core it would cancel a lookup the user
+ // started. A failure still shows.
+ onReopen: (photoId) =>
+ viewer
+ .open(photoId)
+ .catch((error) =>
+ context.actions.reportError(
+ error?.message ||
+ msg('The Panoramax photo could not be loaded'),
+ ),
+ ),
+ step,
+ onStep: (photoId) =>
+ context.actions.openImage(photoId, { frame: false }),
+ onShown: recentreCones,
+ // Esc in the viewer clears the selected sequence, as the panel says.
+ onEscape: () => {
+ if (!state.sequence.selectedId) return false;
+ cones.clearSelection();
+ drawn = null;
+ return true;
+ },
+ render: context.services?.render,
+ ...viewerOptions,
+ });
+
+ /** Nearest of `items` within `radius` metres of a point, or null. */
+ function nearestOf(items, point, radius = NEAREST_RADIUS_M) {
+ let best = null;
+ for (const item of items) {
+ const photo = remember(item);
+ if (!photo) continue;
+ const metres = metresBetween(point, photo);
+ if (metres > radius) continue;
+ if (!best || metres < best.metres) best = { photo, metres };
+ }
+ return best?.photo ?? null;
+ }
+
+ return {
+ async status() {
+ return { configured: true };
+ },
+
+ init(cesiumViewer) {
+ state.viewer = cesiumViewer;
+ cones.ensureCollections(cesiumViewer);
+ cones.setVisible(false);
+ },
+
+ activate(cesiumViewer) {
+ state.viewer = cesiumViewer;
+ cones.setVisible(true);
+ coverage.attach(cesiumViewer);
+ },
+
+ deactivate() {
+ coverage.detach();
+ coverage.clear();
- coverage.resetErrors();
++ coverage.unblock();
+ cones.clearSelection();
+ cones.setVisible(false);
+ drawn = null;
+ preferred = null;
+ // Off: decoded tiles and lists go (several MB each over a city).
+ coverageTiles.clear();
+ pictureLists.clear();
+ },
+
+ destroy(cesiumViewer) {
+ coverage.detach();
+ coverage.clear();
- coverage.resetErrors();
++ coverage.unblock();
+ cones.destroy(cesiumViewer);
+ },
+
- refreshCoverage: () => coverage.refresh(),
-
+ /** The filter changed: redraw. Each draw reads it from the context. */
+ setFilter() {
+ coverage.rebuild();
+ cones.rerender();
+ },
+
- setSurface() {
- coverage.setSurface();
- cones.rerender();
- },
-
+ coverageStats() {
- const { kind } = state.coverage;
- const lines = kind === 'sequence';
- const shown = coverage.sequenceCount();
- // Density dots are not sequences: they are not counted as such.
- const count = lines ? shown : 0;
- const loading = state.coverage.pending.size > 0;
- const settled = !loading && !state.coverage.lastError;
++ const stats = coverage.stats();
+ let fallback = '';
- // Tiles that held something the filter hid all of.
- const filteredOut = [...state.coverage.tiles.values()].some(
- (tile) => tile.total > 0,
- );
- if (kind === 'overview')
- fallback =
- shown > 0 || !settled
- ? OVERVIEW_HINT
- : filteredOut
- ? FILTERED_HINT
- : NO_COVERAGE_HINT;
- else if (lines && settled && count === 0)
++ // Lines drawn for the camera (a zoom), all settled, none shown.
++ const settled =
++ state.coverage.zoom != null && !stats.loading && !stats.error;
++ if (settled && stats.count === 0) {
++ // Tiles that held lines the filter hid all of.
++ const filteredOut = [...state.coverage.tiles.values()].some(
++ (tile) => tile.total > 0,
++ );
+ fallback = filteredOut ? FILTERED_HINT : NO_COVERAGE_HINT;
- return {
- count,
- zoom: state.coverage.zoom,
- kind: state.coverage.kind,
- loading,
- hint: state.coverage.hint || fallback,
- error: state.coverage.lastError,
- keyRequired: false,
- keyRejected: false,
- };
++ }
++ return { ...stats, hint: stats.hint || fallback };
+ },
+
+ /**
+ * A line opens its sequence's picture nearest the click (the cones
+ * follow once it is on screen); a cone opens its picture.
+ */
+ handlePick(pickId, { groundPoint } = {}) {
+ if (pickId.startsWith(PICK_PREFIX.image)) {
+ context.actions.openImage(pickId.slice(PICK_PREFIX.image.length));
+ return true;
+ }
+ const sequenceId = sequenceIdFromPick(pickId, PICK_PREFIX.sequence);
+ if (!sequenceId) return false;
+ const point = groundPoint?.();
+ // No ground under the click (the sky beyond a line): nothing to open.
+ if (!point) return true;
+ anchors.set(sequenceId, { ...point, sequenceId });
+ preferred = {
+ sequenceId,
+ lon: point.lon,
+ lat: point.lat,
+ radius: lineClickRadius(),
+ };
+ context.actions.openNearest(point);
+ return true;
+ },
+
+ selectSequence: (sequenceId) =>
+ cones.select(sequenceId, { force: true }),
+ clearSequence: () => {
+ cones.clearSelection();
+ drawn = null;
+ },
+ sequenceStats: () => ({
+ selectedId: state.sequence.selectedId,
+ images: state.sequence.images.length,
+ loading: state.sequence.loading,
++ error: state.sequence.error,
+ }),
+
+ /**
+ * The nearest picture within the search radius that passes the
+ * imagery filter, or null. After a click on a line, that line's
+ * sequence is asked first.
+ */
+ async nearestImage({ lat, lon }, { signal } = {}) {
+ const point = { lat, lon };
+ const filter = context.getFilter();
+ // Only the lookup the click itself asked for (the same point).
+ const wanted =
+ preferred && metresBetween(preferred, point) < 1 ? preferred : null;
+ preferred = null;
+ const ask = (collections, radius = NEAREST_RADIUS_M) =>
+ source.nearestItems(
+ {
+ lat,
+ lon,
+ radius,
+ limit: NEAREST_LIMIT,
+ collections,
+ pano: filter.pano,
+ sinceMs: filter.sinceMs,
+ },
+ { signal },
+ );
+ if (wanted) {
+ const hit = nearestOf(
+ await ask(wanted.sequenceId, wanted.radius),
+ point,
+ wanted.radius,
+ );
+ if (hit) return hit.id;
+ }
+ return nearestOf(await ask(null), point)?.id ?? null;
+ },
+
+ viewer,
+ };
+ },
+ });
+ }
diff --cc src/layers/streetLevel/providers/panoramax/policy.js
index 000000000,55036cb32..e9a51c10e
mode 000000,100644..100644
--- a/src/layers/streetLevel/providers/panoramax/policy.js
+++ b/src/layers/streetLevel/providers/panoramax/policy.js
@@@ -1,0 -1,322 +1,312 @@@
+ import { COLORS as SHARED_COLORS, PROVIDER_COLORS } from '../../policy.js';
+ import { msg } from '../../../../i18n/index.js';
+
+ export { NEAREST_RADIUS_M } from '../../policy.js';
+
+ /** Identity and tuning for the Panoramax street-level provider (keyless). */
+ export const PANORAMAX_PROVIDER_ID = 'panoramax';
+ export const PANORAMAX_NAME = 'Panoramax';
+ export const PANORAMAX_LABEL = 'PANORAMAX';
+
+ /**
+ * The Panoramax meta-catalogue: one keyless, CORS-enabled STAC API over
+ * every federated instance (OpenStreetMap France, IGN, MapComplete…). Its
+ * pictures are served by the instance that holds them.
+ */
+ export const PANORAMAX_API = 'https://api.panoramax.xyz/api';
+ /** The meta-catalogue's web viewer, where the caption link goes. */
+ export const PANORAMAX_VIEWER = 'https://api.panoramax.xyz/';
+
+ /** Stable id prefixes for picked primitives; every one starts with `pnx:`. */
+ export const PICK_PREFIX = Object.freeze({
+ root: 'pnx:',
+ sequence: 'pnx:seq:',
+ image: 'pnx:img:',
+ });
+
+ export const COLORS = Object.freeze({
+ coverage: PROVIDER_COLORS.panoramax,
+ selected: SHARED_COLORS.selected,
+ });
+
+ /**
+ * Sequence lines come from z7–15 tiles; z10–14 are drawn below 60 km, as
+ * Mapillary's are (a dense tile over Paris: z10 ~2.1 MB and 8,600
- * sequences, z11 ~1.4 MB, z12 ~800 kB). Higher up, the z0–5 `grid` layer's
- * density cells (0.1°, ~10 km) draw as points: lower down they would be a
- * handful of dots over a whole city, which reads as no coverage.
++ * sequences, z11 ~1.4 MB, z12 ~800 kB). Higher up nothing is drawn.
+ */
+ export const COVERAGE_Z14_BELOW_M = 1_800;
+ export const COVERAGE_Z13_BELOW_M = 5_000;
+ export const COVERAGE_Z12_BELOW_M = 12_000;
+ export const COVERAGE_Z11_BELOW_M = 30_000;
+ export const COVERAGE_LINES_BELOW_M = 60_000;
+ export const COVERAGE_TUNING = Object.freeze({
+ maxTiles: 9,
- overviewMaxTiles: 6,
+ // Each tile draws at most 1,600 lines, its longest first (as decoded,
+ // `keepOrder`): a dense z11
+ // tile over Paris holds 3,800, and a lower cap left the city centre
+ // looking emptier than its suburbs. (KartaView draws as many.)
+ maxSequences: 14_400,
+ keepOrder: true,
- // Points drawn at most, over every tile (each becomes ~8 ground-line
- // vertices, ~1.4 kB of geometry): the simplified Paris z10 tile alone
- // holds 57,000, unsimplified 750,000, which hung the tab.
++ // Points drawn at most, over every tile, a ninth of it a tile (each
++ // becomes ~8 ground-line vertices, ~1.4 kB of geometry): the simplified
++ // Paris z10 tile alone holds 57,000, unsimplified 750,000, which hung
++ // the tab.
+ maxPoints: 90_000,
+ lineWidthPx: 2.5,
- overviewPointPx: 4,
+ moveDebounceMs: 320,
+ viewRangeMinM: 2_500,
+ viewRangePerHeight: 10,
- viewNearM: 1_000,
+ });
+ /**
+ * Lines are simplified (Douglas–Peucker) to this many tile units of a
+ * 4,096 extent: about a pixel where each zoom is drawn (1.6 m at z14,
+ * within GPS noise), and 6–10% of the points GPS tracks carry.
+ */
+ export const SIMPLIFY_TOLERANCE_UNITS = 4;
+
+ /**
+ * Coverage tiles decode in slices of this many ms, the page getting a turn
+ * between them (decode.js `decodeCoverageTileSliced`): under a frame.
+ */
+ export const DECODE_SLICE_MS = 8;
+
-/**
- * Grid cells per overview tile, at most: a z0 tile holds ~70,000 cells
- * (1.9 MB), drawn as this many binned points.
- */
-export const OVERVIEW_BINS_PER_AXIS = 96;
-
+ export const RATE_LIMITED_MESSAGE = msg(
+ 'Panoramax is busy — coverage resumes on its own',
+ );
+ export const NO_COVERAGE_HINT = msg('no Panoramax photos in view');
+ /** Lines in view, all hidden by the imagery filter. */
+ export const FILTERED_HINT = msg('no Panoramax photos here match the filters');
+ export const UNREADABLE_TILE_MESSAGE = msg(
+ 'Panoramax sent a map tile that could not be read',
+ );
+ export const GONE_MESSAGE = msg('This Panoramax photo is no longer available');
-/** From high up the dots are where pictures are, not sequences to click. */
-export const OVERVIEW_HINT = msg('zoom in to see Panoramax coverage');
++/** Above the line ceiling nothing is drawn. */
++export const ZOOM_IN_HINT = msg('zoom in to see Panoramax coverage');
+
+ /** Cones come from z15 tiles' `pictures` layer (~110 bytes a picture). */
+ export const PICTURE_TILE_ZOOM = 15;
+ /** Within this of a z15 tile's edge, the neighbouring tile's pictures join. */
+ export const PICTURE_TILE_EDGE_M = 150;
+
+ export const TILE_TIMEOUT_MS = 20_000;
+ /**
+ * Once an answer has started, it may take as long as it keeps coming: a
+ * 2 MB tile on a slow link outlasts any whole-request timeout, so only a
+ * stream silent this long is given up.
+ */
+ export const STREAM_IDLE_TIMEOUT_MS = 15_000;
+ /** Busy (429/503) without a Retry-After the browser can read: back off from this. */
+ export const BUSY_BACKOFF_BASE_SEC = 5;
+ export const API_TIMEOUT_MS = 12_000;
+ /** Real tiles are under 6 MB (z6 over France); refuse anything absurd. */
+ export const MAX_RESPONSE_BYTES = 16 * 1024 * 1024;
+ /**
+ * The meta-catalogue speaks HTTP/1.1 only, so the browser opens six
+ * connections to it: coverage tiles take three, searches two and the
+ * cones' tiles one, so a click's lookup never queues behind megabyte tiles
+ * (it timed out doing so).
+ */
+ export const API_CONCURRENCY = 2;
+ export const TILE_CONCURRENCY = 3;
+ /** The selected sequence's z15 tiles (cones) take the sixth. */
+ export const PICTURE_TILE_CONCURRENCY = 1;
+
+ /** Pictures asked for around a point; the API returns them nearest first. */
+ export const NEAREST_LIMIT = 10;
+ /**
+ * The widest the API allows: the point may be beside a picture, but a
+ * picture looking away from it is still left out (the bounding-box search
+ * beside it has those).
+ */
+ export const NEAREST_FOV_TOLERANCE_DEG = 180;
+ /**
+ * Pictures in the bounding box around a click, at most. The API returns
+ * them roughly nearest first (the first ten of 100 are the first ten of
+ * 10), and the browser ranks them exactly: 20 is ~60 kB, 100 ~600 kB.
+ */
+ export const NEAREST_BOX_LIMIT = 20;
+ /**
+ * A line clicked from high up may be tens of metres off the click: its
+ * sequence is searched within the camera height / 100 (50–400 m).
+ */
+ export const LINE_CLICK_RADIUS_PER_HEIGHT = 0.01;
+ export const LINE_CLICK_RADIUS_MAX_M = 400;
+
+ /** A full-resolution panorama is only fetched up to this width (memory). */
+ export const PANO_HD_MAX_WIDTH = 8_192;
+ /** An HD panorama can be several megabytes. */
+ export const HD_TIMEOUT_MS = 30_000;
+ /** Panoramax's SD derivative is 2,048 px wide, its thumbnail 500 px. */
+ export const SD_WIDTH = 2_048;
+
+ /** On-globe credit: licences are per picture, named in the caption. */
+ export const PANORAMAX_CREDIT_HTML =
+ 'Street Level: imagery © <a href="https://panoramax.fr" target="_blank" rel="noopener">Panoramax</a> contributors, licence per picture';
+
+ export const LINE_CLICK_HINT = 'click a line for its nearest photo';
+
+ /** Licence ids Panoramax uses, as the caption names them. */
+ const LICENSE_LABELS = Object.freeze({
+ 'CC-BY-SA-4.0': 'CC BY-SA 4.0',
+ 'CC-BY-4.0': 'CC BY 4.0',
+ 'CC0-1.0': 'CC0',
+ 'etalab-2.0': 'Licence Ouverte 2.0',
+ });
+
+ /** The caption's licence name for a STAC licence id, or null. */
+ export function licenseLabel(license) {
+ if (typeof license !== 'string' || !license.trim()) return null;
+ const id = license.trim();
+ if (id === 'proprietary' || id === 'other') return null;
+ return LICENSE_LABELS[id] || id.slice(0, 40);
+ }
+
+ /** Deep link to a picture in the Panoramax web viewer. */
+ export function panoramaxPictureUrl(pictureId) {
+ const id = String(pictureId ?? '').trim();
+ if (!id) return PANORAMAX_VIEWER;
+ return `${PANORAMAX_VIEWER}#${new URLSearchParams({ pic: id, focus: 'pic' })}`;
+ }
+
+ /** Epoch ms for a capture time ('2023-12-12T07:54:47+00:00', '2023-12-12 07:56:37+00'), or null. */
+ export function panoramaxTimeMs(value) {
+ if (typeof value !== 'string' || !value) return null;
+ // Tile timestamps are Postgres text: a space and an hour-only offset.
+ const iso = /\d[T ]\d/.test(value)
+ ? value
+ .replace(' ', 'T')
+ .replace(/([+-]\d{2})$/, '$1:00')
+ .replace(/\.(\d{3})\d+/, '.$1')
+ : value;
+ const ms = Date.parse(iso);
+ return Number.isFinite(ms) && ms > Date.UTC(1990, 0, 1) ? ms : null;
+ }
+
+ /** An https address, or null (asset links come from federated instances). */
+ function httpsUrl(value) {
+ try {
+ const url = new URL(String(value));
+ return url.protocol === 'https:' ? url.href : null;
+ } catch {
+ return null;
+ }
+ }
+
+ /** Last path segment of an item's `rel` link: the linked picture's id. */
+ function linkedId(item, rel) {
+ const href = item?.links?.find?.((link) => link?.rel === rel)?.href;
+ if (typeof href !== 'string') return null;
+ const id = href.split(/[?#]/)[0].split('/').filter(Boolean).pop();
+ if (!id) return null;
+ try {
+ return decodeURIComponent(id);
+ } catch {
+ // A malformed escape is no link, not a failed lookup.
+ return null;
+ }
+ }
+
+ /**
+ * An email address anywhere in a name, at any of its '@'s. Linear: names
+ * come from any instance, and each run between '@'s is scanned once.
+ */
+ function looksLikeEmail(name) {
+ return /[^\s@]@[^\s@]+\.[^\s@]/.test(name);
+ }
+
+ /**
+ * Who took the picture. Producers are account names, and some accounts
+ * are named by an email address: those are not repeated in the caption.
+ */
+ function creatorOf(item) {
+ const props = item.properties || {};
+ const names = [
+ props['geovisio:producer'],
+ ...(Array.isArray(item.providers)
+ ? item.providers
+ .filter((p) => p?.roles?.includes?.('producer'))
+ .map((p) => p.name)
+ : []),
+ ];
+ // Every producer is credited (an uploading app and its photographer),
+ // each name once, none that is an email address.
+ const credited = [];
+ const seen = new Set();
+ for (const value of names) {
+ if (typeof value !== 'string') continue;
+ const name = value.trim().slice(0, 80);
+ if (!name || looksLikeEmail(value)) continue;
+ const key = name.toLowerCase();
+ if (seen.has(key)) continue;
+ seen.add(key);
+ credited.push(name);
+ }
+ return credited.length ? credited.join(', ').slice(0, 120) : null;
+ }
+
+ /** The federated instance holding a picture (its `via` link's host), or null. */
+ function instanceOf(item) {
+ const href = item?.links?.find?.((link) => link?.rel === 'via')?.href;
+ try {
+ const url = new URL(String(href));
+ return url.protocol === 'https:' ? url.hostname.slice(0, 80) : null;
+ } catch {
+ return null;
+ }
+ }
+
+ /** A 360° picture: a full-sphere field of view or an equirectangular projection. */
+ export function isEquirectangular(item) {
+ const props = item?.properties || {};
+ const orientation = props['pers:interior_orientation'];
+ if (Number(orientation?.field_of_view) >= 360) return true;
+ return props['pers:projection'] === 'equirectangular';
+ }
+
+ /**
+ * A STAC item (from search or a collection) in the shape the provider and
+ * viewer use, or null without an id or a position.
+ * @returns {{id: string, sequenceId: string|null, lon: number, lat: number, heading: number|null, isPano: boolean, capturedAt: number|null, creator: string|null, license: string|null, width: number|null, prevId: string|null, nextId: string|null, urls: {thumb: string|null, sd: string|null, hd: string|null}}|null}
+ */
+ export function normalizeItem(item) {
+ if (!item || item.id == null) return null;
+ // Only numbers: Number(null) and Number('') would put a picture at 0,0.
+ const [lon, lat] = Array.isArray(item.geometry?.coordinates)
+ ? item.geometry.coordinates.map((value) =>
+ typeof value === 'number' ? value : NaN,
+ )
+ : [NaN, NaN];
+ if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null;
+ if (Math.abs(lat) > 90 || Math.abs(lon) > 180) return null;
+ const props = item.properties || {};
+ const assets = item.assets || {};
+ const azimuth =
+ props['view:azimuth'] === '' || props['view:azimuth'] == null
+ ? NaN
+ : Number(props['view:azimuth']);
+ const width = Number(
+ props['pers:interior_orientation']?.sensor_array_dimensions?.[0],
+ );
+ return {
+ id: String(item.id),
+ sequenceId: item.collection != null ? String(item.collection) : null,
+ lon,
+ lat,
+ heading: Number.isFinite(azimuth) ? ((azimuth % 360) + 360) % 360 : null,
+ isPano: isEquirectangular(item),
+ capturedAt: panoramaxTimeMs(props.datetime),
+ creator: creatorOf(item),
+ // Licences ask for the source to be named: where no author can be
+ // named, the caption names the instance holding the picture.
+ via: instanceOf(item),
+ license: licenseLabel(props.license),
+ width: Number.isFinite(width) && width > 0 ? width : null,
+ prevId: linkedId(item, 'prev'),
+ nextId: linkedId(item, 'next'),
+ urls: {
+ thumb: httpsUrl(assets.thumb?.href),
+ sd: httpsUrl(assets.sd?.href),
+ hd: httpsUrl(assets.hd?.href),
+ },
+ };
+ }
diff --cc src/layers/streetLevel/providers/panoramax/provider.test.mjs
index 000000000,4bee380ae..628805ce1
mode 000000,100644..100644
--- a/src/layers/streetLevel/providers/panoramax/provider.test.mjs
+++ b/src/layers/streetLevel/providers/panoramax/provider.test.mjs
@@@ -1,0 -1,1246 +1,1184 @@@
+ import assert from 'node:assert/strict';
+ import test from 'node:test';
+ import {
+ createPanoramaxProvider,
- overviewPointSize,
+ panoramaxZoomFor,
+ passesCoverage,
+ pictureTilesAround,
+ } from './index.js';
+ import {
+ FILTERED_HINT,
+ NO_COVERAGE_HINT,
- OVERVIEW_HINT,
+ PICK_PREFIX,
++ ZOOM_IN_HINT,
+ } from './policy.js';
+ import { validateProviders } from '../../registry.js';
+ import { tileBounds } from '../../tileMath.js';
+ import { fakeHost, until } from '../../../../testSupport/kartaViewFakes.mjs';
+ import {
+ coverageViewer,
+ tileCentre,
+ } from '../../../../testSupport/streetLevelFakes.mjs';
+ import {
+ encodePanoramaxTile,
+ stacItem,
+ } from '../../../../testSupport/panoramaxFixtures.mjs';
+
+ const ORIGIN = { lon: 2.3495, lat: 48.8874 };
+ /** A point `metres` east of ORIGIN. */
+ const east = (metres) => ({
+ lon: ORIGIN.lon + metres / 73_300,
+ lat: ORIGIN.lat,
+ });
+
+ /**
+ * A sequence `seq` of `count` pictures 5 m apart heading east from ORIGIN
+ * (`offset` m in), each linked to its neighbours.
+ */
+ function sequence(seq, count, { offset = 0, pano = false } = {}) {
+ return Array.from({ length: count }, (_, i) => {
+ const at = east(offset + i * 5);
+ return stacItem({
+ id: `${seq}-${i}`,
+ sequenceId: seq,
+ ...at,
+ pano,
+ prevId: i ? `${seq}-${i - 1}` : null,
+ nextId: i < count - 1 ? `${seq}-${i + 1}` : null,
+ });
+ });
+ }
+
+ /** A source over `items`, answering nearest lookups by distance, recording calls. */
+ function fakeSource({ items = [], tiles = () => new Uint8Array(0) } = {}) {
+ const calls = { nearest: [], items: [], tiles: [] };
+ const metres = (a, b) =>
+ Math.hypot((a.lon - b.lon) * 73_300, (a.lat - b.lat) * 111_200);
+ return {
+ calls,
+ getTile: async (tile) => {
+ calls.tiles.push(`${tile.z}/${tile.x}/${tile.y}`);
+ return tiles(tile);
+ },
+ getItem: async (id) => {
+ calls.items.push(id);
+ return items.find((item) => item.id === id) ?? null;
+ },
+ nearestItems: async (query) => {
+ calls.nearest.push(query);
+ const at = { lon: query.lon, lat: query.lat };
+ return items
+ .filter(
+ (item) => !query.collections || item.collection === query.collections,
+ )
+ .map((item) => ({
+ item,
+ d: metres(at, {
+ lon: item.geometry.coordinates[0],
+ lat: item.geometry.coordinates[1],
+ }),
+ }))
+ .filter(({ d }) => d <= query.radius)
+ .sort((a, b) => a.d - b.d)
+ .slice(0, query.limit)
+ .map(({ item }) => item);
+ },
+ };
+ }
+
+ function fakeContext({ filter = { pano: 'all', sinceMs: null } } = {}) {
+ const actions = { opened: [], nearest: [], errors: [], instance: null };
+ return {
+ actions,
+ context: {
+ services: {},
+ getFilter: () => filter,
+ isActive: () => true,
- groundCaster: null,
- meshSampler: null,
- getSurface: () => 'draped',
+ notify() {},
+ actions: {
+ openImage: async (id, options) => {
+ actions.opened.push({ id, options });
+ // As the core does, errors included (a test may not mount a viewer).
+ await actions.instance?.viewer.open(id).catch((error) => {
+ actions.errors.push(error.message);
+ });
+ return true;
+ },
+ openNearest: (point) => actions.nearest.push(point),
+ reportError: (message) => actions.errors.push(message),
+ },
+ },
+ };
+ }
+
+ function setup(sourceOptions, contextOptions) {
+ const source = fakeSource(sourceOptions);
+ const loads = [];
+ const definition = createPanoramaxProvider({
+ source,
+ viewerOptions: {
+ load: async (url) => {
+ loads.push(url);
+ return { src: url };
+ },
+ createRenderer: () => {
+ throw new Error('no WebGL in Node');
+ },
+ },
+ });
+ const { context, actions } = fakeContext(contextOptions);
+ const instance = definition.create(context);
+ actions.instance = instance;
+ return { definition, instance, source, actions, loads };
+ }
+
+ test('Panoramax registers keyless and off by default, with both filters and its own wording', () => {
+ const { definition } = setup();
+ assert.equal(definition.id, 'panoramax');
+ assert.equal(definition.label, 'PANORAMAX');
+ assert.equal(definition.requiresKeyId, null);
+ assert.equal(definition.defaultOn, false);
+ assert.equal(definition.filters, undefined, 'pano and since both apply');
+ assert.notEqual(definition.highlightsSequence, false, 'lines are sequences');
+ assert.match(definition.credit.html, /Panoramax<\/a> contributors/);
+ assert.equal(
+ definition.coverageLabel.action,
+ 'click a line for its nearest photo',
+ );
+ assert.doesNotThrow(() => validateProviders([definition]));
+ });
+
-test('lines at z10–14 below 60 km, as Mapillary’s; density points from z5 down to z0 above', () => {
- assert.deepEqual(panoramaxZoomFor(500), { zoom: 14, kind: 'sequence' });
- assert.deepEqual(panoramaxZoomFor(1_800), { zoom: 14, kind: 'sequence' });
- assert.deepEqual(panoramaxZoomFor(4_000), { zoom: 13, kind: 'sequence' });
- assert.deepEqual(panoramaxZoomFor(12_000), { zoom: 12, kind: 'sequence' });
- assert.deepEqual(panoramaxZoomFor(25_000), { zoom: 11, kind: 'sequence' });
- assert.deepEqual(panoramaxZoomFor(30_000), { zoom: 11, kind: 'sequence' });
- assert.deepEqual(panoramaxZoomFor(30_001), { zoom: 10, kind: 'sequence' });
- assert.deepEqual(panoramaxZoomFor(60_000), { zoom: 10, kind: 'sequence' });
- assert.deepEqual(panoramaxZoomFor(60_001), { zoom: 5, kind: 'overview' });
- assert.deepEqual(panoramaxZoomFor(100_000), { zoom: 5, kind: 'overview' });
- assert.deepEqual(panoramaxZoomFor(2_000_000), { zoom: 3, kind: 'overview' });
- assert.deepEqual(panoramaxZoomFor(20_000_000), { zoom: 0, kind: 'overview' });
++test('lines at z10–14 below 60 km, as Mapillary’s; nothing above', () => {
++ assert.equal(panoramaxZoomFor(500), 14);
++ assert.equal(panoramaxZoomFor(1_800), 14);
++ assert.equal(panoramaxZoomFor(4_000), 13);
++ assert.equal(panoramaxZoomFor(12_000), 12);
++ assert.equal(panoramaxZoomFor(25_000), 11);
++ assert.equal(panoramaxZoomFor(30_000), 11);
++ assert.equal(panoramaxZoomFor(30_001), 10);
++ assert.equal(panoramaxZoomFor(60_000), 10);
++ assert.equal(panoramaxZoomFor(60_001), null);
++ assert.equal(panoramaxZoomFor(20_000_000), null);
+ assert.equal(panoramaxZoomFor(NaN), null);
+ });
+
+ test('a line with no camera type or no day passes the filters: a click finds out', () => {
+ const filter = { pano: 'pano', sinceMs: Date.UTC(2024, 0, 1) };
+ assert.equal(
+ passesCoverage({ isPano: null, capturedAt: Date.UTC(2025, 0, 1) }, filter),
+ true,
+ );
+ assert.equal(passesCoverage({ isPano: true, capturedAt: 0 }, filter), true);
+ assert.equal(passesCoverage({ isPano: false, capturedAt: 0 }, filter), false);
+ assert.equal(
+ passesCoverage({ isPano: null, capturedAt: Date.UTC(2020, 0, 1) }, filter),
+ false,
+ );
+ });
+
-test('the imagery filter: lines by type and day, density cells by what they hold', () => {
++test('the imagery filter: lines by type and day', () => {
+ const old = Date.UTC(2020, 0, 1);
+ const since = { pano: 'all', sinceMs: Date.UTC(2024, 0, 1) };
+ assert.equal(
+ passesCoverage({ isPano: false, capturedAt: old }, since),
+ false,
+ );
+ assert.equal(
+ passesCoverage(
+ { isPano: true, capturedAt: Date.UTC(2025, 0, 1) },
+ {
+ pano: 'pano',
+ sinceMs: null,
+ },
+ ),
+ true,
+ );
- const cell = { hasPano: false, hasFlat: true, capturedAt: null };
- assert.equal(passesCoverage(cell, { pano: 'pano', sinceMs: null }), false);
- assert.equal(passesCoverage(cell, { pano: 'flat', sinceMs: null }), true);
- assert.equal(passesCoverage(cell, since), true, 'cells are undated: kept');
- assert.equal(passesCoverage(cell, null), true);
++ assert.equal(passesCoverage({ isPano: false, capturedAt: old }, null), true);
+ });
+
+ test('cones read the z15 tile around a picture, and its neighbours near an edge', () => {
+ const home = tileCentre(ORIGIN.lon, ORIGIN.lat, 15);
+ assert.equal(pictureTilesAround(home).length, 1, 'mid-tile: one tile');
+ const box = tileBounds(home.tile.x, home.tile.y, 15);
+ const corner = { lon: box.west + 0.0002, lat: box.north - 0.0002 };
+ const tiles = pictureTilesAround(corner).map((t) => `${t.x}/${t.y}`);
+ const { x, y } = home.tile;
+ assert.deepEqual(tiles, [
+ `${x}/${y}`,
+ `${x - 1}/${y}`,
+ `${x}/${y - 1}`,
+ `${x - 1}/${y - 1}`,
+ ]);
+ // Across the antimeridian the column wraps.
+ const dateLine = pictureTilesAround({ lon: -179.9999, lat: 0.5 });
+ assert.equal(dateLine[1].x, 2 ** 15 - 1);
+ });
+
+ test('the nearest picture within 50 m that passes the filter; filters go to the API', async () => {
+ const items = [
+ ...sequence('far', 1, { offset: 80 }),
+ ...sequence('a', 3, { offset: 10 }),
+ ];
+ const { instance, source } = setup(
+ { items },
+ { filter: { pano: 'pano', sinceMs: 123 } },
+ );
+ const id = await instance.nearestImage(east(0));
+ assert.equal(id, 'a-0');
+ assert.equal(source.calls.nearest.length, 1);
+ assert.equal(source.calls.nearest[0].pano, 'pano');
+ assert.equal(source.calls.nearest[0].sinceMs, 123);
+ assert.equal(source.calls.nearest[0].collections, null);
+ assert.equal(await instance.nearestImage(east(300)), null, 'none near');
+ });
+
+ test('a click on a line opens that sequence’s picture nearest the click, not another’s', async () => {
+ const items = [
+ ...sequence('other', 2, { offset: 0 }),
+ ...sequence('clicked', 4, { offset: 8 }),
+ ];
+ const { instance, actions, source } = setup({ items });
+ assert.equal(
- instance.handlePick(`${PICK_PREFIX.sequence}clicked~1`, {
++ instance.handlePick(`${PICK_PREFIX.sequence}clicked`, {
+ groundPoint: () => east(1),
+ }),
+ true,
+ );
+ assert.deepEqual(actions.nearest, [east(1)]);
+ // The core asks the provider for the nearest picture to that point.
+ assert.equal(await instance.nearestImage(east(1)), 'clicked-0');
+ assert.equal(source.calls.nearest[0].collections, 'clicked');
+ // Only once: the next lookup (OPEN, another click) is any sequence's.
+ assert.equal(await instance.nearestImage(east(1)), 'other-0');
+ });
+
+ test('a line click whose sequence has nothing near falls back to any picture there', async () => {
+ const items = [
+ ...sequence('near', 1),
+ ...sequence('clicked', 1, { offset: 400 }),
+ ];
+ const { instance, source } = setup({ items });
+ instance.handlePick(`${PICK_PREFIX.sequence}clicked`, {
+ groundPoint: () => east(0),
+ });
+ assert.equal(await instance.nearestImage(east(0)), 'near-0');
+ assert.deepEqual(
+ source.calls.nearest.map((q) => q.collections),
+ ['clicked', null],
+ );
+ });
+
+ test('a cone opens its picture; foreign ids are not picked', () => {
+ const { instance, actions } = setup();
+ assert.equal(instance.handlePick(`${PICK_PREFIX.image}abc`), true);
+ assert.equal(actions.opened[0].id, 'abc');
+ assert.equal(instance.handlePick('kv:line:1'), false);
+ assert.equal(instance.handlePick('pnx:other'), false);
+ });
+
+ /** A provider and its viewer mounted, opening pictures through the fake core. */
+ async function mounted(sourceOptions, contextOptions) {
+ const env = setup(sourceOptions, contextOptions);
+ const poses = [];
+ env.instance.viewer.onPose((pose) => poses.push(pose.imageId));
+ const host = fakeHost();
+ await env.instance.viewer.mount(host);
+ const [, , prev, next] = host.children[0].children;
+ return { ...env, poses, prev, next };
+ }
+
+ test('› and ‹ step along the picture’s links without moving the camera, asking only for the next picture', async () => {
+ const items = sequence('s', 3);
+ const env = await mounted({ items });
+ await env.instance.viewer.open('s-0');
+ assert.ok(await until(() => env.prev.disabled), 'the first picture: no ‹');
+ env.next.fire('click');
+ assert.ok(await until(() => env.poses.at(-1) === 's-1'));
+ assert.deepEqual(env.actions.opened.at(-1), {
+ id: 's-1',
+ options: { frame: false },
+ });
+ env.next.fire('click');
+ assert.ok(await until(() => env.poses.at(-1) === 's-2'));
+ assert.ok(await until(() => env.next.disabled), 'the last picture: no ›');
+ assert.deepEqual(env.source.calls.items, ['s-0', 's-1', 's-2']);
+ env.prev.fire('click');
+ assert.ok(await until(() => env.poses.at(-1) === 's-1'));
+ assert.equal(env.source.calls.items.length, 3, 's-1 came from the cache');
+ });
+
+ test('one lookup for a picture asked twice at once', async () => {
+ const items = sequence('s', 1);
+ const { instance, source } = setup({ items });
+ let release;
+ const gate = new Promise((resolve) => (release = resolve));
+ const getItem = source.getItem;
+ source.getItem = async (id) => {
+ await gate;
+ return getItem(id);
+ };
+ const host = fakeHost();
+ await instance.viewer.mount(host);
+ const first = instance.viewer.open('s-0');
+ const second = instance.viewer.open('s-0');
+ release();
+ await Promise.all([first, second]);
+ assert.deepEqual(source.calls.items, ['s-0']);
+ });
+
+ test('a picture Panoramax does not know, or an id it refuses, fails the open with a reason', async () => {
+ const env = await mounted({ items: [] });
+ await assert.rejects(
+ env.instance.viewer.open('ghost'),
+ /no longer available/,
+ );
+ env.source.getItem = async () => {
+ throw Object.assign(new Error('Panoramax answered HTTP 400'), {
+ status: 400,
+ });
+ };
+ await assert.rejects(
+ env.instance.viewer.open('not-a-uuid'),
+ /no longer available/,
+ );
+ env.source.getItem = async () => {
+ throw Object.assign(new Error('Panoramax is busy'), { status: 503 });
+ };
+ await assert.rejects(env.instance.viewer.open('busy'), /busy/);
+ });
+
+ /** Cones on a stand-in Cesium viewer; `count()` reads how many are drawn. */
+ async function withCones(t, env) {
+ const Cesium = await import('cesium');
+ // The cone glyph draws on a canvas: any drawing call is fine.
+ const drawing = new Proxy({}, { get: () => () => {}, set: () => true });
+ const saved = globalThis.document;
+ globalThis.document = {
+ createElement: () => ({ getContext: () => drawing }),
+ };
+ t.after(() => (globalThis.document = saved));
+ let collection = null;
+ env.instance.init({
+ scene: {
+ frameState: { mode: Cesium.SceneMode.SCENE3D },
+ updateHeight: () => () => {},
+ getHeight: () => undefined,
+ primitives: { add: (c) => (collection = c), remove() {} },
+ preRender: { addEventListener: () => () => {} },
+ },
+ camera: { positionWC: new Cesium.Cartesian3(0, 0, 1e8) },
+ });
+ return {
+ count: () => collection?.length ?? 0,
+ ids: () =>
+ Array.from({ length: collection?.length ?? 0 }, (_, i) =>
+ String(collection.get(i).id).replace(PICK_PREFIX.image, ''),
+ ),
+ };
+ }
+
+ /** z15 tiles holding every item of `items` as a picture. */
+ const pictureTiles = (items) => (tile) => {
+ if (tile.z !== 15) return new Uint8Array(0);
+ const box = tileBounds(tile.x, tile.y, tile.z);
+ const inside = items.filter(
+ ({
+ geometry: {
+ coordinates: [lon, lat],
+ },
+ }) =>
+ lon >= box.west && lon < box.east && lat <= box.north && lat > box.south,
+ );
+ return encodePanoramaxTile(tile, {
+ pictures: inside.map((item) => ({
+ id: item.id,
+ lon: item.geometry.coordinates[0],
+ lat: item.geometry.coordinates[1],
+ sequenceId: item.collection,
+ ts: item.properties.datetime.replace('T', ' ').replace('+00:00', '+00'),
+ })),
+ });
+ };
+
+ test('once a picture is on screen its sequence’s cones load from the z15 tile around it', async (t) => {
+ const items = [...sequence('s', 6), ...sequence('x', 3, { offset: 2 })];
+ const env = await mounted({ items, tiles: pictureTiles(items) });
+ const cones = await withCones(t, env);
+ await env.instance.viewer.open('s-2');
+ await env.instance.selectSequence('s');
+ assert.ok(await until(() => !env.instance.sequenceStats().loading));
+ assert.equal(env.instance.sequenceStats().selectedId, 's');
+ assert.equal(env.instance.sequenceStats().images, 6, 'only sequence s');
+ assert.equal(cones.count(), 6);
+ assert.ok(env.source.calls.tiles.every((key) => key.startsWith('15/')));
+ });
+
+ test('a click on a line with no ground under it changes nothing: the open sequence keeps its cones', async (t) => {
+ const items = [...sequence('x', 6), ...sequence('y', 3, { offset: 3 })];
+ const env = await mounted({ items, tiles: pictureTiles(items) });
+ const cones = await withCones(t, env);
+ await env.instance.viewer.open('x-1');
+ await env.instance.selectSequence('x');
+ assert.ok(await until(() => cones.count() === 6));
+ const asked = env.source.calls.tiles.length;
+ assert.equal(
+ env.instance.handlePick(`${PICK_PREFIX.sequence}y`, {
+ groundPoint: () => null,
+ }),
+ true,
+ 'the click is the provider’s, even with nothing to open',
+ );
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ assert.equal(env.instance.sequenceStats().selectedId, 'x');
+ assert.equal(cones.count(), 6);
+ assert.equal(env.source.calls.tiles.length, asked);
+ assert.deepEqual(env.actions.nearest, []);
+ });
+
+ test('a sequence selected with nothing to centre on draws no cones, and a picture opening in it then does not throw', async (t) => {
+ const items = sequence('s', 3);
+ const env = await mounted({ items, tiles: pictureTiles(items) });
+ await withCones(t, env);
+ await env.instance.selectSequence('s');
+ assert.equal(env.instance.sequenceStats().images, 0);
+ assert.deepEqual(env.source.calls.tiles, []);
+ // Its first picture opens: the cones load around it.
+ await env.instance.viewer.open('s-0');
+ await env.instance.selectSequence('s');
+ assert.ok(await until(() => env.instance.sequenceStats().images === 3));
+ });
+
+ test('a line clicked from high up looks for its sequence further off; the radius grows with height, up to 400 m', async () => {
+ const items = [
+ ...sequence('near', 1),
+ ...sequence('line', 1, { offset: 220 }),
+ ];
+ const { instance, source } = setup({ items });
+ const height = (h) =>
+ instance.init({
+ camera: { positionCartographic: { height: h } },
+ scene: {
+ primitives: { add() {}, remove() {} },
+ preRender: { addEventListener: () => () => {} },
+ },
+ });
+ const click = () =>
+ instance.handlePick(`${PICK_PREFIX.sequence}line`, {
+ groundPoint: () => east(0),
+ });
+ height(25_000);
+ click();
+ assert.equal(
+ await instance.nearestImage(east(0)),
+ 'line-0',
+ '220 m off, from 25 km',
+ );
+ assert.equal(source.calls.nearest.at(-1).radius, 250);
+ height(1_000);
+ click();
+ assert.equal(
+ await instance.nearestImage(east(0)),
+ 'near-0',
+ 'from 1 km only 50 m: any sequence’s nearer picture',
+ );
+ height(900_000);
+ click();
+ await instance.nearestImage(east(0));
+ assert.equal(
+ source.calls.nearest.filter((q) => q.collections === 'line').at(-1).radius,
+ 400,
+ 'capped',
+ );
+ });
+
+ test('a lookup at another point does not take a line click’s sequence', async () => {
+ const items = [
+ ...sequence('other', 1),
+ ...sequence('clicked', 1, { offset: 8 }),
+ ];
+ const { instance, source } = setup({ items });
+ instance.handlePick(`${PICK_PREFIX.sequence}clicked`, {
+ groundPoint: () => east(1),
+ });
+ // OPEN at the view centre, a few metres away, overtakes the click.
+ assert.equal(await instance.nearestImage(east(3)), 'other-0');
+ assert.deepEqual(
+ source.calls.nearest.map((q) => q.collections),
+ [null],
+ );
+ });
+
+ test('the cones come in capture order, and a broken neighbour tile only thins them', async (t) => {
+ const items = sequence('s', 5).map((item, i) => ({
+ ...item,
+ properties: {
+ ...item.properties,
+ // Captured in reverse of their position along the street.
+ datetime: `2025-06-01T10:00:0${9 - i}+00:00`,
+ },
+ }));
+ const tiles = pictureTiles(items);
+ const env = await mounted({ items, tiles });
+ const cones = await withCones(t, env);
+ await env.instance.viewer.open('s-0');
+ await env.instance.selectSequence('s');
+ assert.ok(await until(() => cones.count() === 5));
+ assert.deepEqual(cones.ids(), ['s-4', 's-3', 's-2', 's-1', 's-0']);
+ // A neighbour answers with garbage: the home tile's cones still draw.
+ });
+
+ test('a broken neighbour z15 tile only thins the cones; an unreadable home tile reads as such', async (t) => {
+ // At a tile corner: the home tile and three neighbours are asked.
+ const home = tileCentre(ORIGIN.lon, ORIGIN.lat, 15);
+ const box = tileBounds(home.tile.x, home.tile.y, 15);
+ const at = { lon: box.west + 0.0003, lat: box.north - 0.0002 };
+ const items = [0, 1, 2].map((i) =>
+ stacItem({
+ id: `c-${i}`,
+ sequenceId: 'c',
+ lon: at.lon + i * 0.00005,
+ lat: at.lat,
+ }),
+ );
+ const tiles = pictureTiles(items);
+ const broken = new TextEncoder().encode('<html>oops</html>');
+ const homeKey = `15/${home.tile.x}/${home.tile.y}`;
+ const env = await mounted({
+ items,
+ tiles: (tile) =>
+ `${tile.z}/${tile.x}/${tile.y}` === homeKey ? tiles(tile) : broken,
+ });
+ const cones = await withCones(t, env);
+ await env.instance.viewer.open('c-0');
+ await env.instance.selectSequence('c');
+ assert.ok(await until(() => !env.instance.sequenceStats().loading));
+ assert.equal(cones.count(), 3, 'the home tile’s cones draw');
+ assert.ok(env.source.calls.tiles.length > 1, 'neighbours were asked');
+ // Another sequence whose home tile is unreadable too.
+ const env2 = await mounted({ items, tiles: () => broken });
+ await withCones(t, env2);
+ await env2.instance.viewer.open('c-0');
+ await env2.instance.selectSequence('c');
- assert.ok(await until(() => env2.actions.errors.some(Boolean)));
- assert.match(env2.actions.errors.filter(Boolean).at(-1), /could not be read/);
++ assert.ok(await until(() => env2.instance.sequenceStats().error));
++ assert.match(env2.instance.sequenceStats().error, /could not be read/);
++ assert.deepEqual(
++ env2.actions.errors.filter(Boolean),
++ [],
++ 'a sequence error is the sequence’s, not the viewer’s',
++ );
+ });
+
+ test('cones re-centred into tiles already read do not read them again', async (t) => {
+ const items = sequence('long', 400);
+ const env = await mounted({ items, tiles: pictureTiles(items) });
+ await withCones(t, env);
+ await env.instance.viewer.open('long-0');
+ await env.instance.selectSequence('long');
+ assert.ok(await until(() => env.instance.sequenceStats().images > 0));
+ await env.instance.viewer.open('long-399');
+ assert.ok(await until(() => !env.instance.sequenceStats().loading));
+ const asked = env.source.calls.tiles.length;
+ // Back to the start: its tiles are kept.
+ await env.instance.viewer.open('long-0');
+ assert.ok(await until(() => !env.instance.sequenceStats().loading));
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ assert.equal(env.source.calls.tiles.length, asked);
+ assert.ok(env.instance.sequenceStats().images > 0);
+ });
+
+ test('› within the tiles the cones came from reloads nothing', async (t) => {
+ const items = sequence('s', 4);
+ const env = await mounted({ items, tiles: pictureTiles(items) });
+ await withCones(t, env);
+ await env.instance.viewer.open('s-0');
+ await env.instance.selectSequence('s');
+ assert.ok(await until(() => env.instance.sequenceStats().images === 4));
+ const asked = env.source.calls.tiles.length;
+ env.next.fire('click');
+ assert.ok(await until(() => env.poses.at(-1) === 's-1'));
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ assert.equal(env.source.calls.tiles.length, asked);
+ });
+
+ test('the cones re-centre when › walks into another z15 tile', async (t) => {
+ // 400 pictures 5 m apart span 2 km: more than two z15 tiles (~800 m).
+ const items = sequence('long', 400);
+ const env = await mounted({ items, tiles: pictureTiles(items) });
+ await withCones(t, env);
+ await env.instance.viewer.open('long-0');
+ await env.instance.selectSequence('long');
+ assert.ok(await until(() => !env.instance.sequenceStats().loading));
+ const firstTiles = new Set(env.source.calls.tiles);
+ const first = env.instance.sequenceStats().images;
+ assert.ok(first > 0 && first < 400, `part of the sequence: ${first}`);
+ // Jump to the far end: the cones follow.
+ await env.instance.viewer.open('long-399');
+ assert.ok(
+ await until(() =>
+ env.source.calls.tiles.some((key) => !firstTiles.has(key)),
+ ),
+ 'a new tile was read',
+ );
+ assert.ok(await until(() => !env.instance.sequenceStats().loading));
+ assert.ok(env.instance.sequenceStats().images > 0);
+ });
+
+ /** The provider drawing coverage on a stand-in viewer above one z14 tile. */
-function coverageSetup(
- t,
- { sequences = [], grid = [], filter, height = 900 } = {},
-) {
++function coverageSetup(t, { sequences = [], filter, height = 900 } = {}) {
+ const centre = tileCentre(ORIGIN.lon, ORIGIN.lat);
+ let hold = null;
+ const env = setup(
+ {
+ tiles: (tile) => {
- const bytes = encodePanoramaxTile(tile, { sequences, grid });
++ const bytes = encodePanoramaxTile(tile, { sequences });
+ return hold ? hold.then(() => bytes) : bytes;
+ },
+ },
+ { filter },
+ );
+ const viewer = coverageViewer({ ...centre, height }, t);
+ env.instance.init(viewer);
+ t.after(() => env.instance.destroy(viewer));
+ return {
+ ...env,
+ viewer,
+ centre,
+ holdTiles() {
+ let release;
+ hold = new Promise((resolve) => (release = resolve));
+ return () => {
+ hold = null;
+ release();
+ };
+ },
+ };
+ }
+
+ const line = (id, options = {}) => ({
+ id,
+ parts: [
+ [
+ [ORIGIN.lon - 0.001, ORIGIN.lat],
+ [ORIGIN.lon + 0.001, ORIGIN.lat],
+ ],
+ ],
+ ...options,
+ });
+
+ test('sequence lines draw near the ground, and the imagery filter thins them', async (t) => {
+ const env = coverageSetup(t, {
+ sequences: [
+ line('new-pano', { type: 'equirectangular', date: '2025-06-01' }),
+ line('old-flat', { date: '2019-06-01' }),
+ ],
+ });
+ env.instance.activate(env.viewer);
+ assert.ok(await until(() => env.instance.coverageStats().count === 2));
- assert.equal(env.instance.coverageStats().kind, 'sequence');
+ assert.equal(env.instance.coverageStats().keyRequired, false);
++ assert.equal(env.instance.coverageStats().error, null);
+ env.instance.deactivate();
+
+ const filtered = coverageSetup(t, {
+ filter: { pano: 'pano', sinceMs: null },
+ sequences: [
+ line('new-pano', { type: 'equirectangular' }),
+ line('old-flat'),
+ ],
+ });
+ filtered.instance.activate(filtered.viewer);
+ assert.ok(await until(() => filtered.instance.coverageStats().count === 1));
+ });
+
++test('the selected sequence’s line is drawn again over the coverage, and goes with it', async (t) => {
++ const env = coverageSetup(t, { sequences: [line('a'), line('b')] });
++ env.instance.activate(env.viewer);
++ assert.ok(await until(() => env.instance.coverageStats().count === 2));
++ const ground = env.viewer.scene.groundPrimitives.items;
++ const drawn = ground.size;
++ await env.instance.selectSequence('a');
++ assert.equal(ground.size, drawn + 1, 'one highlight over the lines');
++ env.instance.clearSequence();
++ assert.equal(ground.size, drawn);
++});
++
+ test('coverage hints: nothing while loading, “no pictures” once an empty view has loaded', async (t) => {
+ const env = coverageSetup(t);
+ const release = env.holdTiles();
+ env.instance.activate(env.viewer);
+ assert.ok(await until(() => env.instance.coverageStats().loading));
+ assert.equal(env.instance.coverageStats().hint, '');
+ release();
+ assert.ok(await until(() => !env.instance.coverageStats().loading));
+ assert.equal(env.instance.coverageStats().hint, NO_COVERAGE_HINT);
+ });
+
-test('from high up the density grid draws points, not counted as sequences, and the panel says to zoom in', async (t) => {
- const env = coverageSetup(t, {
- height: 200_000,
- grid: [{ lon: ORIGIN.lon, lat: ORIGIN.lat, pano: 2, flat: 3 }],
- });
++test('from high up nothing is drawn or fetched, and the panel says to zoom in', async (t) => {
++ const env = coverageSetup(t, { height: 200_000, sequences: [line('a')] });
+ env.instance.activate(env.viewer);
+ assert.ok(
- await until(() => env.instance.coverageStats().kind === 'overview'),
++ await until(() => env.instance.coverageStats().hint === ZOOM_IN_HINT),
+ );
- assert.ok(await until(() => !env.instance.coverageStats().loading));
- assert.equal(env.instance.coverageStats().zoom, 5);
- assert.equal(env.instance.coverageStats().count, 0, 'dots are not sequences');
- assert.equal(env.instance.coverageStats().hint, OVERVIEW_HINT);
++ assert.equal(env.instance.coverageStats().count, 0);
++ assert.equal(env.instance.coverageStats().loading, false);
++ assert.deepEqual(env.source.calls.tiles, []);
++ assert.equal(env.viewer.scene.groundPrimitives.items.size, 0);
+ });
+
+ test('switching off clears the cones and forgets a pending line click', async (t) => {
+ const items = sequence('s', 3);
+ const env = await mounted({ items, tiles: pictureTiles(items) });
+ const cones = await withCones(t, env);
+ await env.instance.viewer.open('s-0');
+ await env.instance.selectSequence('s');
+ assert.ok(await until(() => cones.count() === 3), 'cones to clear');
+ env.instance.handlePick(`${PICK_PREFIX.sequence}s`, {
+ groundPoint: () => east(0),
+ });
+ env.instance.deactivate();
+ assert.equal(env.instance.sequenceStats().selectedId, null);
+ assert.equal(cones.count(), 0, 'the cones are gone');
+ // The click's preference is gone: a later lookup asks any sequence.
+ await env.instance.nearestImage(east(0));
+ assert.equal(env.source.calls.nearest.at(-1).collections, null);
+ });
+
+ test('lines in view that the filter hides all of say so, not that there is nothing here', async (t) => {
+ const env = coverageSetup(t, {
+ filter: { pano: 'pano', sinceMs: null },
+ sequences: [line('flat-only')],
+ });
+ env.instance.activate(env.viewer);
- assert.ok(
- await until(
- () =>
- !env.instance.coverageStats().loading &&
- env.instance.coverageStats().zoom !== null,
- ),
- );
+ assert.ok(
+ await until(() => env.instance.coverageStats().hint === FILTERED_HINT),
+ );
+ assert.equal(env.instance.coverageStats().count, 0);
+ });
+
-test('from high up over empty sea the panel says there is nothing, not to zoom in', async (t) => {
- const env = coverageSetup(t, { height: 200_000, grid: [] });
- env.instance.activate(env.viewer);
- assert.ok(
- await until(() => env.instance.coverageStats().kind === 'overview'),
- );
- assert.ok(
- await until(() => env.instance.coverageStats().hint === NO_COVERAGE_HINT),
- );
-});
-
-test('density dots grow with the pictures they stand for', () => {
- assert.equal(overviewPointSize({ weight: 1 }), 2.5);
- assert.equal(overviewPointSize({ weight: 100 }), 4.5);
- assert.equal(overviewPointSize({ weight: 1e9 }), 8);
- assert.equal(overviewPointSize({}), 2.5);
- assert.ok(
- overviewPointSize({ weight: 50_000 }) >
- overviewPointSize({ weight: 50 }) + 2,
- );
-});
-
+ test('Esc in the docked viewer clears the selected sequence before the panel can collapse', async (t) => {
+ const items = sequence('s', 3);
+ const env = await mounted({ items, tiles: pictureTiles(items) });
+ await withCones(t, env);
+ await env.instance.viewer.open('s-0');
+ await env.instance.selectSequence('s');
+ assert.ok(await until(() => env.instance.sequenceStats().images === 3));
+ const root = env.next.parentNode;
+ const flags = { stopped: false, prevented: false };
+ root.fire('keydown', {
+ key: 'Escape',
+ stopPropagation: () => (flags.stopped = true),
+ preventDefault: () => (flags.prevented = true),
+ });
+ assert.equal(env.instance.sequenceStats().selectedId, null);
+ assert.deepEqual(
+ flags,
+ { stopped: true, prevented: true },
+ 'consumed: the panel never sees it',
+ );
+ // Nothing selected: Esc goes on to the panel.
+ const again = { key: 'Escape', defaultPrevented: false };
+ const result = { prevented: false };
+ root.fire('keydown', {
+ ...again,
+ preventDefault() {
+ result.prevented = true;
+ },
+ });
+ assert.equal(result.prevented, false);
+ });
+
+ test('cones near the east and south edges read those neighbours; near both edges of a narrow tile, both sides', () => {
+ const home = tileCentre(ORIGIN.lon, ORIGIN.lat, 15);
+ const box = tileBounds(home.tile.x, home.tile.y, 15);
+ const { x, y } = home.tile;
+ const keys = (point) => pictureTilesAround(point).map((t) => `${t.x}/${t.y}`);
+ assert.deepEqual(keys({ lon: box.east - 0.0002, lat: box.south + 0.0002 }), [
+ `${x}/${y}`,
+ `${x + 1}/${y}`,
+ `${x}/${y + 1}`,
+ `${x + 1}/${y + 1}`,
+ ]);
+ // Svalbard: a z15 tile is ~250 m wide, so its middle is near both sides.
+ const north = tileCentre(15.6, 78.22, 15);
+ const around = keys(north);
+ for (const dx of [-1, 1])
+ assert.ok(
+ around.includes(`${north.tile.x + dx}/${north.tile.y}`),
+ `${dx} in ${around}`,
+ );
+ assert.equal(around[0], `${north.tile.x}/${north.tile.y}`, 'its own first');
+ });
+
+ test('a search hit outside the radius (a bounding box’s corner) is not the nearest', async () => {
+ const corner = stacItem({ id: 'corner', sequenceId: 'c', ...east(65) });
+ const { instance, source } = setup({ items: [corner] });
+ source.nearestItems = async () => [corner];
+ assert.equal(await instance.nearestImage(east(0)), null);
+ });
+
+ test('a line clicked from low down still searches its own sequence within 50 m', async () => {
+ const items = [
+ ...sequence('other', 1, { offset: 2 }),
+ ...sequence('clicked', 1, { offset: 30 }),
+ ];
+ const { instance, source } = setup({ items });
+ instance.init({
+ camera: { positionCartographic: { height: 300 } },
+ scene: {
+ primitives: { add() {}, remove() {} },
+ preRender: { addEventListener: () => () => {} },
+ },
+ });
+ instance.handlePick(`${PICK_PREFIX.sequence}clicked`, {
+ groundPoint: () => east(0),
+ });
+ assert.equal(await instance.nearestImage(east(0)), 'clicked-0');
+ assert.equal(source.calls.nearest[0].radius, 50);
+ });
+
+ test('cones re-centre on a picture that opens while they are still loading', async (t) => {
+ const items = sequence('long', 400);
+ const tiles = pictureTiles(items);
+ let release = null;
+ const env = await mounted({ items, tiles });
+ await withCones(t, env);
+ await env.instance.viewer.open('long-0');
+ env.source.getTile = async (tile) => {
+ env.source.calls.tiles.push(`${tile.z}/${tile.x}/${tile.y}`);
+ if (release === null) await new Promise((go) => (release = go));
+ return tiles(tile);
+ };
+ const first = env.instance.selectSequence('long');
+ assert.ok(await until(() => release !== null), 'the first load is held');
+ // The far end opens while the cones around long-0 still load.
+ await env.instance.viewer.open('long-399');
+ release();
+ await first;
+ assert.ok(await until(() => !env.instance.sequenceStats().loading));
+ const [lon, lat] = items[399].geometry.coordinates;
+ const [far] = pictureTilesAround({ lon, lat });
+ assert.ok(
+ env.source.calls.tiles.includes(`15/${far.x}/${far.y}`),
+ `the far picture's tile was read: ${env.source.calls.tiles}`,
+ );
+ });
+
-test('a filter that hides every density dot says so', async (t) => {
- const env = coverageSetup(t, {
- height: 200_000,
- filter: { pano: 'pano', sinceMs: null },
- grid: [{ lon: ORIGIN.lon, lat: ORIGIN.lat, pano: 0, flat: 5 }],
- });
- env.instance.activate(env.viewer);
- assert.ok(
- await until(() => env.instance.coverageStats().hint === FILTERED_HINT),
- );
-});
-
-test('dots are drawn at their own sizes, and the busiest is the biggest', async (t) => {
- const env = coverageSetup(t, {
- height: 200_000,
- grid: [
- { lon: ORIGIN.lon, lat: ORIGIN.lat, pano: 0, flat: 1 },
- { lon: ORIGIN.lon + 3, lat: ORIGIN.lat, pano: 30_000, flat: 20_000 },
- ],
- });
- env.instance.activate(env.viewer);
- const sizes = () => {
- const out = [];
- for (const primitive of env.viewer.scene.primitives.items)
- for (let i = 0; i < (primitive.length ?? 0); i++)
- if (primitive.get(i).pixelSize) out.push(primitive.get(i).pixelSize);
- return out.sort((a, b) => a - b);
- };
- assert.ok(await until(() => sizes().length === 2));
- assert.deepEqual(sizes(), [
- overviewPointSize({ weight: 1 }),
- overviewPointSize({ weight: 50_000 }),
- ]);
-});
-
-test('lines keep the decoded (longest-first) order under a budget of points', async () => {
++test('lines keep the decoded (longest-first) order under a cap on points', async () => {
+ const { COVERAGE_TUNING } = await import('./policy.js');
+ assert.equal(COVERAGE_TUNING.keepOrder, true);
+ assert.ok(COVERAGE_TUNING.maxPoints > 0);
+ });
+
+ test('a coverage tile decoded a moment ago is not fetched again; switched off, the tiles are let go', async (t) => {
+ const env = coverageSetup(t, { sequences: [line('a')] });
+ const asked = [];
+ const getTile = env.source.getTile;
+ env.source.getTile = (tile, options) => {
+ asked.push(`${tile.z}/${tile.x}/${tile.y}`);
+ return getTile(tile, options);
+ };
+ env.instance.activate(env.viewer);
+ assert.ok(await until(() => env.instance.coverageStats().count === 1));
+ const z14 = asked.length;
+ // Up a zoom band and back down: the z14 tile comes from memory.
++ // (Activating again refreshes at once, without the camera debounce.)
+ env.viewer.view.height = 3_000;
- env.instance.refreshCoverage();
- assert.ok(await until(() => env.instance.coverageStats().zoom === 13));
- assert.ok(await until(() => !env.instance.coverageStats().loading));
++ env.instance.activate(env.viewer);
++ assert.ok(await until(() => asked.some((key) => key.startsWith('13/'))));
++ assert.ok(await until(() => env.instance.coverageStats().count === 1));
+ const withZ13 = asked.length;
+ env.viewer.view.height = 900;
- env.instance.refreshCoverage();
- assert.ok(await until(() => env.instance.coverageStats().zoom === 14));
++ env.instance.activate(env.viewer);
+ assert.ok(await until(() => env.instance.coverageStats().count === 1));
++ await new Promise((resolve) => setTimeout(resolve, 10));
+ assert.equal(asked.length, withZ13, 'nothing fetched again');
+ assert.ok(z14 > 0);
+ // Off and on: the memory went back, so the tile is fetched again.
+ env.instance.deactivate();
+ env.instance.activate(env.viewer);
+ assert.ok(await until(() => env.instance.coverageStats().count === 1));
+ assert.ok(asked.length > withZ13);
+ });
+
+ test('a re-centre while the cones still load does not inherit the aborted load’s tiles', async (t) => {
+ const items = sequence('long', 400);
+ const tiles = pictureTiles(items);
+ const env = await mounted({ items, tiles });
+ const cones = await withCones(t, env);
+ let hold = null;
+ env.source.getTile = async (tile, { signal } = {}) => {
+ env.source.calls.tiles.push(`${tile.z}/${tile.x}/${tile.y}`);
+ if (hold) await hold.promise;
+ signal?.throwIfAborted();
+ return tiles(tile);
+ };
+ await env.instance.viewer.open('long-0');
+ const tileOf = (item) => {
+ const [lon, lat] = item.geometry.coordinates;
+ return pictureTilesAround({ lon, lat })[0];
+ };
+ const first = new Set(
+ pictureTilesAround({
+ lon: items[0].geometry.coordinates[0],
+ lat: items[0].geometry.coordinates[1],
+ }).map((tile) => `${tile.x}/${tile.y}`),
+ );
+ const out = items.findIndex((item) => {
+ const tile = tileOf(item);
+ return !first.has(`${tile.x}/${tile.y}`);
+ });
+ hold = {};
+ hold.promise = new Promise((resolve) => (hold.release = resolve));
+ const loading = env.instance.selectSequence('long');
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ // The far picture opens while the first load is held: the cones re-centre.
+ await env.instance.viewer.open(`long-${out}`);
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ const release = hold.release;
+ hold = null;
+ release();
+ await loading;
+ assert.ok(await until(() => !env.instance.sequenceStats().loading));
+ // Every picture in the tiles the second load covers has its cone.
+ const [lon, lat] = items[out].geometry.coordinates;
+ const second = new Set(
+ pictureTilesAround({ lon, lat }).map((tile) => `${tile.x}/${tile.y}`),
+ );
+ const covered = items.filter((item) => {
+ const tile = tileOf(item);
+ return second.has(`${tile.x}/${tile.y}`);
+ });
+ assert.ok(covered.length > 0);
+ // The neighbours join as they arrive: wait for them, then every picture
+ // in the re-centred tiles has its cone (the shared ones too).
+ const coneCount = () => {
+ const ids = new Set(cones.ids());
+ return covered.filter((item) => ids.has(item.id)).length;
+ };
+ assert.ok(
+ await until(() => coneCount() === covered.length),
+ `${coneCount()} of ${covered.length}`,
+ );
+ });
+
+ test('after a GPU reset the viewer draws the same picture itself, leaving the core’s lookups alone; a failure is reported', async () => {
+ const items = sequence('p', 2, { pano: true });
+ let failLoads = false;
+ const view = { yaw: 0, pitch: 0, fov: 90 };
+ const definition = createPanoramaxProvider({
+ source: fakeSource({ items }),
+ viewerOptions: {
+ load: async (url) => {
+ if (failLoads)
+ throw new Error('The Panoramax photo could not be loaded');
+ return { src: url, width: 2048, height: 1024 };
+ },
+ createRenderer: () => ({
+ setImage() {},
+ setView: (next) => Object.assign(view, next),
+ getView: () => ({ ...view }),
+ resize() {},
+ clear() {},
+ destroy() {},
+ }),
+ },
+ });
+ const { context, actions } = fakeContext();
+ const instance = definition.create(context);
+ actions.instance = instance;
+ const host = fakeHost();
+ await instance.viewer.mount(host);
+ const poses = [];
+ instance.viewer.onPose((pose) => poses.push(pose.imageId));
+ await instance.viewer.open('p-0');
+ const canvas = () => host.children[0].children[1];
+ const kind = () => host.children[0].dataset.kind;
+ assert.equal(kind(), 'pano');
+ canvas().fire('webglcontextlost');
+ assert.ok(await until(() => kind() === 'pano'), 'drawn again');
+ assert.deepEqual(poses, ['p-0', 'p-0']);
+ assert.deepEqual(actions.opened, [], 'not through the core');
+ failLoads = true;
+ canvas().fire('webglcontextlost');
+ assert.ok(await until(() => actions.errors.some(Boolean)));
+ assert.match(actions.errors.filter(Boolean)[0], /could not be loaded/);
+ });
+
+ /** A source whose lookup of `heldId` waits for `release()` and ignores aborts. */
+ function holdLookup(source, heldId) {
+ const held = { release: null, signals: [] };
+ const getItem = source.getItem;
+ source.getItem = async (id, options = {}) => {
+ held.signals.push({ id, signal: options.signal });
+ if (id === heldId) await new Promise((go) => (held.release = go));
+ return getItem(id);
+ };
+ return held;
+ }
+
+ test('a lookup that comes back after the user moved on does not move the cones', async (t) => {
+ const items = sequence('long', 400);
+ const env = await mounted({ items, tiles: pictureTiles(items) });
+ await withCones(t, env);
+ const held = holdLookup(env.source, 'long-0');
+ const late = env.instance.viewer.open('long-0');
+ assert.ok(await until(() => held.release !== null));
+ await env.instance.viewer.open('long-399');
+ await late;
+ // The first lookup answers anyway (a source that ignores the abort).
+ held.release();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await env.instance.selectSequence('long');
+ assert.ok(await until(() => !env.instance.sequenceStats().loading));
+ const [lon, lat] = items[399].geometry.coordinates;
+ const [far] = pictureTilesAround({ lon, lat });
+ const [lon0, lat0] = items[0].geometry.coordinates;
+ const [near] = pictureTilesAround({ lon: lon0, lat: lat0 });
+ assert.equal(env.source.calls.tiles[0], `15/${far.x}/${far.y}`);
+ assert.ok(
+ !env.source.calls.tiles.includes(`15/${near.x}/${near.y}`),
+ 'nothing around the picture the user left',
+ );
+ });
+
+ test('a lookup nobody waits for any more is stopped; one still wanted is not', async () => {
+ const items = sequence('s', 3);
+ const env = await mounted({ items });
+ const held = holdLookup(env.source, 's-0');
+ const first = env.instance.viewer.open('s-0');
+ assert.ok(await until(() => held.release !== null));
+ const [{ signal }] = held.signals;
+ assert.equal(signal.aborted, false);
+ await env.instance.viewer.open('s-1');
+ await first;
+ await Promise.resolve();
+ assert.equal(signal.aborted, true, 'the user moved on: its search stops');
+ // The same picture asked again at once shares the lookup, which goes on.
+ held.release = null;
+ held.signals.length = 0;
+ const again = env.instance.viewer.open('s-2');
+ const twice = env.instance.viewer.open('s-2');
+ await Promise.all([again, twice]);
+ assert.equal(held.signals.length, 1);
+ assert.equal(held.signals[0].signal.aborted, false);
+ assert.equal(env.poses.at(-1), 's-2');
+ });
+
+ /**
+ * Two pictures of sequence `e` either side of a z15 tile's west edge,
+ * half-way down it: the cones around the first read its tile and the
+ * west neighbour.
+ */
+ function acrossWestEdge() {
+ const home = tileCentre(ORIGIN.lon, ORIGIN.lat, 15);
+ const box = tileBounds(home.tile.x, home.tile.y, 15);
+ const lat = (box.north + box.south) / 2;
+ const items = [
+ stacItem({
+ id: 'e-0',
+ sequenceId: 'e',
+ lon: box.west + 0.00005,
+ lat,
+ nextId: 'e-1',
+ }),
+ stacItem({
+ id: 'e-1',
+ sequenceId: 'e',
+ lon: box.west - 0.00005,
+ lat,
+ prevId: 'e-0',
+ }),
+ ];
+ const west = `15/${home.tile.x - 1}/${home.tile.y}`;
+ return { items, west };
+ }
+
+ test(
+ 'the open picture’s own tile draws its cones at once; a neighbour’s join as it arrives',
+ { timeout: 10_000 },
+ async (t) => {
+ const { items, west } = acrossWestEdge();
+ const tiles = pictureTiles(items);
+ let release = null;
+ const env = await mounted({
+ items,
+ tiles: async (tile) => {
+ if (`${tile.z}/${tile.x}/${tile.y}` === west)
+ await new Promise((go) => (release = go));
+ return tiles(tile);
+ },
+ });
+ const cones = await withCones(t, env);
+ await env.instance.viewer.open('e-0');
+ const [lon, lat] = items[0].geometry.coordinates;
+ assert.equal(
+ pictureTilesAround({ lon, lat }).length,
+ 2,
+ 'the west neighbour is read too',
+ );
+ // Not awaited: a load that waited for the neighbour would hang here.
+ env.instance.selectSequence('e');
+ assert.ok(await until(() => release !== null), 'the neighbour is held');
+ assert.ok(
+ await until(() => cones.count() === 1),
+ 'the home tile’s cone shows',
+ );
+ assert.deepEqual(cones.ids(), ['e-0']);
+ release();
+ assert.ok(await until(() => cones.count() === 2), 'the neighbour’s joins');
+ },
+ );
+
+ test('a neighbour tile that failed is not counted as shown: › into it re-centres the cones there', async (t) => {
+ const { items, west } = acrossWestEdge();
+ const tiles = pictureTiles(items);
+ let failing = true;
+ const env = await mounted({
+ items,
+ tiles: (tile) => {
+ if (failing && `${tile.z}/${tile.x}/${tile.y}` === west)
+ throw Object.assign(new Error('Panoramax is busy'), { status: 503 });
+ return tiles(tile);
+ },
+ });
+ const cones = await withCones(t, env);
+ await env.instance.viewer.open('e-0');
+ await env.instance.selectSequence('e');
+ assert.ok(await until(() => cones.count() === 1));
+ // Let the neighbour's failure land.
+ assert.ok(await until(() => env.source.calls.tiles.includes(west)));
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ failing = false;
+ const asked = env.source.calls.tiles.filter((key) => key === west).length;
+ env.next.fire('click');
+ assert.ok(await until(() => env.poses.at(-1) === 'e-1'));
+ assert.ok(
+ await until(
+ () => env.source.calls.tiles.filter((key) => key === west).length > asked,
+ ),
+ 'the failed tile is asked again',
+ );
+ assert.ok(await until(() => cones.count() === 2), 'e-1 has its cone');
+ });
+
+ test('a busy or timed-out tile keeps its own message; only a body that is not a tile reads as unreadable', async (t) => {
+ const items = sequence('s', 3);
+ const failures = [
+ Object.assign(new Error('Panoramax is busy'), { status: 429 }),
+ Object.assign(new Error('Panoramax did not answer in time — try again'), {
+ status: 0,
+ }),
+ ];
+ for (const failure of failures) {
+ const env = await mounted({
+ items,
+ tiles: () => {
+ throw failure;
+ },
+ });
+ await withCones(t, env);
+ await env.instance.viewer.open('s-0');
+ await env.instance.selectSequence('s');
- assert.ok(await until(() => env.actions.errors.some(Boolean)));
- assert.equal(env.actions.errors.filter(Boolean).at(-1), failure.message);
++ assert.ok(await until(() => env.instance.sequenceStats().error));
++ assert.equal(env.instance.sequenceStats().error, failure.message);
+ }
+ });
diff --cc src/layers/streetLevel/providers/panoramax/viewer.test.mjs
index 000000000,3f8ae4789..9f5df8363
mode 000000,100644..100644
--- a/src/layers/streetLevel/providers/panoramax/viewer.test.mjs
+++ b/src/layers/streetLevel/providers/panoramax/viewer.test.mjs
@@@ -1,0 -1,341 +1,341 @@@
+ import assert from 'node:assert/strict';
+ import test from 'node:test';
+ import { PANORAMAX_SOURCES, createPanoramaxViewer } from './viewer.js';
+ import { normalizeItem } from './policy.js';
+ import { fakeHost, until } from '../../../../testSupport/kartaViewFakes.mjs';
+ import { stacItem } from '../../../../testSupport/panoramaxFixtures.mjs';
+
+ const photo = (options) =>
+ normalizeItem(stacItem({ lon: 2.35, lat: 48.85, ...options }));
+
+ const PHOTOS = {
+ flat: photo({ id: 'flat', prevId: 'p0', nextId: 'flat2', heading: 30 }),
+ flat2: photo({ id: 'flat2', prevId: 'flat', heading: 40 }),
+ pano: photo({ id: 'pano', pano: true, heading: 100, width: 5760 }),
+ bigPano: photo({ id: 'bigPano', pano: true, width: 11_000 }),
+ smallPano: photo({ id: 'smallPano', pano: true, width: 2048 }),
+ email: photo({ id: 'email', producer: '[email protected]' }),
+ };
+
+ function fakeRenderer() {
+ const view = { yaw: 0, pitch: 0, fov: 80 };
+ const images = [];
+ return {
+ images,
+ setImage: (image) => images.push(image),
+ setView(next) {
+ Object.assign(view, next);
+ },
+ getView: () => ({ ...view }),
+ resize() {},
+ clear() {},
+ destroy() {},
+ };
+ }
+
+ function setup() {
+ const loads = [];
+ const renderers = [];
+ const stepped = [];
+ const viewer = createPanoramaxViewer({
+ getPhoto: async (id) => {
+ if (!PHOTOS[id]) throw new Error('no such picture');
+ return PHOTOS[id];
+ },
+ step: async (from, delta) => (delta < 0 ? from.prevId : from.nextId),
+ onStep: (id) => {
+ stepped.push(id);
+ viewer.open(id).catch(() => {});
+ },
+ load: async (url, options) => {
+ loads.push({ url, ...options });
+ return { src: url, width: 1, height: 1 };
+ },
+ createRenderer: () => {
+ const renderer = fakeRenderer();
+ renderers.push(renderer);
+ return renderer;
+ },
+ });
+ const poses = [];
+ viewer.onPose((pose) => poses.push(pose));
+ return { viewer, poses, loads, renderers, stepped, host: fakeHost() };
+ }
+
+ const parts = (host) => {
+ const root = host.children[0];
+ const [picture, canvas, prev, next] = root.children;
+ return { root, picture, canvas, prev, next };
+ };
+
+ test('a flat picture shows its SD version with author, licence and a Panoramax link', async () => {
+ const { viewer, poses, loads, host } = setup();
+ await viewer.mount(host);
+ const { root, picture, canvas } = parts(host);
+ assert.equal(root.dataset.provider, 'panoramax', 'its colour in the CSS');
+ assert.match(root.attributes['aria-label'], /^Panoramax photo/);
+ await viewer.open('flat');
+ assert.equal(picture.hidden, false);
+ assert.equal(canvas.hidden, true);
+ assert.equal(
+ picture.src,
+ 'https://panoramax.example.org/pictures/flat/sd.jpg',
+ );
+ assert.deepEqual(
+ loads.map((l) => l.url),
+ [PHOTOS.flat.urls.sd],
+ );
+ const pose = poses.at(-1);
+ assert.equal(pose.providerId, 'panoramax');
+ assert.equal(pose.bearing, 30);
+ assert.equal(pose.isPano, false);
+ assert.equal(pose.creator, 'tester');
+ assert.equal(pose.license, 'CC BY-SA 4.0');
+ assert.equal(pose.sequenceId, 'seq-1');
+ assert.equal(
+ pose.externalUrl,
+ 'https://api.panoramax.xyz/#pic=flat&focus=pic',
+ );
+ assert.equal(viewer.supportsRenderModes(), true);
+ });
+
+ test('no creator in the caption for an account named by an email address', async () => {
+ const { viewer, poses, host } = setup();
+ await viewer.mount(host);
+ await viewer.open('email');
+ assert.equal(poses.at(-1).creator, null);
+ });
+
+ test('HD replaces SD only once the viewer is wide enough to use it', async (t) => {
+ const { viewer, loads, host } = setup();
+ await viewer.mount(host);
+ const { picture, root } = parts(host);
+ t.after(() => delete globalThis.devicePixelRatio);
+ globalThis.devicePixelRatio = 1;
+ picture.clientWidth = 400;
+ await viewer.open('flat');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ assert.equal(loads.length, 1, 'docked: SD is sharp enough');
+ // EXPAND on a wide screen.
+ picture.clientWidth = root.clientWidth = 2600;
+ viewer.resize();
+ assert.ok(await until(() => picture.src === PHOTOS.flat.urls.hd));
+ viewer.resize();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ assert.equal(
+ loads.filter((l) => l.url === PHOTOS.flat.urls.hd).length,
+ 1,
+ 'asked once',
+ );
+ });
+
+ test('a 360° picture shows its SD equirectangular image, then HD shrunk to 4,096 when expanded', async (t) => {
+ const { viewer, poses, loads, renderers, host } = setup();
+ await viewer.mount(host);
+ const { canvas, picture } = parts(host);
+ t.after(() => delete globalThis.devicePixelRatio);
+ globalThis.devicePixelRatio = 1;
+ canvas.clientWidth = 400;
+ await viewer.open('pano');
+ assert.equal(canvas.hidden, false);
+ assert.equal(picture.hidden, true);
+ assert.equal(viewer.supportsRenderModes(), false, 'no frame to fit');
+ const { signal, ...first } = loads[0];
+ assert.deepEqual(first, {
+ url: PHOTOS.pano.urls.sd,
+ crossOrigin: true,
+ resize: [2048, 1024],
+ failure: 'The Panoramax photo could not be loaded',
+ });
+ assert.equal(signal.aborted, false, 'the open can stop it');
+ assert.equal(poses.at(-1).isPano, true);
+ assert.equal(poses.at(-1).bearing, 100);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ assert.equal(loads.length, 1, 'docked: the 2,048 px SD is enough');
+ // Docked on a dense screen the canvas wants more, but the original is
+ // megabytes: not until the viewer is expanded.
+ canvas.clientWidth = 1800;
+ viewer.resize();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ assert.equal(loads.length, 1, 'docked: still SD only');
+ const root = canvas.parentNode;
+ root.closest = (selector) =>
- selector.includes('sl-viewer-wrap-expanded') ? {} : null;
++ selector.includes('sl-viewer-wrap:fullscreen') ? {} : null;
+ // EXPAND resizes more than once while the panel settles.
+ viewer.resize();
+ viewer.resize();
+ viewer.resize();
+ assert.ok(await until(() => renderers[0].images.length === 2));
+ assert.equal(
+ loads.filter((l) => l.url === PHOTOS.pano.urls.hd).length,
+ 1,
+ 'the original is fetched once',
+ );
+ const hd = loads.at(-1);
+ assert.equal(hd.url, PHOTOS.pano.urls.hd);
+ assert.deepEqual(hd.resize, [4096, 2048]);
+ assert.equal(hd.timeoutMs, 30_000);
+ assert.ok(hd.signal, 'abortable');
+ });
+
+ test('HD panoramas too big to decode, or no bigger than SD, are never fetched; nor while docked', () => {
+ const size = [4096, 2048];
+ const expanded = { expanded: true };
+ assert.equal(
+ PANORAMAX_SOURCES.panoSharp(PHOTOS.pano, size, { expanded: false }),
+ null,
+ );
+ assert.equal(PANORAMAX_SOURCES.panoSharp(PHOTOS.pano, size), null);
+ assert.equal(
+ PANORAMAX_SOURCES.panoSharp(PHOTOS.bigPano, size, expanded),
+ null,
+ );
+ assert.equal(
+ PANORAMAX_SOURCES.panoSharp(PHOTOS.smallPano, size, expanded),
+ null,
+ );
+ assert.deepEqual(
+ PANORAMAX_SOURCES.panoSharp({ ...PHOTOS.pano, width: 3000 }, size, expanded)
+ .resize,
+ [3000, 1500],
+ 'never enlarged',
+ );
+ // Without an SD derivative the HD one is the first and only.
+ const hdOnly = { ...PHOTOS.pano, urls: { ...PHOTOS.pano.urls, sd: null } };
+ assert.deepEqual(PANORAMAX_SOURCES.panoFirst(hdOnly), {
+ url: hdOnly.urls.hd,
+ width: 4096,
+ resize: [4096, 2048],
+ });
+ // …unless it is too big to decode: then no panorama, and the thumbnail.
+ const hugeOnly = { ...hdOnly, width: 11_904 };
+ assert.equal(PANORAMAX_SOURCES.panoFirst(hugeOnly), null);
+ assert.equal(PANORAMAX_SOURCES.hasPano(hugeOnly), false);
+ assert.deepEqual(PANORAMAX_SOURCES.flatFirst(hugeOnly).filter(Boolean), [
+ hugeOnly.urls.thumb,
+ ]);
+ assert.equal(PANORAMAX_SOURCES.panoSharp(hdOnly, size, expanded), null);
+ assert.equal(PANORAMAX_SOURCES.flatSharp(PHOTOS.flat, 2048), null);
+ assert.equal(
+ PANORAMAX_SOURCES.flatSharp(PHOTOS.flat, 2049),
+ PHOTOS.flat.urls.hd,
+ );
+ assert.equal(
+ PANORAMAX_SOURCES.hasPano({ isPano: true, urls: { sd: null, hd: null } }),
+ false,
+ );
+ });
+
+ test('› and ‹ follow the picture’s own links; the ends disable the buttons', async () => {
+ const { viewer, poses, stepped, host } = setup();
+ await viewer.mount(host);
+ const { next, prev } = parts(host);
+ await viewer.open('flat');
+ next.fire('click');
+ assert.ok(await until(() => poses.at(-1)?.imageId === 'flat2'));
+ assert.deepEqual(stepped, ['flat2']);
+ assert.ok(await until(() => next.disabled), 'flat2 is the last');
+ assert.equal(prev.disabled, false);
+ });
+
+ test('without WebGL a 360° picture shows its whole equirectangular image flat', async () => {
+ const loads = [];
+ const viewer = createPanoramaxViewer({
+ getPhoto: async () => PHOTOS.pano,
+ step: async () => null,
+ onStep() {},
+ load: async (url) => {
+ loads.push(url);
+ return { src: url };
+ },
+ createRenderer: () => {
+ throw new Error('no WebGL');
+ },
+ });
+ const host = fakeHost();
+ await viewer.mount(host);
+ await viewer.open('pano');
+ const { picture } = parts(host);
+ assert.equal(picture.hidden, false);
+ assert.equal(picture.src, PHOTOS.pano.urls.sd);
+ });
+
+ test('a picture whose SD fails falls back to the thumbnail; the original only for the expanded viewer', async () => {
+ const tried = [];
+ const viewer = createPanoramaxViewer({
+ getPhoto: async () => PHOTOS.flat,
+ step: async () => null,
+ onStep() {},
+ load: async (url) => {
+ tried.push(url);
+ if (!url.endsWith('thumb.jpg')) throw new Error('gone');
+ return { src: url };
+ },
+ });
+ const host = fakeHost();
+ await viewer.mount(host);
+ await viewer.open('flat');
+ assert.deepEqual(tried, [PHOTOS.flat.urls.sd, PHOTOS.flat.urls.thumb]);
+ assert.equal(parts(host).picture.src, PHOTOS.flat.urls.thumb);
+ // Expanded, the original is worth its megabytes.
+ tried.length = 0;
+ parts(host).root.closest = (selector) =>
- selector.includes('sl-viewer-wrap-expanded') ? {} : null;
++ selector.includes('sl-viewer-wrap:fullscreen') ? {} : null;
+ await viewer.open('flat');
+ assert.deepEqual(tried, [
+ PHOTOS.flat.urls.sd,
+ PHOTOS.flat.urls.hd,
+ PHOTOS.flat.urls.thumb,
+ ]);
+ });
+
+ test('a photo with no author to name is captioned with the instance holding it', () => {
+ const photo = normalizeItem(
+ stacItem({ id: 'x', lon: 1, lat: 2, producer: '[email protected]' }),
+ );
+ photo.via = 'panoramax.ign.fr';
+ assert.deepEqual(PANORAMAX_SOURCES.describe(photo), {
+ title: 'via panoramax.ign.fr',
+ creator: null,
+ license: 'CC BY-SA 4.0',
+ externalUrl: 'https://api.panoramax.xyz/#pic=x&focus=pic',
+ });
+ const named = { ...photo, creator: 'Robot8A' };
+ assert.equal(PANORAMAX_SOURCES.describe(named).title, null);
+ });
+
+ test('an SD panorama refused for its size is not fetched again as a flat photo', async () => {
+ const loads = [];
+ const viewer = createPanoramaxViewer({
+ getPhoto: async () => PHOTOS.pano,
+ step: async () => null,
+ onStep() {},
+ load: async (url, options = {}) => {
+ loads.push({ url, crossOrigin: options.crossOrigin });
+ // The picture host's SD file is past the viewer's size limits.
+ if (url === PHOTOS.pano.urls.sd)
+ throw Object.assign(new Error('too big'), { tooLarge: true });
+ return { src: url };
+ },
+ createRenderer: () => ({
+ setImage() {},
+ setView() {},
+ getView: () => ({ yaw: 0, pitch: 0, fov: 80 }),
+ resize() {},
+ clear() {},
+ destroy() {},
+ }),
+ });
+ const host = fakeHost();
+ await viewer.mount(host);
+ await viewer.open('pano');
+ const sdLoads = loads.filter((l) => l.url === PHOTOS.pano.urls.sd);
+ assert.equal(sdLoads.length, 1, 'tried once, as a bitmap, and refused');
+ assert.equal(sdLoads[0].crossOrigin, true);
+ const { picture } = parts(host);
+ assert.equal(picture.hidden, false, 'the flat fallback shows');
+ assert.notEqual(picture.src, PHOTOS.pano.urls.sd);
+ // Opened again later: the refused file is still not asked for.
+ await viewer.open('pano');
+ assert.equal(loads.filter((l) => l.url === PHOTOS.pano.urls.sd).length, 1);
+ });
diff --cc src/layers/streetLevel/registry.js
index 6fcfd9e48,ce7640137..ba0f986f2
--- a/src/layers/streetLevel/registry.js
+++ b/src/layers/streetLevel/registry.js
@@@ -9,38 -15,60 +15,50 @@@ export function filtersOf(provider)
* @property {string} label Chip text and link label, e.g. 'MAPILLARY'.
* @property {string|null} requiresKeyId Key-setup id the provider needs, or null when keyless.
* @property {string} pickPrefix Every primitive id the provider creates starts with it.
- * @property {{coverage: string}} colors The source's one colour.
+ * @property {{coverage: string}} colors The source's one colour, from policy.js PROVIDER_COLORS.
* @property {{html: string}} credit On-globe attribution while the provider is active.
+ * @property {boolean} [groundClick] No coverage: a ground click at street zoom opens its nearest image.
+ * @property {string} [requiresMapStack] Usable only on this map stack.
- * @property {boolean} [defaultOn] Default true.
++ * @property {boolean} [defaultOn] Default true; the first that defaults on is lit.
+ * @property {{kind: 'view-cone', color: string}} [marker] Default: GEV's pin.
+ * @property {Array<'pano'|'since'>} [filters] Filters it honours (default both).
+ * @property {{noun: string, action: string}} [coverageLabel] How the panel counts its lines and says what a click does (default: sequences, "click a line for its photos").
- * @property {boolean} [highlightsSequence] Its lines show the selected sequence (default true; the legend's "Selected" needs one).
+ * @property {'capture'|'upload'} [sinceBasis] What SINCE compares (default 'capture'); 'upload' puts a note under the slider while the provider is lit.
* @property {(context: ProviderContext) => ProviderInstance} create
*
* @typedef {object} ProviderContext Handed to `create()` once by the core.
- * @property {object} services Scene services: picking, input, render, sprites.
- * @property {object} services Scene services: picking, input, render, sprites, ground, terrain, scenePick (ground clicks need it).
++ * @property {object} services Scene services: picking, input, render, sprites, scenePick (ground clicks need it).
* @property {() => {pano: string, sinceMs: number|null}} getFilter Filter resolved against now; read it on every use so "since N days" keeps up.
* @property {() => boolean} isActive Layer enabled and this provider switched on.
- * @property {() => 'draped'|'terrain'} getSurface 'terrain' on Google 3D at street zoom: draw on bare earth.
- * @property {GroundCaster|null} groundCaster Bare-earth heights for terrain mode (groundCast.js); null without a terrain service.
- * @property {{meshAt: (lon: number, lat: number) => number|undefined, request: (points: Array<[number, number]>) => void, onSampled: (listener: (cells: Array<[number, number]>) => void) => () => void}|null} meshSampler Sampled Google 3D surface heights (meshSampler.js); pass `meshAt` to `castLine`.
* @property {() => void} notify Ask the core to publish a new UI snapshot.
- * @property {{openImage: (imageId: string) => Promise<boolean>}} actions
+ * @property {{openImage: (imageId: string, options?: {frame?: boolean}) => Promise<boolean>, openNearest: (point: {lon: number, lat: number}) => Promise<boolean>, reportError: (message: string|null) => void}} actions
++ * `openNearest` opens this provider's image nearest a point the user picked
++ * (needs `nearestImage`); `reportError` shows a viewer or key error in the
++ * panel, or withdraws this provider's own (null).
*
* @typedef {object} ProviderInstance
- * @property {() => Promise<{configured: boolean}>} status
+ * @property {(options?: {signal?: AbortSignal}) => Promise<{configured: boolean}>} status Whether a usable key is set; the core gives up on a hung answer through `signal`.
* @property {(viewer: object) => void} init Create collections, hidden.
* @property {(viewer: object) => void} activate Start drawing coverage for the camera.
* @property {() => void} deactivate Detach, clear coverage and selection, hide.
* @property {(viewer: object) => void} destroy
- * @property {() => void} refreshCoverage
* @property {(filter: {pano: string, sinceMs: number|null}) => void} setFilter The filter changed: redraw (reading `getFilter()`).
- * @property {(mode: 'draped'|'terrain') => void} [setSurface] Redraw coverage and cones for the new surface mode.
- * @property {() => {count: number, zoom: number|null, kind: string|null, loading: boolean, hint: string, error: string|null, keyRequired: boolean}} coverageStats
+ * @property {() => {count: number, loading: boolean, hint: string, error: string|null, keyRequired: boolean, keyRejected?: boolean}} coverageStats
- * @property {(pickId: string) => boolean} handlePick The id carries the provider's own prefix.
+ * @property {(pickId: string, click?: {groundPoint: () => {lon: number, lat: number}|null}) => boolean} handlePick The id carries the provider's own prefix; `groundPoint` is where the click met the ground.
* @property {(sequenceId: string) => Promise<void>} [selectSequence]
* @property {() => void} [clearSequence]
- * @property {() => {selectedId: string|null, images: number, loading: boolean}} [sequenceStats]
- * @property {(point: {lat: number, lon: number}, options?: {signal?: AbortSignal}) => Promise<string|null>} nearestImage An aborted lookup gives up (it may reject with an AbortError).
+ * @property {() => {selectedId: string|null, images: number, loading: boolean, error?: string|null}} [sequenceStats]
++ * @property {(point: {lat: number, lon: number}, options?: {signal?: AbortSignal}) => Promise<string|null>} [nearestImage] For ground clicks and `openNearest`; an aborted lookup gives up (it may reject with an AbortError).
* @property {ViewerAdapter} viewer
*
- * @typedef {object} GroundCaster
- * @property {(points: Array<[number, number]>, options?: {signal?: AbortSignal}) => Promise<boolean>} prepare Fetch the heights around [lon, lat] points; true when all are known.
- * @property {(lines: Array<Array<[number, number]>>, options?: {signal?: AbortSignal}) => Promise<boolean>} prepareLines
- * @property {(lon: number, lat: number) => number|null} groundAt Cached bare-earth ellipsoidal height.
- * @property {(coords: Array<[number, number]>) => Array<number>|null} castLine Densified [lon, lat, height, ...] or null.
- *
* @typedef {object} ViewerAdapter
* @property {(host: HTMLElement) => Promise<void>} mount Idempotent; may lazy-load a library.
* @property {(imageId: string) => Promise<void>} open Resolves once the image is on screen and a pose was emitted.
* @property {() => void} close Drop the image, keep the instance warm.
* @property {() => void} unmount Destroy the instance (host handed to another provider).
* @property {() => void} resize
- * @property {(host: HTMLElement) => Promise<void>} [prewarm]
* @property {(mode: 'letterbox'|'fill') => void} [setRenderMode]
+ * @property {() => boolean} [supportsRenderModes] False while the image has no frame to fit (a panorama): FIT / FILL hide.
* @property {(listener: (pose: StreetPose) => void) => () => void} onPose
*
* @typedef {object} StreetPose
diff --cc src/layers/streetLevel/selection.js
index dbc97137f,e3710dd8e..c76c3d9f5
--- a/src/layers/streetLevel/selection.js
+++ b/src/layers/streetLevel/selection.js
@@@ -18,9 -20,32 +18,32 @@@ export function createSelection({ state
const id = picking?.resolvePickId
? picking.resolvePickId(picked)
: picked?.id;
- const hit = parts.router.resolve(id);
+ const route = parts.router.resolve(id);
+ // Not ours: the ground handler decides whether it is the map itself.
- if (!route?.instance) {
++ if (!route) {
+ parts.openAtGround?.(click.position, picked);
+ return;
+ }
- const entry = state.providers.get(route.providerId);
- if (!entry?.on) return;
+ // The position marker is the core's own: nothing to select.
- if (hit?.instance) hit.instance.handlePick(hit.id);
++ if (!route.instance) return;
+ route.instance.handlePick(route.id, {
+ groundPoint: () => groundPointAt(viewer, click.position),
+ });
+ }
+
+ /** Lon/lat of the ground under a screen point, or null (sky, no picker). */
+ function groundPointAt(viewer, screenPosition) {
+ const position = state.services.scenePick?.pickGroundPosition?.(
+ viewer,
+ screenPosition,
+ );
+ const carto = position && Cesium.Cartographic.fromCartesian(position);
+ return carto
+ ? {
+ lon: Cesium.Math.toDegrees(carto.longitude),
+ lat: Cesium.Math.toDegrees(carto.latitude),
+ }
+ : null;
}
/**
diff --cc src/layers/streetLevel/selection.test.mjs
index b8ed81626,72e9e6e0c..f77388782
--- a/src/layers/streetLevel/selection.test.mjs
+++ b/src/layers/streetLevel/selection.test.mjs
@@@ -1,12 -1,26 +1,12 @@@
import assert from 'node:assert/strict';
-import test, { mock } from 'node:test';
+import test from 'node:test';
import * as Cesium from 'cesium';
import { createSelection } from './selection.js';
+import { createPickRouter } from './pickRouter.js';
-/**
- * The selection installed on a stand-in viewer. Animation frames queue until
- * `frame()` runs them; timers and Date.now() are mocked so a burst of moves
- * has a known timeline.
- */
-function harness({
- selected = false,
- router = null,
- providers = new Map(),
- services = {},
-} = {}) {
- const saved = {
- document: globalThis.document,
- requestAnimationFrame: globalThis.requestAnimationFrame,
- };
- mock.timers.enable({ apis: ['setTimeout', 'Date'] });
- const frames = [];
- globalThis.requestAnimationFrame = (task) => frames.push(task);
+/** The selection installed on a stand-in viewer, with what its clicks reach. */
- function harness({ selected = false } = {}) {
++function harness({ selected = false, services = {}, providers = [] } = {}) {
+ const saved = globalThis.document;
globalThis.document = new EventTarget();
// The document's keydown listeners, so a test can hand them any target.
const keyListeners = new Set();
@@@ -24,11 -38,13 +24,12 @@@
if (type === 'keydown') keyListeners.delete(listener);
removeListener(type, listener, options);
};
- const sequences = { selected, cleared: 0 };
+ const sequences = { selected, cleared: 0, selects: [] };
+ const opened = [];
+ const groundClicks = [];
- const picks = [];
- /** What the pointer is over: a line this layer owns, or nothing. */
+ /** What the pointer is over: a pick id, or nothing. */
const scene = { under: null };
const canvas = Object.assign(new EventTarget(), {
- style: {},
// Keep Cesium's handler on the canvas; there is no real document here.
disableRootEvents: true,
onwheel: null,
@@@ -40,44 -65,35 +41,47 @@@
viewer,
enabled: true,
clickHandler: null,
- services: { picking: null, input: null },
- providers,
+ services: { picking: null, input: null, ...services },
+ providers: new Map([
+ [
+ 'mapillary',
+ {
+ def: { id: 'mapillary', pickPrefix: 'mly:' },
+ instance: {
+ handlePick(id) {
+ if (id.startsWith('mly:seq:'))
+ sequences.selects.push(id.slice(8));
+ else if (id.startsWith('mly:img:')) opened.push(id.slice(8));
+ return true;
+ },
+ },
+ },
+ ],
++ ...providers,
+ ]),
};
- const selection = createSelection({
- state,
- parts: {
- router: router || {
- ownsPick: (id) => id === 'mly:seq:1',
- resolve: () => null,
- },
- hasSelectedSequence: () => sequences.selected,
- openAtGround: (position, picked) =>
- groundClicks.push({ position, picked }),
- clearSequences() {
- sequences.cleared++;
- sequences.selected = false;
- },
+ const parts = {
+ router: createPickRouter(() => state.providers.values(), {
+ positionId: 'sl:pos',
+ }),
+ hasSelectedSequence: () => sequences.selected,
++ openAtGround: (position, picked) => groundClicks.push({ position, picked }),
+ clearSequences() {
+ sequences.cleared++;
+ sequences.selected = false;
},
- });
+ };
+ const selection = createSelection({ state, parts });
selection.install(viewer);
- const onMove = state.clickHandler.getInputAction(
- Cesium.ScreenSpaceEventType.MOUSE_MOVE,
- );
- const onClick = state.clickHandler.getInputAction(
- Cesium.ScreenSpaceEventType.LEFT_CLICK,
- );
+ const action = (type) =>
+ state.clickHandler.getInputAction(Cesium.ScreenSpaceEventType[type]);
return {
state,
sequences,
+ opened,
++ groundClicks,
+ scene,
- click: () => action('LEFT_CLICK')({ position: { x: 10, y: 10 } }),
++ click: (x = 10) => action('LEFT_CLICK')({ position: { x, y: 10 } }),
/** A keydown reaching the document from `target`; the event as handled. */
key(key, target, { defaultPrevented = false } = {}) {
const event = {
@@@ -98,20 -136,85 +102,25 @@@
};
}
-test('hover picks at most every 120 ms through a burst of moves, ending on the last one', () => {
- const h = harness();
- try {
- // One second of a pointer moving at 60 Hz.
- for (let i = 0; i < 60; i++) {
- h.move(i);
- h.wait(16);
- }
- assert.ok(h.picks.length <= 9, `${h.picks.length} picks in ~1 s`);
- assert.ok(h.picks.length >= 7, `${h.picks.length} picks in ~1 s`);
- h.wait(200);
- assert.deepEqual(h.picks.at(-1), { x: 59, y: 10 }, 'the resting position');
- const settled = h.picks.length;
- h.wait(1000);
- assert.equal(h.picks.length, settled, 'a still pointer costs nothing');
- } finally {
- h.restore();
- }
-});
-
-test('hover does not pick while a mouse button is held', () => {
- const h = harness();
- try {
- h.buttons('pointerdown', 1);
- h.move(1);
- h.wait(200);
- assert.equal(h.picks.length, 0, 'a drag in progress');
- h.buttons('pointerup', 0);
- h.move(2);
- h.wait(200);
- assert.equal(h.picks.length, 1);
- } finally {
- h.restore();
- }
-});
-
-test('a camera that never stops (orbit, tracking) keeps hover throttled, not off', () => {
+test('a click on a line selects its sequence, on a cone opens its image, elsewhere does nothing', () => {
const h = harness();
try {
- // An orbiting or tracking camera raises moveStart and never moveEnd.
- h.camera.moveStart.raiseEvent();
- for (let i = 0; i < 60; i++) {
- h.move(i);
- h.wait(16);
+ h.scene.under = 'mly:seq:abc';
+ h.click();
+ assert.deepEqual(h.sequences.selects, ['abc']);
+ h.scene.under = 'mly:img:42';
+ h.click();
+ assert.deepEqual(h.opened, ['42']);
+ for (const under of [null, 'cctv:7', 'sl:pos']) {
+ h.scene.under = under;
+ h.click();
}
- assert.ok(h.picks.length >= 7, `${h.picks.length} picks in ~1 s`);
- assert.ok(h.picks.length <= 9, `${h.picks.length} picks in ~1 s`);
- } finally {
- h.restore();
- }
-});
-
-test('when the camera stops, the pointer is picked again so the cursor cannot stick', () => {
- const h = harness();
- try {
- h.scene.under = 'mly:seq:1';
- h.move(5);
- h.wait(200);
- assert.equal(h.canvas.style.cursor, 'pointer', 'over a line');
- // The camera moves the line out from under a still pointer.
- h.camera.moveStart.raiseEvent();
- h.scene.under = null;
- h.camera.moveEnd.raiseEvent();
- h.wait(200);
- assert.equal(h.picks.length, 2, 'one pick when the camera rests');
- assert.deepEqual(h.picks.at(-1), { x: 5, y: 10 });
- assert.equal(h.canvas.style.cursor, '', 'the pointer cursor is gone');
- } finally {
- h.restore();
- }
-});
-
-test('a hover frame queued before the layer went off does not pick', () => {
- const h = harness();
- try {
- h.move(1);
- h.state.enabled = false;
- h.wait(200);
- assert.equal(h.picks.length, 0);
+ assert.deepEqual([h.sequences.selects, h.opened], [['abc'], ['42']]);
++ // The marker is ours; nothing and another layer's pick go to the ground.
++ assert.deepEqual(
++ h.groundClicks.map(({ picked }) => picked?.id),
++ [undefined, 'cctv:7'],
++ );
} finally {
h.restore();
}
@@@ -170,3 -273,61 +179,64 @@@ test('Esc in a text field or rich-text
h.restore();
}
});
+
+ test('a click on nothing of ours goes to the ground handler with the pick, which decides', () => {
+ const h = harness();
+ try {
+ h.click(5);
+ h.scene.under = 'flight:abc';
+ h.click(6);
+ assert.deepEqual(
+ h.groundClicks.map(({ position, picked }) => [position.x, picked?.id]),
+ [
+ [5, undefined],
+ [6, 'flight:abc'],
+ ],
+ );
+ } finally {
+ h.restore();
+ }
+ });
+
+ test('a click on a provider line hands it the ground under the click, measured only if asked', () => {
+ const handled = [];
- const instance = {
- handlePick: (id, click) => handled.push({ id, click }),
- };
+ const groundPicks = [];
+ const h = harness({
- router: {
- ownsPick: () => true,
- resolve: (id) => ({ providerId: 'kartaview', instance, id }),
- },
- providers: new Map([['kartaview', { on: true }]]),
++ providers: [
++ [
++ 'kartaview',
++ {
++ def: { id: 'kartaview', pickPrefix: 'kv:' },
++ instance: {
++ handlePick: (id, click) => handled.push({ id, click }),
++ },
++ },
++ ],
++ ],
+ services: {
+ scenePick: {
+ pickGroundPosition: (viewer, position) => {
+ groundPicks.push(position);
+ return Cesium.Cartesian3.fromDegrees(-83.0458, 42.3314, 190);
+ },
+ },
+ },
+ });
+ try {
+ h.scene.under = 'kv:line:14/1/2/3';
+ h.click(40);
+ assert.equal(handled.length, 1);
+ assert.equal(handled[0].id, 'kv:line:14/1/2/3');
+ assert.equal(
+ groundPicks.length,
+ 0,
+ 'no depth read until the provider asks',
+ );
+ const point = handled[0].click.groundPoint();
+ assert.ok(Math.abs(point.lon + 83.0458) < 1e-9);
+ assert.ok(Math.abs(point.lat - 42.3314) < 1e-9);
+ assert.deepEqual(groundPicks, [{ x: 40, y: 10 }]);
+ } finally {
+ h.restore();
+ }
+ });
diff --cc src/layers/streetLevel/sequenceCones.js
index 6c88871b9,8eb79b29f..b18f2cc57
--- a/src/layers/streetLevel/sequenceCones.js
+++ b/src/layers/streetLevel/sequenceCones.js
@@@ -1,29 -1,26 +1,22 @@@
import * as Cesium from 'cesium';
import { imageConeGlyph } from './glyphs.js';
import { passesImageryFilter } from './filter.js';
-import { refineHeights } from './groundCast.js';
import { createHorizonCull, metresBetween } from './view.js';
- import {
- COLORS,
- IMAGE_CONE_MIN_SPACING_M,
- IMAGE_CONE_SIZE_PX,
- PICK_PREFIX,
- } from './policy.js';
-
- const SPRITE_ID = 'street-level:mapillary-cones';
-import { meshCellKey } from './meshSampler.js';
--
- /** Normalize a graph image record into the shape the cones use. */
- function normalizeSequenceImage(record) {
- const coordinates = record?.geometry?.coordinates;
- if (!Array.isArray(coordinates) || coordinates.length < 2) return null;
- return {
- id: String(record.id),
- lon: Number(coordinates[0]),
- lat: Number(coordinates[1]),
- compassAngle: Number(record.compass_angle) || 0,
- capturedAt: Number(record.captured_at) || 0,
- isPano: record.is_pano === true,
- };
- }
-/** How many recently viewed sequences keep their image list in memory. */
-const SEQUENCE_CACHE_SIZE = 40;
++import { msg } from '../../i18n/index.js';
+
+ /** Cones closer than this to the previous kept one are dropped. */
+ export const IMAGE_CONE_MIN_SPACING_M = 3;
+ export const IMAGE_CONE_SIZE_PX = 26;
+
+ /**
+ * @typedef {object} ConeImage One image of a sequence, as the cones draw it.
+ * @property {string} id
+ * @property {number} lon
+ * @property {number} lat
+ * @property {number} compassAngle Degrees clockwise from north.
+ * @property {number} capturedAt Epoch ms (0 when unknown).
+ * @property {boolean} isPano
+ */
/** Drop images closer than the spacing to the previous kept one. */
export function thinImages(images, spacingM = IMAGE_CONE_MIN_SPACING_M) {
@@@ -38,8 -35,33 +31,35 @@@
return kept;
}
- /** Image cones for one selected sequence. */
- export function createSequences({ state, source, parts }) {
+ /**
- * Image cones for one selected sequence, any provider's. A cone's pick id is
- * `pickPrefix` + the image id; 360° images draw as rings.
++ * Image cones for one selected sequence, any provider's, clamped to the
++ * ground. A cone's pick id is `pickPrefix` + the image id; 360° images draw
++ * as rings. Why a sequence could not load stays in `state.sequence.error`
++ * until it goes.
+ *
+ * @param {object} options
+ * @param {object} options.state Provider state: `context`, `services`, `viewer`, `sequence`.
+ * @param {(sequenceId: string, init: {signal: AbortSignal}) => Promise<Array<ConeImage>>} options.loadImages
+ * The sequence's images in capture order, thinned (see `thinImages`).
+ * @param {{coverage: string}} options.colors
+ * @param {string} options.pickPrefix Pick-id prefix of the cones.
+ * @param {string} options.spriteId Sprite-order id of the cone collection.
+ * @param {string} options.renderKey Render-governor reason.
- * @param {(sequenceId: string, selected: boolean) => void} [options.onHighlight]
- * Highlight (or stop highlighting) the sequence's coverage line.
++ * @param {(sequenceId: string|null) => void} [options.onHighlight]
++ * Highlight the sequence's coverage line (null: none).
+ * @param {(image: ConeImage, filter: object) => boolean} [options.passes]
+ * Whether the imagery filter keeps a cone.
+ */
+ export function createSequenceCones({
+ state,
+ loadImages,
+ colors,
+ pickPrefix,
+ spriteId,
+ renderKey,
+ onHighlight = () => {},
+ passes = passesImageryFilter,
+ }) {
const { render, sprites } = state.services;
function requestRender() {
@@@ -47,11 -69,12 +67,11 @@@
}
function notify() {
- state.notify?.();
+ state.context.notify();
}
- const nothingDrawn = () => ({ images: [], cones: [], cells: new Set() });
- /** Drawn cones, plus the mesh cells under them, so a sample moves only those. */
- let drawn = nothingDrawn();
+ /** Drawn cone billboards. */
+ let cones = [];
// The cones skip the depth test: hide the ones behind the globe.
const horizon = createHorizonCull({
@@@ -80,24 -145,25 +100,24 @@@
const collection = state.sequence.collection;
if (!collection) return;
collection.removeAll();
- drawn = { ...nothingDrawn(), images };
- const heights = coneHeights(images);
+ cones = [];
// One colour per source; 360° images keep the ring shape.
- const cone = imageConeGlyph({ size: 32, color: COLORS.coverage });
+ const cone = imageConeGlyph({ size: 32, color: colors.coverage });
const ring = imageConeGlyph({
size: 32,
- color: COLORS.coverage,
+ color: colors.coverage,
pano: true,
});
// Resolved now, so a "since N days" window keeps up with the clock.
- const filter = state.getFilter();
+ const filter = state.context.getFilter();
- images.forEach((image, index) => {
- if (!passes(image, filter)) return;
- const height = heights?.[index] ?? null;
+ for (const image of images) {
- if (!passesImageryFilter(image, filter)) continue;
++ if (!passes(image, filter)) continue;
const billboard = collection.add({
- id: `${PICK_PREFIX.image}${image.id}`,
+ id: `${pickPrefix}${image.id}`,
- ...placement(image, height),
+ position: Cesium.Cartesian3.fromDegrees(image.lon, image.lat),
+ heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
image: image.isPano ? ring : cone,
- imageId: image.isPano ? 'mly-cone-pano' : 'mly-cone',
+ imageId: image.isPano ? `${spriteId}:pano` : `${spriteId}:flat`,
width: IMAGE_CONE_SIZE_PX,
height: IMAGE_CONE_SIZE_PX,
rotation: -Cesium.Math.toRadians(image.compassAngle),
@@@ -112,8 -210,19 +132,11 @@@
requestRender();
}
- /** Select a sequence: highlight its line and load its image cones. */
- async function select(sequenceId) {
- function remember(sequenceId, images) {
- const { cache } = state.sequence;
- cache.delete(sequenceId);
- cache.set(sequenceId, images);
- while (cache.size > SEQUENCE_CACHE_SIZE)
- cache.delete(cache.keys().next().value);
- }
-
+ /**
+ * Select a sequence: highlight its line and load its image cones. `force`
+ * reloads a selected one (a provider that loads part of a sequence moved on).
+ */
+ async function select(sequenceId, { force = false } = {}) {
if (!sequenceId || !state.viewer) return;
// Already on screen, or already on its way.
if (
@@@ -121,9 -231,21 +145,9 @@@
(state.sequence.images.length || state.sequence.abort)
)
return;
- if (state.sequence.selectedId && state.sequence.selectedId !== sequenceId)
- onHighlight(state.sequence.selectedId, false);
state.sequence.abort?.abort();
state.sequence.selectedId = sequenceId;
- parts.coverage.highlight(sequenceId);
- onHighlight(sequenceId, true);
- const cached = force ? null : state.sequence.cache.get(sequenceId);
- if (cached) {
- state.sequence.abort = null;
- state.sequence.loading = false;
- state.sequence.images = cached;
- renderCones(cached);
- state.context.actions.reportError(null);
- notify();
- return;
- }
++ onHighlight(sequenceId);
// The previous sequence's cones must not stay clickable under the new
// highlight while this one loads, nor after its load fails.
clearCones();
@@@ -131,29 -253,24 +155,24 @@@
const controller = new AbortController();
state.sequence.abort = controller;
state.sequence.loading = true;
+ // An earlier sequence's error does not belong to this one.
+ state.sequence.error = null;
notify();
try {
- const records = await source.getSequenceImages(sequenceId, {
+ const images = await loadImages(sequenceId, {
signal: controller.signal,
});
if (controller.signal.aborted) return;
- const images = thinImages(
- records
- .map(normalizeSequenceImage)
- .filter(Boolean)
- .sort((a, b) => a.capturedAt - b.capturedAt),
- );
- remember(sequenceId, images);
state.sequence.images = images;
renderCones(images);
- state.context.actions.reportError(null);
+ state.sequence.error = null;
} catch (error) {
if (!controller.signal.aborted) {
// Nothing to show: drop the highlight, so a click asks again.
- parts.coverage.highlight(null);
- onHighlight(sequenceId, false);
++ onHighlight(null);
state.sequence.selectedId = null;
- state.sequence.error = error?.message || 'Sequence images unavailable';
- state.context.actions.reportError(
- error?.message || 'Sequence images unavailable',
- );
++ state.sequence.error =
++ error?.message || msg('Sequence images unavailable');
}
} finally {
if (state.sequence.abort === controller) {
@@@ -167,7 -284,8 +186,7 @@@
function clearSelection() {
state.sequence.abort?.abort();
state.sequence.abort = null;
- if (state.sequence.selectedId) parts.coverage.highlight(null);
- if (state.sequence.selectedId)
- onHighlight(state.sequence.selectedId, false);
++ if (state.sequence.selectedId) onHighlight(null);
state.sequence.selectedId = null;
state.sequence.loading = false;
clearCones();
@@@ -190,10 -311,11 +209,10 @@@
function destroy(viewer) {
state.sequence.abort?.abort();
horizon.stop();
- drawn = nothingDrawn();
- stopMeshListener?.();
+ cones = [];
const collection = state.sequence.collection;
if (collection) {
- sprites?.unregisterSpriteCollection?.(SPRITE_ID, collection);
+ sprites?.unregisterSpriteCollection?.(spriteId, collection);
viewer?.scene?.primitives?.remove(collection);
state.sequence.collection = null;
}
diff --cc src/layers/streetLevel/sequenceCones.test.mjs
index faae9f95b,000000000..0e301cffc
mode 100644,000000..100644
--- a/src/layers/streetLevel/sequenceCones.test.mjs
+++ b/src/layers/streetLevel/sequenceCones.test.mjs
@@@ -1,200 -1,0 +1,217 @@@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import * as Cesium from 'cesium';
+import { resolveFilter } from './filter.js';
- import { createSequences } from './sequences.js';
++import { createSequenceCones, thinImages } from './sequenceCones.js';
+
+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+/** A billboard collection that remembers the cones on the globe. */
+function cones() {
+ const items = [];
+ return {
+ items,
+ show: true,
+ add(options) {
+ items.push(options);
+ return options;
+ },
+ removeAll() {
+ items.length = 0;
+ },
+ };
+}
+
+/** A source whose sequence lookups the test answers, one call at a time. */
+function deferredSource() {
+ const calls = [];
+ return {
+ calls,
+ getSequenceImages(sequenceId, { signal } = {}) {
+ return new Promise((resolve, reject) => {
+ calls.push({ sequenceId, signal, resolve, reject });
+ });
+ },
+ /** The latest lookup for a sequence. */
+ last(sequenceId) {
+ return calls.filter((call) => call.sequenceId === sequenceId).at(-1);
+ },
+ };
+}
+
+/** Graph image records for a sequence, a few metres apart. */
+function records(sequenceId, count = 2) {
+ return Array.from({ length: count }, (_, i) => ({
+ id: `${sequenceId}-${i}`,
+ geometry: { coordinates: [-121.49 + i * 0.001, 38.58] },
+ compass_angle: 90,
+ captured_at: 1_700_000_000_000 + i,
+ }));
+}
+
+function setup() {
+ const source = deferredSource();
+ /** Every highlight asked of the coverage: a sequence id, or null for none. */
+ const highlights = [];
+ const state = {
+ services: {},
+ viewer: {},
+ filter: { pano: 'all', sinceDays: 0 },
- getFilter: () => resolveFilter(state.filter),
- notify() {},
++ context: {
++ getFilter: () => resolveFilter(state.filter),
++ notify() {},
++ },
+ sequence: {
+ selectedId: null,
+ images: [],
+ collection: cones(),
+ loading: false,
+ error: null,
+ abort: null,
+ },
+ };
- const parts = {
- coverage: {
- highlight: (id) => highlights.push(id),
++ const sequences = createSequenceCones({
++ state,
++ async loadImages(sequenceId, { signal }) {
++ const list = await source.getSequenceImages(sequenceId, { signal });
++ return thinImages(
++ list.map((record) => ({
++ id: String(record.id),
++ lon: record.geometry.coordinates[0],
++ lat: record.geometry.coordinates[1],
++ compassAngle: Number(record.compass_angle) || 0,
++ capturedAt: Number(record.captured_at) || 0,
++ isPano: record.is_pano === true,
++ })),
++ );
+ },
- };
- const sequences = createSequences({ state, source, parts });
++ colors: { coverage: '#05cb63' },
++ pickPrefix: 'mly:img:',
++ spriteId: 'street-level:test-cones',
++ renderKey: 'test-sequence',
++ onHighlight: (id) => highlights.push(id),
++ });
+ const drawn = () =>
+ state.sequence.collection.items.map((cone) => cone.id.split(':').at(-1));
+ return { state, source, sequences, highlights, drawn };
+}
+
+test('a failed sequence load leaves no stale cones and can be retried', async () => {
+ const { state, source, sequences, highlights, drawn } = setup();
+ sequences.select('A');
+ source.last('A').resolve(records('A'));
+ await settle();
+ assert.deepEqual(drawn(), ['A-0', 'A-1']);
+
+ sequences.select('B');
+ assert.deepEqual(drawn(), [], "A's cones go while B loads");
+ source.last('B').reject(new Error('Sequence images unavailable'));
+ await settle();
+ assert.deepEqual(drawn(), [], 'nothing of A is left to click');
+ assert.equal(state.sequence.loading, false);
+ assert.equal(state.sequence.selectedId, null, 'B is not left highlighted');
+ assert.equal(highlights.at(-1), null);
+ assert.equal(state.sequence.error, 'Sequence images unavailable');
+
+ // Clicking B again asks again, without the old error.
+ sequences.select('B');
+ assert.equal(source.calls.filter((c) => c.sequenceId === 'B').length, 2);
+ assert.equal(state.sequence.error, null, 'not shown while B loads again');
+ source.last('B').resolve(records('B'));
+ await settle();
+ assert.deepEqual(drawn(), ['B-0', 'B-1']);
+ assert.equal(state.sequence.selectedId, 'B');
+ assert.equal(state.sequence.error, null, 'cleared once B loads');
+});
+
+test('a late answer for a superseded sequence draws nothing', async () => {
+ const { state, source, sequences, drawn } = setup();
+ sequences.select('A');
+ sequences.select('B');
+ assert.equal(source.last('A').signal.aborted, true, 'A was cancelled');
+ source.last('B').resolve(records('B'));
+ await settle();
+ source.last('A').resolve(records('A'));
+ await settle();
+ assert.deepEqual(drawn(), ['B-0', 'B-1']);
+ assert.equal(state.sequence.selectedId, 'B');
+ assert.equal(state.sequence.loading, false);
+});
+
+test('a second click on a loading sequence does not start another lookup', async () => {
+ const { source, sequences } = setup();
+ sequences.select('A');
+ sequences.select('A');
+ assert.equal(source.calls.length, 1);
+ assert.equal(source.calls[0].signal.aborted, false);
+});
+
+test('clearSelection cancels the lookup and drops the highlight', async () => {
+ const { state, source, sequences, highlights, drawn } = setup();
+ sequences.select('A');
+ sequences.clearSelection();
+ assert.equal(source.last('A').signal.aborted, true);
+ assert.deepEqual(highlights, ['A', null]);
+ assert.equal(state.sequence.selectedId, null);
+ assert.equal(state.sequence.loading, false);
+ assert.equal(state.sequence.error, null, 'an error about it goes too');
+ source.last('A').resolve(records('A'));
+ await settle();
+ assert.deepEqual(drawn(), [], 'the late answer draws nothing');
+});
+
+test('cones are clamped to the ground and turned to their compass angle', async () => {
+ const { state, source, sequences } = setup();
+ sequences.select('A');
+ source.last('A').resolve(records('A', 2));
+ await settle();
+ const items = state.sequence.collection.items;
+ assert.equal(items.length, 2);
+ for (const cone of items) {
+ assert.equal(cone.heightReference, Cesium.HeightReference.CLAMP_TO_GROUND);
+ assert.equal(cone.rotation, -Cesium.Math.toRadians(90));
+ }
+});
+
+test('cones behind the globe are hidden, and show again from the other side', async () => {
+ const { state, source, sequences } = setup();
+ const view = { lon: -121.49, lat: 38.58, height: 20_000_000 };
+ const preRender = new Set();
+ state.viewer = {
+ camera: {
+ get positionWC() {
+ return Cesium.Cartesian3.fromDegrees(view.lon, view.lat, view.height);
+ },
+ },
+ scene: {
+ preRender: {
+ addEventListener(listener) {
+ preRender.add(listener);
+ return () => preRender.delete(listener);
+ },
+ },
+ },
+ };
+ sequences.select('A');
+ // One image under the camera, one near its antipode.
+ source.last('A').resolve([
+ ...records('A', 1),
+ {
+ id: 'A-far',
+ geometry: { coordinates: [58.51, -38.58] },
+ captured_at: 1_800_000_000_000,
+ },
+ ]);
+ await settle();
+ const [near, far] = state.sequence.collection.items;
+ assert.equal(near.show, true, 'the near side stays visible');
+ assert.equal(far.show, false, 'the far side does not show through');
+ // Fly round to the other hemisphere: the two swap.
+ view.lon = 58.51;
+ view.lat = -38.58;
+ for (const listener of [...preRender]) listener();
+ assert.equal(near.show, false);
+ assert.equal(far.show, true);
+ sequences.clearSelection();
+ assert.equal(preRender.size, 0, 'the cull listener is gone');
+});
diff --cc src/layers/streetLevel/state.js
index e5bc8209f,a7bf85e37..f9e5e4c88
--- a/src/layers/streetLevel/state.js
+++ b/src/layers/streetLevel/state.js
@@@ -69,7 -57,13 +52,10 @@@ export function createState({ services
...freshStreet(),
},
- marker: { collection: null, billboard: null },
+ /** Whether the camera is low enough for a ground click to open an image. */
+ groundClickReady: false,
+
- /** 'terrain' on Google 3D at street zoom (overlays on the bare earth), else 'draped'. */
- surface: 'draped',
-
+ marker: { collection: null, billboard: null, look: null },
clickHandler: null,
};
}
diff --cc src/layers/streetLevel/street-level-unique-tiles.test.mjs
index 000000000,52e7b6aea..169d14e28
mode 000000,100644..100644
--- a/src/layers/streetLevel/street-level-unique-tiles.test.mjs
+++ b/src/layers/streetLevel/street-level-unique-tiles.test.mjs
@@@ -1,0 -1,31 +1,18 @@@
+ import test from 'node:test';
+ import assert from 'node:assert/strict';
+ import { tilesForBbox } from './tileMath.js';
+
-test('reachable polar dateline coverage ranks 24 distinct tiles before overview truncation', () => {
- // coverage uses the actual view bbox above zoom 1; polar views can wrap.
- const bbox = [-10, 60, -20, 85];
- const result = tilesForBbox(bbox, 3);
- const keys = result.tiles.map((tile) => `${tile.x}/${tile.y}/${tile.z}`);
++const keysOf = (tiles) => tiles.map((tile) => `${tile.x}/${tile.y}/${tile.z}`);
++
++test('a polar view across the date line ranks 24 distinct tiles', () => {
++ // The halves of [-10, 60, -20, 85] share a column at z3.
++ const keys = keysOf(tilesForBbox([-10, 60, -20, 85], 3));
+ assert.equal(keys.length, 24);
+ assert.equal(new Set(keys).size, 24);
- assert.equal(result.total, 24);
- assert.equal(result.truncated, false);
- const overview = tilesForBbox(bbox, 3, { limit: 16 });
- assert.equal(overview.total, 24);
- assert.equal(overview.tiles.length, 16);
- assert.equal(
- new Set(overview.tiles.map((tile) => `${tile.x}/${tile.y}/${tile.z}`)).size,
- 16,
- );
- assert.equal(overview.truncated, true);
+ });
+
-test('a limit that fits every distinct tile is not spent on repeats', () => {
- // Before de-duplication this box yielded 27 entries for 24 tiles, so a
- // 24-slot overview held repeats and still reported itself truncated.
- const result = tilesForBbox([-10, 60, -20, 85], 3, { limit: 24 });
- const keys = result.tiles.map((tile) => `${tile.x}/${tile.y}/${tile.z}`);
- assert.equal(new Set(keys).size, 24);
- assert.equal(result.truncated, false);
++test('a limit is not spent on repeats', () => {
++ const keys = keysOf(tilesForBbox([-10, 60, -20, 85], 3, { limit: 16 }));
++ assert.equal(keys.length, 16);
++ assert.equal(new Set(keys).size, 16);
+ });
diff --cc src/layers/streetLevel/tileMath.js
index 7e317f63d,350188200..65dfb9cb9
--- a/src/layers/streetLevel/tileMath.js
+++ b/src/layers/streetLevel/tileMath.js
@@@ -72,48 -77,97 +72,55 @@@ export function normalizeBbox(input)
}
/**
- * Squared distance (in tiles) from tile (x, y)'s centre to the segment
- * `from` → `to` at zoom z, measured the short way round the date line.
+ * Tiles at zoom z covering a [west, south, east, north] box (west > east
+ * crosses the date line), nearest to `from` first (default: the box centre),
+ * capped at `limit`. Distances are measured the short way round ±180°.
+ * @param {{limit?: number, from?: {lon: number, lat: number}|null}} [options]
+ * @returns {Array<{x:number,y:number,z:number}>}
*/
-function segmentDistance2(tile, from, to, z) {
- const n = 2 ** z;
- const px = tile.x + 0.5;
- const py = tile.y + 0.5;
- const ax = tileXAt(from.lon, z);
- const ay = tileYAt(from.lat, z);
- let bx = to ? tileXAt(to.lon, z) : ax;
- const by = to ? tileYAt(to.lat, z) : ay;
- if (bx - ax > n / 2) bx -= n;
- else if (ax - bx > n / 2) bx += n;
- let best = Infinity;
- for (const shift of [-n, 0, n]) {
- const x = px + shift;
- const vx = bx - ax;
- const vy = by - ay;
- const len2 = vx * vx + vy * vy;
- const t = len2
- ? Math.max(0, Math.min(1, ((x - ax) * vx + (py - ay) * vy) / len2))
- : 0;
- const dx = x - (ax + t * vx);
- const dy = py - (ay + t * vy);
- best = Math.min(best, dx * dx + dy * dy);
- }
- return best;
-}
-
-/**
- * Tiles at zoom z covering a bbox (west > east crosses the date line), from
- * the centre outwards, capped at `limit`. With `focus`, tiles rank by distance
- * from the segment `from` (ground under the camera) to `to` (screen centre):
- * a tilted view's box centre can sit kilometres ahead of both.
- * @param {{limit?: number, focus?: {from: {lon: number, lat: number}, to?: {lon: number, lat: number}|null}|null}} [options]
- * @returns {{tiles: Array<{x:number,y:number,z:number}>, truncated: boolean, total: number}}
- */
-export function tilesForBbox(bbox, z, { limit = Infinity, focus = null } = {}) {
- const n = 2 ** z;
- const tiles = [];
- let centre;
- if (Array.isArray(bbox) && Number(bbox[0]) > Number(bbox[2])) {
- // A box across the date line comes as west > east: split it at ±180°.
- const [west, south, east, north] = bbox.map(Number);
- for (const half of [
- [west, south, 180, north],
- [-180, south, east, north],
- ]) {
- const box = normalizeBbox(half);
- if (box) tiles.push(...tileGrid(box, z).tiles);
- }
- centre = {
- x: ((lonToTileX(west, z) + lonToTileX(east, z) + n) / 2) % n,
- y: (latToTileY(north, z) + latToTileY(south, z)) / 2,
- };
- } else {
- const box = normalizeBbox(bbox);
- if (!box) return { tiles: [], truncated: false, total: 0 };
- const grid = tileGrid(box, z);
- tiles.push(...grid.tiles);
- centre = { x: (grid.x0 + grid.x1) / 2, y: (grid.y0 + grid.y1) / 2 };
- }
- const distance2 = focus?.from
- ? (tile) => segmentDistance2(tile, focus.from, focus.to, z)
- : (tile) => {
- // Measured the short way round the date line.
- const dx = Math.abs(tile.x - centre.x);
- return Math.min(dx, n - dx) ** 2 + (tile.y - centre.y) ** 2;
- };
- // The date-line halves share a column when the gap between east and west is
- // narrower than a tile; count that column once so a capped overview does not
- // spend its slots on repeats. Each tile's distance is computed once; ties keep
- // their row order.
- const unique = [
+export function tilesForBbox(bbox, z, { limit = Infinity, from = null } = {}) {
+ const [west, south, east, north] = Array.isArray(bbox)
+ ? bbox.map(Number)
+ : [];
+ const across = west > east;
+ // A box across the date line is split at ±180°.
+ const halves = across
+ ? [
+ [west, south, 180, north],
+ [-180, south, east, north],
+ ]
+ : [bbox];
- const grid = halves
- .map(normalizeBbox)
- .filter(Boolean)
- .flatMap((box) => tileGrid(box, z));
++ // The halves share a column when the gap between east and west is
++ // narrower than a tile: count it once, so a capped set holds no repeats.
++ const grid = [
+ ...new Map(
- tiles.map((tile) => [`${tile.x}/${tile.y}/${tile.z}`, tile]),
++ halves
++ .map(normalizeBbox)
++ .filter(Boolean)
++ .flatMap((box) => tileGrid(box, z))
++ .map((tile) => [`${tile.x}/${tile.y}`, tile]),
+ ).values(),
+ ];
- const ranked = unique
- .map((tile) => ({ tile, d: distance2(tile) }))
+ const n = 2 ** z;
+ const centre = from || {
+ lon: wrapLon(west + (east - west + (across ? 360 : 0)) / 2),
+ lat: (south + north) / 2,
+ };
+ const cx = tileXAt(wrapLon(centre.lon), z);
+ const cy = tileYAt(centre.lat, z);
+ // Each tile's distance is computed once; ties keep their row order.
+ const ranked = grid
+ .map((tile) => {
+ const dx = Math.abs(tile.x + 0.5 - cx);
+ const d = Math.min(dx, n - dx) ** 2 + (tile.y + 0.5 - cy) ** 2;
+ return { tile, d };
+ })
.sort((a, b) => a.d - b.d)
.map(({ tile }) => tile);
- const truncated = ranked.length > limit;
- return {
- tiles: truncated ? ranked.slice(0, limit) : ranked,
- truncated,
- total: ranked.length,
- };
+ return ranked.slice(0, limit);
}
-/** The tiles at zoom z in a normalized box, row by row, and their range. */
+/** The tiles at zoom z in a normalized box, row by row. */
function tileGrid(box, z) {
const x0 = lonToTileX(box.west, z);
const x1 = lonToTileX(box.east, z);
diff --cc src/layers/streetLevel/uiState.js
index 0b0b8dfd0,9d1afecc2..efb0dd750
--- a/src/layers/streetLevel/uiState.js
+++ b/src/layers/streetLevel/uiState.js
@@@ -1,3 -1,6 +1,5 @@@
-import { COLORS } from './policy.js';
-
+ import { msg, t } from '../../i18n/index.js';
++
/**
* @typedef {object} ProviderSnapshot
* @property {string} id
@@@ -13,6 -16,11 +15,10 @@@
* @property {string} hint
* @property {string|null} error
* @property {string} color The source's one colour.
+ * @property {boolean} [groundClick]
+ * @property {Array<'pano'|'since'>} [filters]
+ * @property {{noun: string, action: string}|null} [coverageLabel]
- * @property {boolean} [highlightsSequence] Its lines turn cyan when their sequence is selected.
+ * @property {'capture'|'upload'} [sinceBasis] What its SINCE compares.
*/
/**
@@@ -39,9 -49,49 +47,48 @@@ export function summarizeCoverage(provi
};
}
+ /**
+ * Switched-off providers that would draw with a key already set, offered
+ * while the switched-on ones lack theirs.
+ * @param {Array<ProviderSnapshot>} providers
+ * @returns {Array<{id: string, label: string, requiresKeyId: string|null}>}
+ */
+ export function keyAlternatives(providers) {
+ if (!summarizeCoverage(providers).keyRequired) return [];
+ return providers
+ .filter((p) => !p.on && p.configured === true && p.keyRequired !== true)
+ .map(({ id, label, requiresKeyId }) => ({ id, label, requiresKeyId }));
+ }
+
+ /**
+ * The filter controls a switched-on provider honours (both when none is on).
+ * @param {Array<ProviderSnapshot>} providers
+ */
+ export function filterControls(providers) {
+ const active = providers.filter((p) => p.on);
+ const honoured = (key) =>
+ active.length === 0 ||
+ active.some((p) => (p.filters ?? ['pano', 'since']).includes(key));
+ return { pano: honoured('pano'), since: honoured('since') };
+ }
+
+ /**
+ * The note under SINCE when a lit provider dates its imagery by upload,
+ * e.g. "KartaView: by upload date", or null.
+ * @param {Array<ProviderSnapshot>} providers
+ */
+ export function sinceNote(providers) {
+ const names = providers
+ .filter((p) => p.on && p.sinceBasis === 'upload')
+ .map((p) => p.name);
+ return names.length
+ ? t('{names}: by upload date', { names: names.join(', ') })
+ : null;
+ }
+
/**
- * The panel snapshot from core state and provider snapshots. The legend has
- * one swatch per active source that draws coverage lines, then Selected.
- * @param {{enabled: boolean, filter: object, providers: Array<ProviderSnapshot>, street: object, sequence: object}} input
+ * The panel snapshot from core state and provider snapshots.
- * @param {{enabled: boolean, filter: object, providers: Array<ProviderSnapshot>, street: object, sequence: object}} input
++ * @param {{enabled: boolean, groundClickReady?: boolean, filter: object, providers: Array<ProviderSnapshot>, street: object, sequence: object}} input
*/
export function composeUIState({
enabled,
@@@ -49,17 -100,44 +97,21 @@@
providers,
street,
sequence,
- surface = 'draped',
}) {
- const active = providers.filter((p) => p.on);
const { keyRequired, keyRejected, ...coverage } =
summarizeCoverage(providers);
- const legend = active
- .filter((provider) => provider.groundClick !== true)
- .map((provider) => ({
- key: provider.id,
- label: provider.name,
- color: provider.color,
- }));
- // "Selected" only beside a source whose lines turn cyan when selected.
- if (
- active.some(
- (provider) =>
- provider.groundClick !== true && provider.highlightsSequence !== false,
- )
- )
- legend.push({
- key: 'selected',
- label: t('Selected'),
- color: COLORS.selected,
- });
return {
enabled,
+ groundClickReady: groundClickReady === true,
keyRequired,
+ keyAlternatives: keyAlternatives(providers),
keyRejected,
filter: { ...filter },
+ filterControls: filterControls(providers),
+ sinceNote: sinceNote(providers),
providers: providers.map((p) => ({ ...p })),
coverage,
- legend,
sequence: { ...sequence },
street: { ...street },
- surface,
};
}
diff --cc src/layers/streetLevel/uiState.test.mjs
index 0d54178a1,21b5eefe0..5b9b0bf41
--- a/src/layers/streetLevel/uiState.test.mjs
+++ b/src/layers/streetLevel/uiState.test.mjs
@@@ -46,6 -47,99 +46,39 @@@ test('the layer is key-gated only when
assert.equal(offOnly.keyRequired, false, 'nothing switched on to gate');
});
-test('the legend is one swatch per active source, in its colour, then Selected', () => {
- const single = composeUIState({ ...base, providers: [provider()] });
- assert.deepEqual(single.legend, [
- { key: 'mapillary', label: 'Mapillary', color: '#05cb63' },
- { key: 'selected', label: 'Selected', color: COLORS.selected },
- ]);
- const two = composeUIState({
- ...base,
- providers: [
- provider(),
- provider({ id: 'panoramax', name: 'Panoramax', color: '#a66bff' }),
- ],
- });
- assert.deepEqual(
- two.legend.map((entry) => [entry.label, entry.color]),
- [
- ['Mapillary', '#05cb63'],
- ['Panoramax', '#a66bff'],
- ['Selected', COLORS.selected],
- ],
- );
- const oneOff = composeUIState({
- ...base,
- providers: [
- provider(),
- provider({ id: 'panoramax', name: 'Panoramax', on: false }),
- ],
- });
- assert.deepEqual(
- oneOff.legend.map((entry) => entry.key),
- ['mapillary', 'selected'],
- );
- assert.deepEqual(
- composeUIState({ ...base, providers: [provider({ on: false })] }).legend,
- [],
- );
-});
-
-test('Street View draws no lines: no legend swatch, and no Selected on its own', () => {
- const streetView = provider({
- id: 'google',
- name: 'Google Street View',
- color: '#4285f4',
- count: 0,
- groundClick: true,
- filters: [],
- });
- assert.deepEqual(
- composeUIState({ ...base, providers: [streetView] }).legend,
- [],
- );
- assert.deepEqual(
- composeUIState({
- ...base,
- providers: [provider(), streetView],
- }).legend.map((entry) => entry.key),
- ['mapillary', 'selected'],
- );
-});
-
+ test('the filter controls show only for a lit provider that honours them', () => {
+ const streetView = provider({ id: 'google', groundClick: true, filters: [] });
+ const controls = (providers) =>
+ composeUIState({ ...base, providers }).filterControls;
+ assert.deepEqual(controls([streetView]), { pano: false, since: false });
+ assert.deepEqual(controls([provider(), streetView]), {
+ pano: true,
+ since: true,
+ });
+ assert.deepEqual(
+ controls([provider({ on: false }), streetView]),
+ { pano: false, since: false },
+ 'Mapillary switched off',
+ );
+ assert.deepEqual(
+ controls([provider({ on: false }), { ...streetView, on: false }]),
+ { pano: true, since: true },
+ 'nothing lit: both, ready for the first chip',
+ );
+ });
+
+ test('a lit provider that dates by upload puts a note under SINCE', () => {
+ const kartaView = provider({
+ id: 'kartaview',
+ name: 'KartaView',
+ sinceBasis: 'upload',
+ });
+ const note = (providers) => composeUIState({ ...base, providers }).sinceNote;
+ assert.equal(note([provider()]), null, 'Mapillary: capture date');
+ assert.equal(note([kartaView]), 'KartaView: by upload date');
+ assert.equal(note([{ ...kartaView, on: false }]), null, 'only while lit');
+ });
+
test('hint and error come from the first active provider that has one', () => {
const ui = composeUIState({
...base,
@@@ -98,3 -193,80 +132,63 @@@ test('a rejected key gates like a missi
false,
);
});
+
-test('the surface mode defaults to draped and passes through', () => {
- assert.equal(
- composeUIState({ ...base, providers: [provider()] }).surface,
- 'draped',
- );
- assert.equal(
- composeUIState({ ...base, providers: [provider()], surface: 'terrain' })
- .surface,
- 'terrain',
- );
-});
-
+ test('every switched-on provider’s hint is kept, once each', async () => {
+ const { summarizeCoverage } = await import('./uiState.js');
+ const { providerSnapshot } =
+ await import('../../testSupport/streetLevelFakes.mjs');
+ const summary = summarizeCoverage([
+ providerSnapshot({ hint: 'zoom in for sequences' }),
+ providerSnapshot({
+ id: 'google',
+ hint: 'click a street to open Street View',
+ }),
+ providerSnapshot({ id: 'off', on: false, hint: 'not shown' }),
+ providerSnapshot({ id: 'dup', hint: 'zoom in for sequences' }),
+ ]);
+ assert.equal(
+ summary.hint,
+ 'zoom in for sequences · click a street to open Street View',
+ );
+ });
+
+ test('a key-gated layer offers the switched-off sources that would draw with a key already set', async () => {
+ const { keyAlternatives } = await import('./uiState.js');
+ const mapillary = providerSnapshot({ keyRequired: true, configured: false });
+ const streetView = providerSnapshot({
+ id: 'google',
+ label: 'STREET VIEW',
+ on: false,
+ configured: true,
+ requiresKeyId: 'google-maps',
+ });
+ assert.deepEqual(keyAlternatives([mapillary, streetView]), [
+ { id: 'google', label: 'STREET VIEW', requiresKeyId: 'google-maps' },
+ ]);
+ // Nothing to offer: Mapillary has its key, or Street View has none either.
+ assert.deepEqual(keyAlternatives([providerSnapshot(), streetView]), []);
+ assert.deepEqual(
+ keyAlternatives([
+ mapillary,
+ { ...streetView, configured: false, keyRequired: true },
+ ]),
+ [],
+ );
+ });
+
-test('a source whose lines never show a selection lists no Selected swatch, and names its own lines', () => {
++test('a source names its own lines', () => {
+ const kartaView = provider({
+ id: 'kartaview',
+ name: 'KartaView',
+ color: '#635bff',
- highlightsSequence: false,
+ coverageLabel: {
+ noun: 'streets',
+ action: 'click a line for its nearest photo',
+ },
+ });
+ const ui = composeUIState({ ...base, providers: [kartaView] });
- assert.deepEqual(
- ui.legend.map((entry) => entry.key),
- ['kartaview'],
- );
+ assert.deepEqual(ui.coverage.label, {
+ noun: 'streets',
+ action: 'click a line for its nearest photo',
+ });
+ });
diff --cc src/layers/streetLevel/view.js
index 0fe86c344,09bc516ed..e14cb6493
--- a/src/layers/streetLevel/view.js
+++ b/src/layers/streetLevel/view.js
@@@ -76,13 -74,12 +76,20 @@@ function groundHit(camera, point, ellip
return Cesium.Cartographic.fromCartesian(cartesian, ellipsoid) || null;
}
++/** Camera height (m) above the ground under it. */
++export function cameraHeightAboveGround(viewer) {
++ const carto = viewer?.camera?.positionCartographic;
++ if (!carto) return null;
++ return carto.height - (groundUnderCamera(viewer) ?? 0);
++}
++
+/** Screen rays per side, less one, that `visibleBbox` casts. */
+const BBOX_GRID = 5;
+
/**
- * Visible [west, south, east, north] degrees, or null. Only screen rays that
- * hit count, so a horizon cannot inflate the box to the world.
- * `groundHeight` raises the ellipsoid to the ground (Google 3D hides the
- * globe), `maxRange` (m) drops near-horizon hits, and `nearRange` (m) always
- * includes the ground around the camera.
+ * Visible [west, south, east, north] degrees from the rays that hit the
+ * ground, or null when fewer than four do. `groundHeight` raises the ellipsoid
+ * to the ground (Denver is 1,600 m up); `maxRange` (m) drops far hits.
*/
export function visibleBbox(
viewer,
@@@ -256,3 -295,3 +263,22 @@@ export function createHorizonCull({ get
return { update, stop };
}
++
++/** The middle of the visible ground, else the point under the camera; null without a camera. */
++export function viewCentre(viewer) {
++ if (!viewer) return null;
++ const bbox = visibleBbox(viewer);
++ if (bbox) {
++ // Across the date line (west > east) the middle is on the far side of 0°.
++ const span = bbox[2] - bbox[0] + (bbox[0] > bbox[2] ? 360 : 0);
++ let lon = bbox[0] + span / 2;
++ if (lon > 180) lon -= 360;
++ return { lat: (bbox[1] + bbox[3]) / 2, lon };
++ }
++ const carto = viewer.camera?.positionCartographic;
++ if (!carto) return null;
++ return {
++ lat: Cesium.Math.toDegrees(carto.latitude),
++ lon: Cesium.Math.toDegrees(carto.longitude),
++ };
++}
diff --cc src/layers/streetLevel/viewerHost.js
index 86b3bf81d,ce7363a13..16c992afd
--- a/src/layers/streetLevel/viewerHost.js
+++ b/src/layers/streetLevel/viewerHost.js
@@@ -25,11 -33,25 +26,23 @@@ export function createViewerHost({ stat
altitude: Number.isFinite(pose.altitude) ? pose.altitude : null,
isPano: pose.isPano === true,
capturedAt: pose.capturedAt ?? null,
+ capturedAtPrecision:
+ pose.capturedAtPrecision === 'month' ? 'month' : 'day',
+ title: pose.title || null,
sequenceId: pose.sequenceId ?? null,
creator: pose.creator || null,
+ license: pose.license || null,
externalUrl: pose.externalUrl || null,
+ // FIT / FILL, unless this image has no frame to fit (a panorama).
+ renderModes:
+ typeof active.adapter.setRenderMode === 'function' &&
+ active.adapter.supportsRenderModes?.() !== false,
});
- parts.marker.set(state.street.position, state.street.bearing);
+ parts.marker.set(
+ state.street.position,
+ state.street.bearing,
- providerEntry(pose.providerId)?.def.marker,
++ state.providers.get(active.id)?.def.marker,
+ );
- parts.follow.followCamera();
// Select the sequence only once the image is on screen, so its lookup
// never competes with the image download.
if (!state.street.loading && state.street.sequenceId !== previousSequence)
@@@ -85,19 -119,23 +98,25 @@@
return promise;
}
-- /** Open an image: true once its first pose is in, false if it failed or was overtaken. */
- async function open(providerId, imageId) {
++ /**
++ * Open an image: true once its first pose is in, false if it failed or was
++ * overtaken. `frame: false` leaves the camera where it is.
++ */
+ async function open(providerId, imageId, { frame = true } = {}) {
- const entry = providerEntry(providerId);
+ const entry = state.providers.get(providerId);
if (!entry || !imageId) return false;
if (!state.street.host) {
- state.street.error = 'Open the Street Level panel to view imagery';
+ // A nearest-image lookup may have set it; nothing is loading now.
+ state.street.loading = false;
+ // English data: the Street Level panel translates it (translateKnown).
+ state.street.error = msg('Open the Street Level panel to view imagery');
notify();
return false;
}
const seq = ++openSeq;
const current = () => seq === openSeq;
// Claimed now, honoured after loading only if nothing newer took the camera.
- const ticket = parts.framing.begin();
- const ticket =
- frame && !state.street.follow ? parts.follow.beginFraming() : null;
++ const ticket = frame ? parts.framing.begin() : null;
Object.assign(state.street, {
loading: true,
error: null,
@@@ -110,12 -148,14 +129,14 @@@
try {
const adapter = await mount(entry);
if (!current()) return false;
+ // Per open: close() resets it, and a reopen skips mount().
+ state.street.renderModes = typeof adapter.setRenderMode === 'function';
await adapter.open(String(imageId));
if (!current()) return false;
- if (ticket && !state.street.follow) parts.follow.lookAtPosition(ticket);
+ if (ticket) parts.framing.frame(ticket);
} catch (error) {
if (current())
- state.street.error = error?.message || 'Image could not be opened';
+ state.street.error = error?.message || msg('Image could not be opened');
} finally {
if (current()) state.street.loading = false;
notify();
diff --cc src/layers/streetLevel/viewerHost.test.mjs
index 0d448c4f4,259934b73..76bcb3e35
--- a/src/layers/streetLevel/viewerHost.test.mjs
+++ b/src/layers/streetLevel/viewerHost.test.mjs
@@@ -472,4 -570,118 +473,82 @@@ test('a photo asks for the camera when
openGate.resolve();
assert.equal(await opening, true);
assert.equal(framing.started, 1);
-
- // FOLLOW owns the camera already: an open neither claims nor frames.
- state.street.follow = true;
- assert.equal(await host.open('mapillary', 'b'), true);
- assert.deepEqual([framing.begun, framing.started], [1, 1]);
});
+
+ /** The harness with a second provider, `google`, whose adapter has no render modes. */
+ function twoProviders() {
+ const mapillary = fakeAdapter();
+ mapillary.prewarm = async () => {};
+ mapillary.setRenderMode = () => {};
+ const google = fakeAdapter();
+ google.prewarm = async () => {};
+ const h = harness(mapillary);
+ h.state.providers.set('google', {
+ def: { id: 'google', name: 'Google Street View', label: 'STREET VIEW' },
+ instance: { viewer: google },
+ on: true,
+ });
+ h.state.providers.get('mapillary').on = true;
+ return { ...h, mapillary, google };
+ }
+
-test("opening one provider's image releases another's prewarmed viewer in the shared host", async () => {
- const { state, host, mapillary, google } = twoProviders();
- await host.prewarm([state.providers.get('mapillary')]);
- assert.equal(mapillary.calls.unmount, 0, 'warm');
- await host.open('google', 'g-1');
- assert.equal(mapillary.calls.unmount, 1, 'not left under the panorama');
- assert.equal(google.calls.unmount, 0);
- // While Google shows, Mapillary is not built again under it.
- let built = 0;
- mapillary.prewarm = async () => built++;
- await host.prewarm([...state.providers.values()]);
- assert.equal(built, 0);
-});
-
+ test('the render modes follow the viewer that is open', async () => {
+ const { state, host } = twoProviders();
+ await host.open('mapillary', 'm-1');
+ assert.equal(state.street.renderModes, true);
+ await host.open('google', 'g-1');
+ assert.equal(state.street.renderModes, false, 'Google always fills');
+ });
+
+ test('a pose can date its image by month and name its place', async () => {
+ const { state, host, google } = twoProviders();
+ await host.open('google', 'g-1');
+ google.emitPose('g-1', {
+ providerId: 'google',
+ capturedAtPrecision: 'month',
+ title: '1014 10th St',
+ capturedAt: Date.UTC(2023, 0, 1),
+ });
+ assert.equal(state.street.capturedAtPrecision, 'month');
+ assert.equal(state.street.title, '1014 10th St');
+ host.close();
+ assert.deepEqual(
+ [state.street.capturedAtPrecision, state.street.title],
+ ['day', null],
+ );
+ });
+
-test('a prewarm that lands after another provider took the host is released, not built under it', async () => {
- const { state, host, mapillary } = twoProviders();
- let release;
- mapillary.prewarm = () =>
- new Promise((resolve) => {
- release = resolve;
- });
- const warming = host.prewarm([state.providers.get('mapillary')]);
- await host.open('google', 'g-1'); // the user opens Street View meanwhile
- release();
- await warming;
- assert.equal(mapillary.calls.unmount, 1, 'released at once');
- // Not kept warm: the next Mapillary open mounts afresh.
- await host.open('mapillary', 'm-1');
- assert.equal(state.street.providerId, 'mapillary');
-});
-
+ test('FIT/FILL stays hidden for a second Street View panorama after a close', async () => {
+ const { state, host } = twoProviders();
+ await host.open('google', 'g-1');
+ assert.equal(state.street.renderModes, false);
+ host.close();
+ await host.open('google', 'g-2');
+ assert.equal(state.street.renderModes, false);
+ });
+
+ test('an adapter that can frame but says this image has no frame offers no FIT / FILL', async () => {
+ const adapter = fakeAdapter();
+ let frameable = false;
+ adapter.setRenderMode = () => {};
+ adapter.supportsRenderModes = () => frameable;
+ const { state, host } = harness(adapter);
+ await host.open('mapillary', 'pano-1');
+ assert.equal(state.street.imageId, 'pano-1', 'the pose arrived');
+ assert.equal(state.street.renderModes, false);
+ frameable = true;
+ await host.open('mapillary', 'flat-1');
+ assert.equal(state.street.renderModes, true, 'a flat image can be framed');
+ });
+
+ test('a pose’s licence reaches the caption state, and a closed viewer forgets it', async () => {
+ const { state, host, google } = twoProviders();
+ await host.open('google', 'g-1');
+ google.emitPose('g-1', { providerId: 'google', license: 'CC BY-SA 4.0' });
+ assert.equal(state.street.license, 'CC BY-SA 4.0');
+ google.emitPose('g-1', { providerId: 'google' });
+ assert.equal(state.street.license, null, 'none given: none shown');
+ google.emitPose('g-1', { providerId: 'google', license: 'CC0' });
+ host.close();
+ assert.equal(state.street.license, null);
+ });
diff --cc src/streetLevelMarkup.test.mjs
index 8daf0bea3,4617eb4d9..8d316c120
--- a/src/streetLevelMarkup.test.mjs
+++ b/src/streetLevelMarkup.test.mjs
@@@ -11,10 -11,12 +11,11 @@@ const read = (file) => fs.readFileSync(
const html = expandApplicationHtml(read('index.html'));
const css = readStylesheet(path.join(ROOT, 'style.css'));
++const panelCss = read('src/ui/styles/street-level.css');
const panelChrome = read('src/ui/panelChrome.js');
const layoutController = read('src/ui/panelLayoutController.js');
-const panelCss = read('src/ui/styles/street-level.css');
-const controls = read('src/ui/streetLevelControls.js');
-test('Street Level is an ordinary collapsible GEV panel that starts collapsed', () => {
+test('Street Level is a collapsible right-rail panel that starts collapsed', () => {
assert.match(
html,
/<div id="street-level-panel" class="panel-collapsible collapsed" data-panel-id="street-level-panel">/,
diff --cc src/testSupport/panoramaxFixtures.mjs
index 000000000,47e807604..611f85a06
mode 000000,100644..100644
--- a/src/testSupport/panoramaxFixtures.mjs
+++ b/src/testSupport/panoramaxFixtures.mjs
@@@ -1,0 -1,129 +1,138 @@@
+ // Panoramax stand-ins for tests and the hermetic QA gate: vector tiles in
+ // the meta-catalogue's shape, and STAC items.
+ import { PbfWriter } from 'pbf';
+ import {
+ layerWriter,
+ lineGeometry,
- lonLatToTileLocal,
+ zigzag,
+ } from '../layers/streetLevel/providers/mapillary/coverageFixture.mjs';
+
++/** Tile-local [x, y] (0..extent) of a lon/lat inside tile (x, y, z). */
++function lonLatToTileLocal([lon, lat], { x, y, z }, extent = 4096) {
++ const n = 2 ** z;
++ const rad = (lat * Math.PI) / 180;
++ const tx = ((lon + 180) / 360) * n;
++ const ty =
++ ((1 - Math.log(Math.tan(rad) + 1 / Math.cos(rad)) / Math.PI) / 2) * n;
++ return [Math.round((tx - x) * extent), Math.round((ty - y) * extent)];
++}
++
+ /**
+ * Encode a Panoramax `/api/map/{z}/{x}/{y}.mvt` tile from lon/lat features.
+ * @param {{x: number, y: number, z: number}} tile
+ * @param {{sequences?: Array<{id: string, date?: string, type?: string, parts: Array<Array<[number, number]>>}>, grid?: Array<{lon: number, lat: number, pano?: number, flat?: number}>, pictures?: Array<{id: string, lon: number, lat: number, sequenceId: string, heading?: number, ts?: string, type?: string}>, extent?: number}} [content]
+ */
+ export function encodePanoramaxTile(
+ tile,
+ { sequences = [], grid = [], pictures = [], extent = 4096 } = {},
+ ) {
+ const pbf = new PbfWriter();
+ if (sequences.length) {
+ const layer = layerWriter('sequences', extent);
+ for (const sequence of sequences)
+ layer.add(
+ 2,
+ lineGeometry(
+ sequence.parts.map((part) =>
+ part.map((point) => lonLatToTileLocal(point, tile, extent)),
+ ),
+ ),
+ {
+ id: sequence.id,
+ type: sequence.type ?? 'flat',
+ date: sequence.date ?? '2025-06-01',
+ model: 'Test camera',
+ },
+ );
+ pbf.writeMessage(3, (_, out) => layer.write(out), null);
+ }
+ const point = (lon, lat) => {
+ const [px, py] = lonLatToTileLocal([lon, lat], tile, extent);
+ return [9, zigzag(px), zigzag(py)];
+ };
+ if (grid.length) {
+ const layer = layerWriter('grid', extent);
+ for (const cell of grid) {
+ const pano = cell.pano ?? 0;
+ const flat = cell.flat ?? 1;
+ layer.add(1, point(cell.lon, cell.lat), {
+ nb_pictures: pano + flat,
+ nb_360_pictures: pano,
+ nb_flat_pictures: flat,
+ });
+ }
+ pbf.writeMessage(3, (_, out) => layer.write(out), null);
+ }
+ if (pictures.length) {
+ const layer = layerWriter('pictures', extent);
+ for (const picture of pictures)
+ layer.add(1, point(picture.lon, picture.lat), {
+ id: picture.id,
+ ts: picture.ts ?? '2025-06-01 10:00:00+00',
+ heading: picture.heading ?? 90,
+ sequences: JSON.stringify([picture.sequenceId]),
+ first_sequence: picture.sequenceId,
+ type: picture.type ?? 'flat',
+ });
+ pbf.writeMessage(3, (_, out) => layer.write(out), null);
+ }
+ return new Uint8Array(pbf.finish());
+ }
+
+ /**
+ * A STAC item as the meta-catalogue returns it.
+ * @param {{id: string, lon: number, lat: number, sequenceId?: string, heading?: number, pano?: boolean, datetime?: string, producer?: string, license?: string, width?: number, prevId?: string|null, nextId?: string|null, host?: string}} options
+ */
+ export function stacItem({
+ id,
+ lon,
+ lat,
+ sequenceId = 'seq-1',
+ heading = 90,
+ pano = false,
+ datetime = '2025-06-01T10:00:00+00:00',
+ producer = 'tester',
+ license = 'CC-BY-SA-4.0',
+ width = pano ? 5760 : 4032,
+ prevId = null,
+ nextId = null,
+ host = 'https://panoramax.example.org',
+ }) {
+ const api = 'https://api.panoramax.xyz/api';
+ const links = [
+ { rel: 'self', href: `${api}/collections/${sequenceId}/items/${id}` },
+ ];
+ if (prevId)
+ links.push({
+ rel: 'prev',
+ href: `${api}/collections/${sequenceId}/items/${prevId}`,
+ });
+ if (nextId)
+ links.push({
+ rel: 'next',
+ href: `${api}/collections/${sequenceId}/items/${nextId}`,
+ });
+ return {
+ type: 'Feature',
+ id,
+ collection: sequenceId,
+ geometry: { type: 'Point', coordinates: [lon, lat] },
+ providers: [{ name: producer, roles: ['producer'] }],
+ properties: {
+ datetime,
+ license,
+ 'view:azimuth': heading,
+ 'geovisio:producer': producer,
+ 'pers:interior_orientation': {
+ ...(pano ? { field_of_view: 360 } : {}),
+ sensor_array_dimensions: [width, pano ? width / 2 : 3024],
+ },
+ },
+ assets: {
+ hd: { href: `${host}/pictures/${id}/hd.jpg` },
+ sd: { href: `${host}/pictures/${id}/sd.jpg` },
+ thumb: { href: `${host}/pictures/${id}/thumb.jpg` },
+ },
+ links,
+ };
+ }
diff --cc src/testSupport/streetLevelFakes.mjs
index d8ae0990f,73702c1f1..ed45f3dc4
--- a/src/testSupport/streetLevelFakes.mjs
+++ b/src/testSupport/streetLevelFakes.mjs
@@@ -1,6 -1,11 +1,11 @@@
-/** Shared Street Level test stand-ins: provider snapshot, minimal provider, ray-casting camera. */
+/** Shared Street Level test stand-ins: provider snapshot and provider, Mapillary source, photo viewer, Cesium viewer, ray-casting camera. */
import * as Cesium from 'cesium';
- import { MAPILLARY_CREDIT_HTML } from '../layers/streetLevel/policy.js';
+ import { MAPILLARY_CREDIT_HTML } from '../layers/streetLevel/providers/mapillary/policy.js';
+ import {
+ latToTileY,
+ lonToTileX,
+ tileBounds,
+ } from '../layers/streetLevel/tileMath.js';
const RAD = Math.PI / 180;
@@@ -259,5 -143,95 +266,94 @@@ export function rayCamera(
const hit = Cesium.IntersectionTests.rayEllipsoid(ray, ellipsoid);
return hit ? Cesium.Ray.getPoint(ray, hit.start) : undefined;
},
- computeViewRectangle: () => undefined,
};
}
+
+ /** The centre of the tile holding a point at zoom `z`, so a small view is one tile. */
+ export function tileCentre(lon, lat, z = 14) {
+ const x = lonToTileX(lon, z);
+ const y = latToTileY(lat, z);
+ const { west, east, south, north } = tileBounds(x, y, z);
+ return {
+ tile: { x, y, z },
+ lon: (west + east) / 2,
+ lat: (south + north) / 2,
+ };
+ }
+
+ /** A scene collection that remembers what is on the globe. */
+ function sceneCollection() {
+ const items = new Set();
+ return {
+ items,
+ add(primitive) {
+ items.add(primitive);
+ return primitive;
+ },
+ remove(primitive) {
+ return items.delete(primitive);
+ },
+ };
+ }
+
+ /**
+ * A viewer looking straight down on a 0.004° square around `view`
+ * (`{lon, lat, height}`, mutable), enough for line coverage to attach,
+ * refresh and draw. Cesium's one-time terrain-height download is skipped.
+ */
+ export function coverageViewer(view, t) {
+ const initialize = Cesium.GroundPolylinePrimitive.initializeTerrainHeights;
+ Cesium.GroundPolylinePrimitive.initializeTerrainHeights = () =>
+ Promise.resolve();
+ t?.after(() => {
+ Cesium.GroundPolylinePrimitive.initializeTerrainHeights = initialize;
+ });
+ // Node has no WebGL context to report line-width limits.
+ Cesium.ContextLimits._minimumAliasedLineWidth = 1;
+ Cesium.ContextLimits._maximumAliasedLineWidth = 10;
+ const listeners = () => {
+ const set = new Set();
+ return {
+ set,
+ addEventListener(listener) {
+ set.add(listener);
+ return () => set.delete(listener);
+ },
+ };
+ };
+ return {
+ view,
+ scene: {
+ canvas: { clientWidth: 100, clientHeight: 100 },
+ globe: { show: false, ellipsoid: Cesium.Ellipsoid.WGS84 },
+ frameState: { mode: Cesium.SceneMode.SCENE3D },
+ updateHeight: () => () => {},
+ getHeight: () => undefined,
+ groundPrimitives: sceneCollection(),
+ primitives: sceneCollection(),
+ postRender: listeners(),
+ preRender: listeners(),
+ },
+ camera: {
+ changed: new Cesium.Event(),
+ moveEnd: new Cesium.Event(),
+ get positionWC() {
+ return Cesium.Cartesian3.fromDegrees(view.lon, view.lat, view.height);
+ },
+ get positionCartographic() {
+ return {
+ longitude: view.lon * RAD,
+ latitude: view.lat * RAD,
+ height: view.height,
+ };
+ },
+ pickEllipsoid(point) {
+ return Cesium.Cartesian3.fromDegrees(
+ view.lon - 0.002 + (point.x / 100) * 0.004,
+ view.lat + 0.002 - (point.y / 100) * 0.004,
+ );
+ },
+ computeViewRectangle: () => undefined,
+ },
+ };
+ }
diff --cc src/tooling/streetLevelQa.test.mjs
index c0f37384e,cd5ff501c..120d7d1b6
--- a/src/tooling/streetLevelQa.test.mjs
+++ b/src/tooling/streetLevelQa.test.mjs
@@@ -1,5 -1,16 +1,6 @@@
import assert from 'node:assert/strict';
-import fs from 'node:fs';
import test from 'node:test';
+ import { inflateSync } from 'node:zlib';
-import { createApplicationStreetLevel } from '../app/layers/streetLevel.js';
-import {
- fixtureTile,
- EXPECTED_PROVIDERS,
- isCollapsed,
- PARK,
- STRICT_ALLOWED_SKIPS,
- strictViolations,
-} from '../../scripts/qa-street-level.mjs';
import {
answerMapillaryRequest,
describeCall,
@@@ -8,7 -21,369 +9,25 @@@
THUMB_HOST,
} from '../../scripts/fixtures/street-level/mapillaryGraph.mjs';
import { redact } from '../../scripts/qa-browserEvidence.mjs';
+ import {
+ answerKartaViewRequest,
+ describeKartaViewCall,
+ KV_LINE,
+ KV_OLD_STREET,
+ KV_SEQUENCE_ID,
+ kartaViewPhotos,
+ resetKartaViewFixture,
+ } from '../../scripts/fixtures/street-level/kartaView.mjs';
+ import {
+ maskedSegments,
+ tileSegments,
+ } from '../layers/streetLevel/providers/kartaview/decode.js';
+ import { lonToTileX, latToTileY } from '../layers/streetLevel/tileMath.js';
+ import {
+ normalizePhoto,
+ resizedImageUrl,
+ } from '../layers/streetLevel/providers/kartaview/policy.js';
-// The press helpers wait for paint; Node has no frames, so a tick stands in.
-globalThis.requestAnimationFrame ??= (callback) =>
- setTimeout(() => callback(Date.now()), 0);
-
-test('the harness expects exactly the providers the app registers, in chip order', () => {
- // Any method a provider asks its source for is a no-op: only ids matter.
- const source = new Proxy({}, { get: () => () => {} });
- const layer = createApplicationStreetLevel({
- surface: null,
- sources: { mapillary: source },
- });
- assert.deepEqual([...EXPECTED_PROVIDERS], [...layer.providerIds]);
-});
-
-test('a panel reads as collapsed only with the collapsed class', () => {
- assert.equal(isCollapsed(['panel-collapsible', 'collapsed']), true);
- assert.equal(isCollapsed(['panel-collapsible']), false);
-});
-
-test('the harness only runs its browser flow when executed directly', () => {
- const source = fs.readFileSync(
- new URL('../../scripts/qa-street-level.mjs', import.meta.url),
- 'utf8',
- );
- assert.match(
- source,
- /import\.meta\.url === pathToFileURL\(process\.argv\[1\]\)\.href/,
- );
- assert.match(source, /PUPPETEER_EXECUTABLE_PATH/);
- assert.match(source, /--url/);
-});
-
-test('fixture tiles give the hermetic gate something real to filter', async () => {
- const { decodeCoverageTile } =
- await import('../layers/streetLevel/providers/mapillary/decode.js');
- const now = Date.UTC(2026, 9, 1);
- const street = decodeCoverageTile(fixtureTile(14, 2662, 6286, now), {
- x: 2662,
- y: 6286,
- z: 14,
- });
- const grid = street.sequences.filter((s) => s.id !== PHOTO_SEQUENCE_ID);
- assert.equal(grid.length, 8);
- const pano = grid.filter((s) => s.isPano).length;
- assert.ok(pano > 0 && pano < 8, '360° and flat both present');
- const year = 365 * 86_400_000;
- const old = grid.filter((s) => now - s.capturedAt > year).length;
- assert.ok(old > 0 && old < 8, 'recent and older both present');
- const orbit = decodeCoverageTile(fixtureTile(3, 1, 3, now), {
- x: 1,
- y: 3,
- z: 3,
- });
- assert.ok(orbit.overview.length > 0, 'overview points from orbit');
- assert.equal(fixtureTile(8, 1, 1, now).length, 0, 'nothing in between');
-});
-
-/* ── The real status route probe ─────────────────────────────────────── */
-
-test('the gate requires the server’s real Mapillary status route', async () => {
- const { assertRealStatusRoute } =
- await import('../../scripts/qa-street-level.mjs');
- const asked = [];
- const answer = (body, init) => async (url) => {
- asked.push(url);
- return typeof body === 'string'
- ? new Response(body, init)
- : Response.json(body, init);
- };
- assert.deepEqual(
- await assertRealStatusRoute(
- 'http://localhost:4173',
- answer({ configured: false }),
- ),
- { configured: false },
- );
- assert.deepEqual(asked, ['http://localhost:4173/api/mapillary/status']);
- for (const [why, fetchImpl] of [
- [
- 'an unregistered route (the API 404)',
- answer({ error: 'Unknown API route' }, { status: 404 }),
- ],
- [
- 'the SPA fallback',
- answer('<!doctype html><title>GEV</title>', {
- headers: { 'content-type': 'text/html' },
- }),
- ],
- ['a malformed status', answer({ configured: 'yes' })],
- [
- 'an unreachable server',
- async () => {
- throw new TypeError('fetch failed');
- },
- ],
- ])
- await assert.rejects(
- assertRealStatusRoute('http://localhost:4173', fetchImpl),
- /api\/mapillary\/status/,
- why,
- );
-});
-
-/* ── Header press-and-verify shared with the panel gate ───────────────── */
-
-/**
- * A page stand-in that runs page functions in Node against a fake document.
- * The hit check always sees the header; `presses` says where each pointerdown
- * lands ('header', 'other', 'moved' or 'none').
- */
-function fakePanelPage({ presses = [], floating = false, stuck = false } = {}) {
- const state = { floating, downs: 0, last: null, dragging: false, shift: 0 };
- const listeners = [];
- const node = (tagName, id, classes, inHeader) => ({
- tagName,
- id,
- classList: classes,
- closest: (selector) =>
- inHeader && selector.includes('.panel-header') ? {} : null,
- });
- const header = node('DIV', '', ['panel-title'], true);
- const other = node('SECTION', 'weather-panel', ['panel'], false);
- const rect = (left, top, width, height) => () => ({
- left,
- top,
- width,
- height,
- });
- const document = {
- querySelector: () => ({ getBoundingClientRect: rect(120, 210, 100, 20) }),
- getElementById: () => ({
- getBoundingClientRect: () => rect(100, 200 + state.shift, 300, 400)(),
- classList: {
- contains: (name) => name === 'panel-floating' && state.floating,
- },
- }),
- elementFromPoint: () => header,
- };
- const window = {
- addEventListener: (type, listener) => listeners.push(listener),
- };
- const inPage = (fn, ...args) => {
- const saved = { document: globalThis.document, window: globalThis.window };
- Object.assign(globalThis, { document, window });
- try {
- return fn(...args);
- } finally {
- Object.assign(globalThis, saved);
- }
- };
- const evaluate = async (fn, ...args) => inPage(fn, ...args);
- const press = () => {
- state.last = presses[state.downs++] ?? 'header';
- // 'none': the pointerdown never reaches the page.
- if (state.last === 'none') return;
- const target = state.last === 'header' ? header : other;
- // 'moved': the panel's layout shifted just before the press landed.
- if (state.last === 'moved') state.shift = -116;
- for (const listener of listeners.splice(0)) inPage(listener, { target });
- state.shift = 0;
- };
- return {
- state,
- evaluate,
- async waitForFunction(fn, options, ...args) {
- for (let i = 0; i < 3; i++) {
- if (await evaluate(fn, ...args)) return;
- await new Promise((resolve) => setTimeout(resolve, 1));
- }
- throw Object.assign(new Error('timed out'), { name: 'TimeoutError' });
- },
- mouse: {
- async move() {},
- async down() {
- press();
- state.dragging = true;
- },
- async up() {
- if (state.dragging && state.last === 'header' && !stuck)
- state.floating = true;
- state.dragging = false;
- },
- async click(x, y, { clickCount }) {
- if (clickCount === 1) press();
- else if (state.last === 'header' && !stuck) state.floating = false;
- },
- },
- };
-}
-
-test('a header press is retried only when it provably missed the header', async () => {
- const { pressMissed } = await import('../../scripts/qa-panelDrag.mjs');
- assert.equal(pressMissed({ done: true, pressed: null }), false);
- assert.equal(
- pressMissed({ done: false, pressed: { inHeader: true } }),
- false,
- );
- assert.equal(
- pressMissed({ done: false, pressed: { inHeader: false } }),
- true,
- );
- // No recorded press is a failure, not a miss to retry.
- assert.equal(pressMissed({ done: false, pressed: null }), false);
-});
-
-test('a lift whose press the rail moved off the header is retried, then lifts', async () => {
- const { liftPanelByHeader, describePress } =
- await import('../../scripts/qa-panelDrag.mjs');
- const page = fakePanelPage({ presses: ['other', 'header'] });
- const notes = [];
- const attempt = await liftPanelByHeader(page, 'street-level-panel', {
- dx: -400,
- dy: 80,
- log: (line) => notes.push(line),
- pauseMs: 0,
- });
- assert.equal(attempt.done, true);
- assert.equal(page.state.downs, 2);
- assert.equal(notes.length, 2, 'a note and a GitHub warning');
- assert.match(notes[0], /missed the street-level-panel header/);
- assert.match(notes[0], /section#weather-panel\.panel/, 'names what it hit');
- assert.match(notes[0], /pre-press hit check passed/);
- assert.match(notes[0], /stillness (held|timed out)/);
- assert.match(
- notes[0],
- /panel box at hit check 100,200 300x400 -> at press 100,200 300x400/,
- );
- assert.match(notes[1], /^::warning title=Panel press retried::retry 1\/2/);
- assert.match(describePress(attempt), /in header: true, after 1 retry$/);
-});
-
-test('a press in the header that does not lift fails at once, naming the target', async () => {
- const { liftPanelByHeader, describePress } =
- await import('../../scripts/qa-panelDrag.mjs');
- const page = fakePanelPage({ stuck: true });
- const attempt = await liftPanelByHeader(page, 'street-level-panel', {
- dx: -400,
- dy: 80,
- log: () => assert.fail('no retry'),
- pauseMs: 0,
- });
- assert.equal(attempt.done, false);
- assert.equal(page.state.downs, 1);
- assert.match(describePress(attempt), /on div\.panel-title, in header: true/);
-});
-
-test('presses that keep missing stop after the retries and report the miss', async () => {
- const { liftPanelByHeader, PRESS_RETRIES } =
- await import('../../scripts/qa-panelDrag.mjs');
- const page = fakePanelPage({ presses: ['other', 'other', 'other', 'other'] });
- const attempt = await liftPanelByHeader(page, 'street-level-panel', {
- dx: -400,
- dy: 80,
- log: () => {},
- pauseMs: 0,
- });
- assert.equal(attempt.done, false);
- assert.equal(page.state.downs, PRESS_RETRIES + 1);
- assert.equal(attempt.pressed.inHeader, false);
-});
-
-test('a header double-click docks, waiting on the docked state', async () => {
- const { dockPanelByDoubleClick } =
- await import('../../scripts/qa-panelDrag.mjs');
- const page = fakePanelPage({ floating: true, presses: ['other', 'header'] });
- const attempt = await dockPanelByDoubleClick(page, 'street-level-panel', {
- log: () => {},
- pauseMs: 0,
- });
- assert.equal(attempt.done, true);
- assert.equal(page.state.floating, false);
- assert.equal(page.state.downs, 2, 'the missed first press was retried');
-});
-
-test('both panel gates press the header through the shared helper', () => {
- for (const script of ['qa-street-level.mjs', 'qa-panel-resize.mjs']) {
- const source = fs.readFileSync(
- new URL(`../../scripts/${script}`, import.meta.url),
- 'utf8',
- );
- assert.match(source, /from '\.\/qa-panelDrag\.mjs'/, script);
- assert.match(source, /liftPanelByHeader\(page, PANEL_ID/, script);
- assert.match(source, /dockPanelByDoubleClick\(page, PANEL_ID/, script);
- }
-});
-
-/* ── Hermetic photo flow: the photo line and the Graph fixtures ────────── */
-
-test('the photo sequence runs through the parked view, clipped to each tile it crosses', async () => {
- const { decodeCoverageTile } =
- await import('../layers/streetLevel/providers/mapillary/decode.js');
- const { lonToTileX, latToTileY } =
- await import('../layers/streetLevel/tileMath.js');
- const x = lonToTileX(PHOTO_LINE.lon, 14);
- const rows = new Set(
- [PHOTO_LINE.south, PHOTO_LINE.north].map((lat) => latToTileY(lat, 14)),
- );
- assert.ok(rows.size > 1, 'the line crosses a tile edge');
- let south = Infinity;
- let north = -Infinity;
- for (const y of rows) {
- const line = decodeCoverageTile(fixtureTile(14, x, y), {
- x,
- y,
- z: 14,
- }).sequences.find((s) => s.id === PHOTO_SEQUENCE_ID);
- assert.ok(line, `tile 14/${x}/${y} carries the photo line`);
- for (const [lon, lat] of line.parts[0]) {
- assert.ok(Math.abs(lon - PHOTO_LINE.lon) < 1e-4);
- south = Math.min(south, lat);
- north = Math.max(north, lat);
- }
- }
- assert.ok(Math.abs(south - PHOTO_LINE.south) < 1e-4);
- assert.ok(Math.abs(north - PHOTO_LINE.north) < 1e-4);
- // Far away there is no photo line, only the grid.
- const elsewhere = decodeCoverageTile(fixtureTile(14, 100, 100), {
- x: 100,
- y: 100,
- z: 14,
- });
- assert.equal(
- elsewhere.sequences.some((s) => s.id === PHOTO_SEQUENCE_ID),
- false,
- );
- // The parked camera looks down onto the line.
- assert.equal(PARK.lon, PHOTO_LINE.lon);
- assert.ok(PARK.lat > PHOTO_LINE.south && PARK.lat < PHOTO_LINE.north);
-});
-
-test('the fixture photos: one sequence, 360° and flat, close enough for any nearest lookup on the line', () => {
- const images = photoImages(Date.UTC(2026, 9, 1));
- assert.ok(images.length >= 3);
- assert.ok(images.some((image) => image.isPano));
- assert.ok(images.some((image) => !image.isPano));
- for (let i = 1; i < images.length; i++) {
- const gap = metresApart(images[i - 1], images[i]);
- // Above the cones' 3 m thinning, and at most 50 m apart: any point on
- // the line has a photo within the Graph API's 50 m radius.
- assert.ok(gap > 3 && gap < 50, `gap ${gap}`);
- }
- assert.equal(new Set(images.map((image) => image.id)).size, images.length);
-});
-
const graph = (path, params) =>
`https://graph.mapillary.com/${path}?${new URLSearchParams({ access_token: 'MLY|0|qa-fixture', ...params })}`;
const answer = (url, method = 'GET') => {
@@@ -112,3 -530,407 +131,279 @@@ test('evidence never carries a Mapillar
'loaded with AIza…REDACTED inline',
);
});
+
-test('--strict accepts only the documented skips', () => {
- assert.deepEqual(
- [...STRICT_ALLOWED_SKIPS],
- ['no Google 3D', 'no Google key', 'fixtures only'],
- );
- assert.deepEqual(
- strictViolations([
- { reason: 'no Google 3D', label: 'terrain' },
- { reason: 'no Google key', label: 'street view' },
- { reason: 'fixtures only', label: 'keyless page' },
- { reason: 'no Mapillary key', label: 'the keyed steps' },
- { reason: 'Google key refused', label: 'street view' },
- ]),
- [
- { reason: 'no Mapillary key', label: 'the keyed steps' },
- { reason: 'Google key refused', label: 'street view' },
- ],
- );
-});
-
-test('a press that records no pointerdown fails at once, without a retry', async () => {
- const { liftPanelByHeader, describePress } =
- await import('../../scripts/qa-panelDrag.mjs');
- const page = fakePanelPage({ presses: ['none', 'header'] });
- const attempt = await liftPanelByHeader(page, 'street-level-panel', {
- dx: -400,
- dy: 80,
- log: () => assert.fail('no retry'),
- pauseMs: 0,
- });
- assert.equal(attempt.done, false);
- assert.equal(attempt.pressed, null);
- assert.equal(page.state.downs, 1);
- assert.match(describePress(attempt), /no pointerdown reached the page/);
-});
-
-test('QA_FAIL_ON_RETRY turns a retry into a failure that says why', async () => {
- const { liftPanelByHeader, failOnRetryDefault } =
- await import('../../scripts/qa-panelDrag.mjs');
- assert.equal(failOnRetryDefault({ QA_FAIL_ON_RETRY: '1' }, []), true);
- assert.equal(failOnRetryDefault({}, ['--fail-on-retry']), true);
- assert.equal(failOnRetryDefault({}, []), false);
- const page = fakePanelPage({ presses: ['other', 'header'] });
- await assert.rejects(
- liftPanelByHeader(page, 'street-level-panel', {
- dx: -400,
- dy: 80,
- log: () => {},
- pauseMs: 0,
- failOnRetry: true,
- }),
- /QA_FAIL_ON_RETRY=1 .*missed the street-level-panel header.*pre-press hit check passed/,
- );
- assert.equal(page.state.downs, 1);
-});
-
-test('QA_FAIL_ON_RETRY retries, with a warning, a miss the panel moving explains', async () => {
- const { liftPanelByHeader, panelMoved } =
- await import('../../scripts/qa-panelDrag.mjs');
- assert.equal(panelMoved({ left: 0, top: 382 }, { left: 0, top: 266 }), true);
- assert.equal(panelMoved({ left: 0, top: 382 }, { left: 1, top: 383 }), false);
- const page = fakePanelPage({ presses: ['moved', 'header'] });
- const lines = [];
- const attempt = await liftPanelByHeader(page, 'street-level-panel', {
- dx: -400,
- dy: 80,
- log: (line) => lines.push(line),
- pauseMs: 0,
- failOnRetry: true,
- });
- assert.equal(attempt.done, true, 'the second press lifted it');
- assert.equal(page.state.downs, 2);
- assert.ok(
- lines.some((line) =>
- /::warning title=Panel press retried::.*-> at press 100,84/.test(line),
- ),
- lines.join('\n'),
- );
-});
-
-test('both gates save failure evidence and fail on render-loop errors', () => {
- for (const script of ['qa-street-level.mjs', 'qa-panel-resize.mjs']) {
- const source = fs.readFileSync(
- new URL(`../../scripts/${script}`, import.meta.url),
- 'utf8',
- );
- assert.match(source, /saveFailureArtifacts\(/, script);
- assert.match(source, /hookRenderErrors\(/, script);
- assert.match(source, /readRenderErrors\(/, script);
- assert.match(source, /--fail-on-retry/, script);
- }
-});
-
-test('CI runs the gates hermetically against a production build, strict, with evidence', () => {
- const ci = fs.readFileSync(
- new URL('../../.github/workflows/ci.yml', import.meta.url),
- 'utf8',
- );
- const job = ci.slice(ci.indexOf('street-level-browser:'));
- const gate = job.slice(0, job.indexOf('\n windows-onboarding:'));
- // The dummy token is baked into the bundle at build time and the preview
- // server's status route reads it at run time: both steps carry it.
- assert.match(
- gate,
- /MAPILLARY_CLIENT_TOKEN: 'MLY\|0\|qa-fixture'\s+run: npm run build/,
- );
- assert.match(
- gate,
- /MAPILLARY_CLIENT_TOKEN: 'MLY\|0\|qa-fixture'\s+run: \|\s+npx vite preview --port 4173 --strictPort/,
- );
- assert.doesNotMatch(gate, /npx vite --port/);
- assert.equal(
- (gate.match(/MAPILLARY_CLIENT_TOKEN: 'MLY\|0\|qa-fixture'/g) || []).length,
- 2,
- );
- assert.match(gate, /qa:street-level:fixtures -- --strict/);
- assert.match(
- gate,
- /if: failure\(\)[\s\S]*actions\/upload-artifact@[0-9a-f]{40}/,
- );
- assert.match(gate, /path: qa-artifacts\//);
- assert.match(
- gate,
- /QA_FAIL_ON_RETRY: '1'/,
- 'a missed header press fails CI now that the rail settles',
- );
-});
-
+ test('KartaView fixtures draw the drive, answer nearest first, and refuse the storage host the API names', () => {
+ const body = (answer) => JSON.parse(answer.body);
+ const lat = (KV_LINE.south + KV_LINE.north) / 2;
+ const x = lonToTileX(KV_LINE.lon, 14);
+ const y = latToTileY(lat, 14);
+ const tile = answerKartaViewRequest({
+ method: 'GET',
+ url: `https://api.kartaview.org/2.0/sequence/tiles/${x}/${y}/14.json`,
+ });
+ assert.equal(tile.known, true);
+ assert.ok(body(tile).lines.length >= 1);
+ const empty = answerKartaViewRequest({
+ method: 'GET',
+ url: `https://api.kartaview.org/2.0/sequence/tiles/${x + 3}/${y}/14.json`,
+ });
+ assert.deepEqual(body(empty).lines, []);
+ const nearUrl = `https://api.kartaview.org/2.0/photo/?lat=${lat}&lng=${KV_LINE.lon + 0.0001}&zoomLevel=18&itemsPerPage=10`;
+ resetKartaViewFixture();
+ // The first lookup is rate-limited, readable cross-origin; the retry answers.
+ const limited = answerKartaViewRequest({ method: 'GET', url: nearUrl });
+ assert.equal(limited.status, 429);
+ assert.equal(limited.known, true);
+ assert.equal(limited.headers['Retry-After'], '0');
+ assert.match(limited.headers['Access-Control-Expose-Headers'], /Retry-After/);
+ const near = answerKartaViewRequest({ method: 'GET', url: nearUrl });
+ assert.equal(near.status, 200);
+ const records = body(near).result.data;
+ assert.ok(records.length > 1);
+ assert.ok(Number(records[0].distance) <= Number(records[1].distance));
+ const photo = normalizePhoto(records[0]);
+ assert.match(photo.urls.view, /^https:\/\/storage2\.openstreetcam\.org\//);
+ assert.equal(
+ answerKartaViewRequest({ method: 'GET', url: photo.urls.view }).known,
+ true,
+ );
+ // Every odd photo is archived: its file answers 409, an even one the image.
+ const photos = kartaViewPhotos();
+ const storageAnswer = (index) =>
+ answerKartaViewRequest({
+ method: 'GET',
+ url: normalizePhoto(
+ body(
+ answerKartaViewRequest({
+ method: 'GET',
+ url: `https://api.kartaview.org/2.0/photo/${photos[index].id}`,
+ }),
+ ).result.data,
+ ).urls.view,
+ });
+ assert.equal(photos[3].archived, true);
+ assert.equal(storageAnswer(3).status, 409);
+ assert.equal(storageAnswer(3).known, true);
+ assert.equal(photos[4].archived, false);
+ assert.equal(storageAnswer(4).status, 200);
+ assert.equal(storageAnswer(4).contentType, 'image/jpeg');
+ // The image proxy still serves an archived photo: the 360° step opens one.
+ const pano = photos.find((p) => p.isPano);
+ assert.equal(pano.archived, true);
+ const panoRecord = body(
+ answerKartaViewRequest({
+ method: 'GET',
+ url: `https://api.kartaview.org/2.0/photo/${pano.id}`,
+ }),
+ ).result.data;
+ assert.equal(
+ answerKartaViewRequest({
+ method: 'GET',
+ url: resizedImageUrl(normalizePhoto(panoRecord).urls.pano, [1024, 512]),
+ }).status,
+ 200,
+ );
+ assert.equal(
+ answerKartaViewRequest({ method: 'GET', url: records[0].fileurlLTh }).known,
+ false,
+ 'the storage1 address the API gives is not where the photo is',
+ );
+ const page = answerKartaViewRequest({
+ method: 'GET',
+ url: `https://api.kartaview.org/2.0/sequence/${KV_SEQUENCE_ID}/photos?page=1&itemsPerPage=1000`,
+ });
+ assert.equal(body(page).result.data.length, kartaViewPhotos().length);
+ assert.ok(kartaViewPhotos().some((p) => p.isPano));
+ assert.equal(
+ describeKartaViewCall(
+ 'GET',
+ new URL('https://api.kartaview.org/2.0/photo/77000001'),
+ ),
+ 'GET api.kartaview.org/2.0/photo/{id}',
+ );
+ });
+
+ test('Panoramax fixtures: two sequences on one street, searches honour sequence and filters, unknown calls are flagged', async () => {
+ const {
+ answerPanoramaxRequest,
+ describePanoramaxCall,
+ PNX_LINE,
+ PNX_SEQUENCES,
+ panoramaxHdDownloads,
+ panoramaxPictures,
+ panoramaxTile,
+ resetPanoramaxFixture,
+ } = await import('../../scripts/fixtures/street-level/panoramax.mjs');
+ const { decodeCoverageTile, decodePictures } =
+ await import('../layers/streetLevel/providers/panoramax/decode.js');
+ const { normalizeItem } =
+ await import('../layers/streetLevel/providers/panoramax/policy.js');
+ resetPanoramaxFixture();
+ const pictures = panoramaxPictures();
+ assert.deepEqual(
+ [...new Set(pictures.map((p) => p.sequenceId))],
+ [...PNX_SEQUENCES],
+ );
+ assert.ok(pictures.some((p) => p.isPano));
+ // Coverage: both lines in a z14 tile on the street; cones in z15.
+ const z = 14;
+ const x = lonToTileX((PNX_LINE.west + PNX_LINE.east) / 2, z);
+ const y = latToTileY(PNX_LINE.lat, z);
+ const lines = decodeCoverageTile(panoramaxTile(z, x, y), { x, y, z });
+ assert.deepEqual(
+ lines.sequences.map((s) => s.id).sort(),
+ [...PNX_SEQUENCES].sort(),
+ );
+ const t15 = {
+ x: lonToTileX(pictures[20].lon, 15),
+ y: latToTileY(PNX_LINE.lat, 15),
+ z: 15,
+ };
+ assert.ok(
+ decodePictures(panoramaxTile(15, t15.x, t15.y), t15, PNX_SEQUENCES[0])
+ .length > 0,
+ );
+ // A search for one sequence near the street gives only its pictures, nearest first.
+ const at = pictures[30];
+ const ask = (query) =>
+ JSON.parse(
+ answerPanoramaxRequest({
+ method: 'GET',
+ url: `https://api.panoramax.xyz/api/search?${query}`,
+ }).body,
+ ).features.map(normalizeItem);
+ const own = ask(
+ `place_position=${at.lon},${at.lat}&place_distance=0-50&limit=5&collections=${PNX_SEQUENCES[1]}`,
+ );
+ assert.ok(own.length > 0);
+ assert.ok(own.every((p) => p.sequenceId === PNX_SEQUENCES[1]));
+ assert.equal(own[0].nextId && typeof own[0].nextId, 'string');
+ const panos = ask(
+ `place_position=${at.lon},${at.lat}&place_distance=0-200&limit=50&filter=field_of_view%3D360`,
+ );
+ assert.ok(panos.length > 0 && panos.every((p) => p.isPano));
+ assert.deepEqual(
+ ask(
+ `place_position=${at.lon},${at.lat}&place_distance=0-200&limit=50&datetime=2024-01-01T00:00:00.000Z/..`,
+ ).every((p) => p.sequenceId === PNX_SEQUENCES[0]),
+ true,
+ 'the second sequence is older',
+ );
+ // A box has every picture in it, those looking away included; a place
+ // search leaves out pictures the point is behind (all look east).
+ const d = 0.0002;
+ const boxed = ask(
+ `bbox=${at.lon - d},${at.lat - d},${at.lon + d},${at.lat + d}&limit=100`,
+ );
+ assert.ok(
+ boxed.some((p) => p.lon < at.lon) && boxed.some((p) => p.lon > at.lon),
+ );
+ const placed = ask(
+ `place_position=${at.lon},${at.lat}&place_distance=0-30&limit=50`,
+ );
+ assert.ok(placed.length > 0);
+ assert.ok(
+ placed.every((p) => p.lon <= at.lon + 1e-7),
+ 'none it is behind',
+ );
+ const one = ask(`ids=${at.id}&limit=1`);
+ assert.equal(one[0].id, at.id);
+ // Its pictures, and only those, are served; HD downloads are counted.
+ const file = (name) =>
+ answerPanoramaxRequest({
+ method: 'GET',
+ url: `https://panoramax.openstreetmap.fr/derivates/${name}`,
+ });
+ assert.equal(file(`${at.id}/sd.jpg`).status, 200);
+ assert.equal(file(`${at.id}/hd.jpg`).status, 200);
+ assert.equal(panoramaxHdDownloads(), 1);
+ assert.equal(file('nope/sd.jpg').known, false);
+ const unknown = answerPanoramaxRequest({
+ method: 'GET',
+ url: 'https://api.panoramax.xyz/api/collections/x/items',
+ });
+ assert.equal(unknown.known, false);
+ assert.equal(
+ describePanoramaxCall(
+ 'GET',
+ new URL('https://api.panoramax.xyz/api/map/14/1/2.mvt'),
+ ),
+ 'GET api.panoramax.xyz/api/map/{z}/{x}/{y}.mvt',
+ );
+ });
+
+ /** The alpha of a fixture PNG (8-bit RGBA, unfiltered rows, as it writes them). */
+ function fixturePngAlpha(bytes) {
+ const width = bytes.readUInt32BE(16);
+ const height = bytes.readUInt32BE(20);
+ const idat = [];
+ for (let at = 8; at < bytes.length;) {
+ const length = bytes.readUInt32BE(at);
+ const type = bytes.toString('ascii', at + 4, at + 8);
+ if (type === 'IDAT') idat.push(bytes.subarray(at + 8, at + 8 + length));
+ at += 12 + length;
+ }
+ const rows = inflateSync(Buffer.concat(idat));
+ const alpha = new Uint8Array(width * height);
+ for (let y = 0; y < height; y++)
+ for (let x = 0; x < width; x++)
+ alpha[y * width + x] = rows[y * (width * 4 + 1) + 1 + x * 4 + 3];
+ return { width, height, alpha };
+ }
+
+ test('KartaView fixtures filter like KartaView: PNG tiles by view and upload date, the photo search by projection', () => {
+ const body = (answer) => JSON.parse(answer.body);
+ const z = 14;
+ const x = lonToTileX(KV_LINE.lon, z);
+ const y = latToTileY((KV_LINE.south + KV_LINE.north) / 2, z);
+ assert.equal(x, lonToTileX(KV_OLD_STREET.lon, z), 'both streets in a tile');
+ const base = `https://api.kartaview.org/2.0/sequence/tiles/${x}/${y}/${z}`;
+ const segments = tileSegments(
+ body(answerKartaViewRequest({ method: 'GET', url: `${base}.json` })),
+ );
+ const lons = (kept) => [...new Set(kept.map((segment) => segment[0][0]))];
+ const keptFor = (query) => {
+ const answer = answerKartaViewRequest({
+ method: 'GET',
+ url: `${base}.png?${query}`,
+ });
+ assert.equal(answer.contentType, 'image/png');
+ assert.equal(answer.known, true);
+ return lons(
+ maskedSegments(segments, fixturePngAlpha(answer.body), { x, y, z }),
+ );
+ };
+ assert.deepEqual(
+ lons(segments).sort(),
+ [KV_LINE.lon, KV_OLD_STREET.lon].sort(),
+ );
+ assert.deepEqual(keptFor('fieldOfView=360'), [KV_LINE.lon]);
+ assert.deepEqual(keptFor('fieldOfView=plane').sort(), lons(segments).sort());
+ const lastYear = new Date(Date.now() - 365 * 86_400_000)
+ .toISOString()
+ .slice(0, 10);
+ assert.deepEqual(keptFor(`startDate=${lastYear}`), [KV_LINE.lon]);
+ assert.deepEqual(keptFor('startDate=2099-01-01'), []);
+ assert.equal(
+ describeKartaViewCall('GET', new URL(`${base}.png?fieldOfView=360`)),
+ 'GET api.kartaview.org/2.0/sequence/tiles/{x}/{y}/{z}.png?fieldOfView',
+ );
+ // The photo search: 360° only, and nothing uploaded after the drive.
+ resetKartaViewFixture();
+ const search = (extra) => {
+ answerKartaViewRequest({
+ method: 'GET',
+ url: 'https://api.kartaview.org/2.0/photo/?lat=0&lng=0',
+ });
+ return body(
+ answerKartaViewRequest({
+ method: 'GET',
+ url: `https://api.kartaview.org/2.0/photo/?lat=${KV_LINE.south + 0.002}&lng=${KV_LINE.lon}&zoomLevel=18&itemsPerPage=10${extra}`,
+ }),
+ ).result.data;
+ };
+ const panos = search('&projection=SPHERE');
+ assert.ok(panos.length > 0);
+ assert.ok(panos.every((record) => record.projection === 'SPHERE'));
+ assert.deepEqual(search('&startDate=2099-01-01'), []);
+ });
diff --cc src/ui/panelPositionControls.js
index 20926198c,41bb67830..f0ba655cf
--- a/src/ui/panelPositionControls.js
+++ b/src/ui/panelPositionControls.js
@@@ -1,4 -1,6 +1,5 @@@
-/** Own panel position preferences, viewport clamping and drag listeners. */
-import { t, msg } from '../i18n/index.js';
-import { RESIZE_DIRECTIONS, resizeBox } from './panelResize.js';
+/** Own panel collapsed-state preferences and the one-time layout-reset notice. */
++import { t } from '../i18n/index.js';
/** Versioned localStorage namespace prefix to invalidate stale panel layouts. */
const PANEL_LAYOUT_STORAGE_VERSION = 'v6';
/**
diff --cc src/ui/rightPanelRail.js
index 70dc776dc,be49999fd..836fd75d4
--- a/src/ui/rightPanelRail.js
+++ b/src/ui/rightPanelRail.js
@@@ -69,8 -69,17 +69,17 @@@ export function layoutRightPanelRail(
// A collapse may schedule one follow-up, which only measures and allocates.
const isCollapseRetry = pendingCollapseRetries.delete(stack);
- // A floating (lifted-out) panel is not laid out by the rail. Neither is one
- // that other CSS hides, such as an event view. Exclusive presentation hides
- // collapsed panels itself; those stay in the rail so they can be restored.
++ // Other CSS may hide a panel, such as an event view: it is not laid out.
++ // Exclusive presentation hides collapsed panels itself; those stay in the
++ // rail so they can be restored.
+ const hiddenByRail = (panel) =>
+ stack.classList.contains('layout-exclusive') &&
+ panel.classList.contains('collapsed');
const panels = [...stack.children].filter(
- (panel) => panel.matches('[data-panel-id]') && !panel.hidden,
+ (panel) =>
- panel.matches('[data-panel-id]:not(.panel-floating)') &&
++ panel.matches('[data-panel-id]') &&
+ !panel.hidden &&
+ (hiddenByRail(panel) || getComputedStyle(panel).display !== 'none'),
);
if (!hud.visible || hud.variant !== 'tactical') {
for (const panel of panels.filter((item) =>
diff --cc src/ui/shellToasts.i18n.test.mjs
index 000000000,9890e01d5..616767016
mode 000000,100644..100644
--- a/src/ui/shellToasts.i18n.test.mjs
+++ b/src/ui/shellToasts.i18n.test.mjs
@@@ -1,0 -1,104 +1,103 @@@
+ // Shell toasts, prompts and launcher labels: pin that they are marked in the
+ // code, present in every shipped catalog, and that no bare literal is left at
+ // the call sites (`window.prompt/confirm` and constants are invisible to the
+ // unmarked-text checker).
+ import { test } from 'node:test';
+ import assert from 'node:assert/strict';
+ import { readFileSync } from 'node:fs';
+ import { fileURLToPath } from 'node:url';
+ import {
+ extractMessages,
+ readCatalog,
+ shippedLocales,
+ } from '../../scripts/i18n.mjs';
+ import { setLocale } from '../i18n/index.js';
+ import {
+ beginDeferredNavigation,
+ reassertNavigationHandoff,
+ runExplicitNavigation,
+ } from '../navigationPolicy.js';
+
+ const KEYS = [
+ 'Tilted view',
+ 'Straight-down view',
+ 'North up',
+ 'Exit cockpit to fly to a camera',
+ 'Exit cockpit to fly to a location',
+ 'Exit cockpit to fly to a photo',
+ 'Exit cockpit to fly to a shared view',
+ 'Go to expanded Radio section',
+ 'Expand Radio section in Context',
- 'Double-click the header to snap the panel back',
+ 'New scene name',
+ 'Delete scene "{scene}" and all shots?',
+ 'Detailed outline unavailable',
+ ];
+
+ const messages = extractMessages();
+
+ for (const key of KEYS) {
+ test(`marked for translation: ${key}`, () => {
+ assert.ok(messages.has(key), `not marked with t()/msg(): ${key}`);
+ });
+ for (const locale of shippedLocales()) {
+ test(`${locale} catalog translates: ${key}`, () => {
+ const value = readCatalog(locale)[key];
+ assert.ok(value, `missing in ${locale}.json`);
+ assert.notEqual(value, key);
+ });
+ }
+ }
+
+ test('no bare literal reaches showToast in the orientation and navigation code', () => {
+ for (const file of [
+ '../ui/cameraOrientationControls.js',
+ '../navigationPolicy.js',
+ '../ui/locationNavigation.js',
+ '../ui/panelPositionControls.js',
+ ]) {
+ const source = readFileSync(
+ fileURLToPath(new URL(file, import.meta.url)),
+ 'utf8',
+ );
+ assert.doesNotMatch(
+ source,
+ /_?showToast\??\.?\(\s*['"`]/,
+ `${file} passes a bare literal to showToast`,
+ );
+ }
+ });
+
+ test.afterEach(() => setLocale('en'));
+
+ test('the Cockpit refusal keeps its English wording per noun', () => {
+ setLocale('en');
+ const log = [];
+ const showToast = (text) => log.push(text);
+ runExplicitNavigation({ cockpitActive: true, noun: 'camera', showToast });
+ beginDeferredNavigation({ cockpitActive: true, showToast });
+ reassertNavigationHandoff({
+ generation: 1,
+ currentGeneration: 1,
+ cockpitActive: true,
+ showToast,
+ });
+ assert.deepEqual(log, [
+ 'Exit cockpit to fly to a camera',
+ 'Exit cockpit to fly to a location',
+ 'Exit cockpit to fly to a location',
+ ]);
+ });
+
+ for (const locale of ['es', 'ru']) {
+ test(`${locale}: the Cockpit refusal is translated`, () => {
+ setLocale(locale);
+ const log = [];
+ runExplicitNavigation({
+ cockpitActive: true,
+ noun: 'camera',
+ showToast: (text) => log.push(text),
+ });
+ assert.equal(log.length, 1);
+ assert.doesNotMatch(log[0], /Exit cockpit/);
+ });
+ }
diff --cc src/ui/streetLevelControls.js
index 7a6fa015e,d15b92e2f..44bd18488
--- a/src/ui/streetLevelControls.js
+++ b/src/ui/streetLevelControls.js
@@@ -4,10 -4,11 +4,11 @@@ import
presentStreetLevelPanel,
SINCE_STOPS,
} from './streetLevelPresentation.js';
-
+ import { t, translateKnown } from '../i18n/index.js';
+
const RENDER_MODE_KEY = 'gev:street-level:render-mode';
-const FOCUSABLE =
- 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';
+/** <body> classes of the modes that hide every panel; an expanded photo leaves with them. */
+const PANEL_HIDING_MODES = ['ui-clean-view', 'recording-mode', 'cockpit-mode'];
const RADIO_STEPS = Object.freeze({
ArrowRight: 1,
ArrowDown: 1,
@@@ -55,12 -65,18 +56,16 @@@ export class StreetLevelControls
];
return {
status: byId('sl-status'),
- controls: byId('sl-controls'),
providerChips: byId('sl-provider-chips'),
+ nearestBtn: byId('sl-nearest-btn'),
+ controls: byId('sl-controls'),
error: byId('sl-error'),
errorText: byId('sl-error-text'),
+ panoRow: byId('sl-pano-row'),
+ sinceRow: byId('sl-since-row'),
sinceRange: byId('sl-since'),
sinceLabel: byId('sl-since-label'),
+ sinceNote: byId('sl-since-note'),
- legend: byId('sl-legend'),
- followBtn: byId('sl-follow-btn'),
viewerWrap: byId('sl-viewer-wrap'),
viewerExpand: byId('sl-viewer-expand'),
viewerClose: byId('sl-viewer-close'),
@@@ -117,33 -136,22 +124,42 @@@
this.listen(el.sinceRange, 'change', () =>
this._setParams({ sinceDays: sinceDays() }),
);
+ this.listen(el.nearestBtn, 'click', () => {
+ const nearest = this._view?.nearest;
+ if (!nearest?.visible || nearest.disabled) return;
+ this.layer.openNearest?.(undefined, {
+ providerIds: nearest.providerIds,
+ frame: false,
+ aim: 'screen-centre',
+ });
+ });
- this.listen(el.followBtn, 'click', () => {
- this.layer.setFollow?.(!(this._state?.street?.follow === true));
- });
this.listen(el.viewerClose, 'click', () => this.layer.closeViewer?.());
- this.listen(el.viewerExpand, 'click', () =>
- this.setViewerExpanded(!this.isViewerExpanded(), { dock: true }),
- );
+ // EXPAND is the browser's fullscreen. iPhone Safari has no element
+ // fullscreen, so there it is a top-layer popover; with neither, no button.
+ this._expandMode =
+ typeof el.viewerWrap?.requestFullscreen === 'function'
+ ? 'fullscreen'
+ : typeof el.viewerWrap?.showPopover === 'function'
+ ? 'popover'
+ : null;
+ this._popoverOpen = false;
+ if (this._expandMode) {
+ this.listen(el.viewerExpand, 'click', () => this._toggleExpanded());
+ if (this._expandMode === 'fullscreen')
+ this.listen(document, 'fullscreenchange', () => this._syncExpanded());
+ else
+ this.listen(el.viewerWrap, 'toggle', (event) =>
+ this._onPopoverToggle(event),
+ );
+ // Esc shrinks the photo before the panel's own Esc can collapse it, in
+ // a browser that hands the key to the page while full screen too.
+ this.listen(el.viewerWrap, 'keydown', (event) => {
+ if (event.key !== 'Escape' || !this.isViewerExpanded()) return;
+ event.preventDefault();
+ event.stopPropagation();
+ this._exitExpanded();
+ });
+ } else setProp(el.viewerExpand, 'hidden', true);
for (const button of el.renderButtons) {
this.listen(button, 'click', () => {
const mode = button.dataset.slRender;
@@@ -204,26 -224,36 +220,29 @@@
});
}
- async _ensureEnabled() {
- if (this.actions.isEnabled?.()) return true;
+ async _toggleEnabled() {
+ const enabled = this.actions.isEnabled?.() === true;
try {
- await this.actions.setEnabled?.(true);
+ await this.actions.setEnabled?.(!enabled);
} catch (error) {
- this.actions.showToast?.(error?.message || 'Street Level toggle failed');
+ this.actions.showToast?.(
- translateKnown(error?.message || '') ||
- t('Street Level could not start'),
++ translateKnown(error?.message || '') || t('Street Level toggle failed'),
+ );
- return false;
}
- return this.actions.isEnabled?.() === true;
}
- async _toggleEnabled() {
- const enabled = this.actions.isEnabled?.() === true;
+ async _ensureEnabled() {
+ if (this.actions.isEnabled?.()) return true;
try {
- await this.actions.setEnabled?.(!enabled);
+ await this.actions.setEnabled?.(true);
} catch (error) {
this.actions.showToast?.(
- error?.message || 'Street Level could not start',
- translateKnown(error?.message || '') || t('Street Level toggle failed'),
++ translateKnown(error?.message || '') ||
++ t('Street Level could not start'),
);
+ return false;
}
- }
-
- /** Through the data manager, so saved state and share links record it. */
- _setParams(params) {
- if (this.actions.setParams)
- this.actions.setParams(params, { origin: 'user' });
- else this.layer.setParams?.(params);
+ return this.actions.isEnabled?.() === true;
}
/**
@@@ -252,110 -283,195 +272,110 @@@
}
}
- connect() {
- this._unsubscribe?.();
- this._unsubscribe = null;
- if (this.destroyed || !this.root) return;
- this._unsubscribeEnableRequests?.();
- this._unsubscribeEnableRequests =
- this.actions.subscribeEnableRequests?.((origin) => {
- this._explicitEnable = isExplicitLayerStateOrigin(origin);
- }) || null;
- this._unsubscribe = this.layer.subscribe?.((state) => this.render(state));
- if (this.layer.getUIState) this.render(this.layer.getUIState());
- }
-
- onPanelResized() {
- this._requestResize();
- }
-
- setCollapsed(collapsed, options = {}) {
- this.actions.setPanelCollapsed?.(collapsed, options);
- if (!collapsed) this._requestResize();
+ /** Through the data manager, so saved state and share links record it. */
+ _setParams(params) {
+ this.actions.setParams(params, { origin: 'user' });
}
+ /** Whether EXPAND has the viewer full screen (or, on iPhone, open over the page). */
isViewerExpanded() {
- return (
- this._elements.viewerWrap?.classList.contains(
- 'sl-viewer-wrap-expanded',
- ) === true
- );
+ const wrap = this._elements.viewerWrap;
+ if (!wrap) return false;
+ return this._expandMode === 'popover'
+ ? this._popoverOpen
+ : document.fullscreenElement === wrap;
}
- /**
- * A user's shrink (`dock`) also returns a floating panel to its rail, so the
- * viewer does not land in a window over the globe.
- */
- setViewerExpanded(expanded, { dock = false } = {}) {
+ async _toggleExpanded() {
const wrap = this._elements.viewerWrap;
- if (!wrap) return;
- const on = expanded === true;
- if (on === this.isViewerExpanded()) return;
- if (on) {
- // Lift the viewer out of the panel: the panel's backdrop-filter would
- // otherwise pin a fixed-position child inside it.
- this._wrapHome = { parent: wrap.parentNode, next: wrap.nextSibling };
- this._expandReturnFocus = document.activeElement;
- document.body.appendChild(wrap);
- wrap.classList.add('sl-viewer-wrap-expanded');
- wrap.setAttribute('role', 'dialog');
- wrap.setAttribute('aria-modal', 'true');
- wrap.setAttribute('aria-label', t('Street-level image'));
- wrap.tabIndex = -1;
- wrap.focus({ preventScroll: true });
- this._watchModal(true);
- } else {
- // Release the application first: the focus returned below may be in it.
- this._watchModal(false);
- wrap.classList.remove('sl-viewer-wrap-expanded');
- wrap.removeAttribute('role');
- wrap.removeAttribute('aria-modal');
- wrap.removeAttribute('aria-label');
- wrap.removeAttribute('tabindex');
- if (this._wrapHome?.parent)
- this._wrapHome.parent.insertBefore(wrap, this._wrapHome.next);
- this._wrapHome = null;
- const target = this._expandReturnFocus;
- this._expandReturnFocus = null;
- // A closed image hides the wrap: focus inside it would drop to <body>.
- const reachable = (node) =>
- node?.isConnected &&
- typeof node.focus === 'function' &&
- !(wrap.hidden && wrap.contains(node));
- if (reachable(target)) target.focus({ preventScroll: true });
- else if (reachable(this._elements.viewerExpand))
- this._elements.viewerExpand.focus({ preventScroll: true });
- else this._focusPanelControl();
- }
- const button = this._elements.viewerExpand;
- if (button) {
- const icon = button.querySelector('.sl-btn-icon');
- const text = button.querySelector('.sl-btn-text');
- if (icon) icon.textContent = on ? '⤡' : '⤢';
- if (text) text.textContent = on ? t('SHRINK') : t('EXPAND');
- button.setAttribute('aria-pressed', String(on));
- button.setAttribute('aria-label', on ? t('Shrink') : t('Expand'));
+ try {
+ if (this.isViewerExpanded()) this._exitExpanded();
+ else if (this._expandMode === 'fullscreen')
+ await wrap.requestFullscreen();
+ else {
+ // Only while open: a closed popover is hidden even inside the panel.
+ wrap.popover = 'auto';
+ wrap.showPopover();
+ }
+ } catch {
+ /* refused (no user gesture, policy): the panel view stays */
}
- if (!on && dock) this.actions.dockPanel?.();
- this._requestResize();
}
- /** Park focus on a control that stays on screen while the viewer is hidden. */
- _focusPanelControl() {
- const el = this._elements;
- const target =
- el.status || el.providerChips?.querySelector('.data-toggle-chip');
- target?.focus?.({ preventScroll: true });
+ _exitExpanded() {
+ if (!this.isViewerExpanded()) return;
+ if (this._expandMode === 'popover') this._elements.viewerWrap.hidePopover();
+ else document.exitFullscreen().catch(() => {});
}
- /** Clean View, recording and the cockpit hide the expanded viewer with CSS. */
- _isDialogShown() {
- if (!this.isViewerExpanded()) return false;
- const wrap = this._elements.viewerWrap;
- return (
- typeof wrap.checkVisibility !== 'function' ||
- // `checkVisibilityCSS` is the option's name before Chrome 121.
- wrap.checkVisibility({
- visibilityProperty: true,
- checkVisibilityCSS: true,
- })
- );
+ _onPopoverToggle(event) {
+ this._popoverOpen = event.newState === 'open';
+ if (!this._popoverOpen)
+ this._elements.viewerWrap.removeAttribute('popover');
+ this._syncExpanded();
}
- /**
- * Make every other <body> child inert while the expanded viewer is shown.
- * A CSS-hidden viewer releases them so a hidden modal never leaves the app
- * dead. Returns whether the dialog is shown.
- */
- _syncModal() {
- if (this.destroyed || !this._isDialogShown()) {
- this._releaseModal();
- return false;
- }
- const wrap = this._elements.viewerWrap;
- for (const node of [...(document.body?.children || [])]) {
- if (node === wrap || node.inert) continue;
- node.inert = true;
- this._inerted.add(node);
+ /** Clean View, recording and the cockpit hide every panel, so they end EXPAND too. */
+ _watchPanelHidingModes(on) {
+ const body = document.body;
+ if (!on || !body) {
+ this._modesObserver?.disconnect();
+ this._modesObserver = null;
+ return;
}
- return true;
- }
-
- _releaseModal() {
- for (const node of this._inerted) node.inert = false;
- this._inerted.clear();
- }
-
- /** Re-check the modal when <body> changes class or gains a child. */
- _watchModal(on) {
- this._modalObserver?.disconnect();
- this._modalObserver = null;
- if (!on) return this._releaseModal();
- if (typeof MutationObserver === 'function' && document.body) {
- this._modalObserver = new MutationObserver(() => this._syncModal());
- this._modalObserver.observe(document.body, {
+ const leaveIfHiding = () => {
+ if (PANEL_HIDING_MODES.some((mode) => body.classList.contains(mode)))
+ this._exitExpanded();
+ };
+ if (!this._modesObserver && typeof MutationObserver === 'function') {
+ this._modesObserver = new MutationObserver(leaveIfHiding);
+ this._modesObserver.observe(body, {
attributes: true,
attributeFilter: ['class'],
- childList: true,
});
}
- this._syncModal();
+ leaveIfHiding();
}
- _onDialogKey(event) {
- if (event.key !== 'Escape' && event.key !== 'Tab') return;
- if (!this._syncModal()) return;
- // Only keys meant for the viewer: from inside it, from nowhere (<body>)
- // or from the globe. A field elsewhere (search) keeps its Esc and Tab.
- const target = event.target;
- const wrap = this._elements.viewerWrap;
- if (
- !wrap.contains(target) &&
- target !== document.body &&
- target !== document.documentElement &&
- !target?.closest?.('#cesiumContainer')
- )
- return;
- if (event.key === 'Escape') {
- event.preventDefault();
- event.stopPropagation();
- this.setViewerExpanded(false, { dock: true });
- return;
+ /** Mirror the expanded state on EXPAND, watch the panel-hiding modes, refit. */
+ _syncExpanded() {
+ const on = this.isViewerExpanded();
+ this._watchPanelHidingModes(on);
+ const button = this._elements.viewerExpand;
+ if (button) {
+ setProp(
+ button.querySelector('.sl-btn-icon'),
+ 'textContent',
+ on ? '⤡' : '⤢',
+ );
+ setProp(
+ button.querySelector('.sl-btn-text'),
+ 'textContent',
- on ? 'SHRINK' : 'EXPAND',
++ on ? t('SHRINK') : t('EXPAND'),
+ );
+ setAttr(button, 'aria-pressed', String(on));
- setAttr(button, 'aria-label', on ? 'Shrink' : 'Expand');
++ setAttr(button, 'aria-label', on ? t('Shrink') : t('Expand'));
}
- // A radio off the roving tab stop (tabindex -1) is not a stop either.
- const focusable = [...wrap.querySelectorAll(FOCUSABLE)].filter(
- (node) =>
- node.getAttribute('tabindex') !== '-1' &&
- (node.offsetParent !== null || node === document.activeElement),
+ this._requestResize();
+ }
+
+ connect() {
+ this._unsubscribe?.();
+ this._unsubscribe = null;
+ if (this.destroyed || !this.root) return;
+ this._unsubscribeEnableRequests?.();
+ this._unsubscribeEnableRequests = this.actions.subscribeEnableRequests(
+ (origin) => {
+ this._explicitEnable = isExplicitLayerStateOrigin(origin);
+ },
);
- if (!focusable.length) return;
- const first = focusable[0];
- const last = focusable[focusable.length - 1];
- if (event.shiftKey && document.activeElement === first) {
- event.preventDefault();
- last.focus();
- } else if (!event.shiftKey && document.activeElement === last) {
- event.preventDefault();
- first.focus();
- } else if (!wrap.contains(document.activeElement)) {
- event.preventDefault();
- first.focus();
- }
+ this._unsubscribe = this.layer.subscribe?.((state) => this.render(state));
+ if (this.layer.getUIState) this.render(this.layer.getUIState());
+ }
+
+ setCollapsed(collapsed, options = {}) {
+ this.actions.setPanelCollapsed?.(collapsed, options);
+ if (!collapsed) this._requestResize();
}
render(state) {
@@@ -369,8 -485,9 +389,9 @@@
this._renderError(view);
this._renderFilters(view);
this._renderViewer(view);
- this._renderMeta(view);
+ setProp(this._elements.coverageMeta, 'textContent', view.meta);
+ this._renderNearest(view);
- this._reactToTransitions(view, state);
+ this._reactToTransitions(view);
}
_renderHeader(view) {
@@@ -406,6 -531,14 +427,13 @@@
_renderFilters(view) {
const el = this._elements;
+ const shows = view.filterControls || { pano: true, since: true };
+ setProp(el.panoRow, 'hidden', !shows.pano);
+ setProp(el.sinceRow, 'hidden', !shows.since);
+ // A lit source that dates by upload says so under the slider.
+ setProp(el.sinceNote, 'textContent', view.sinceNote || '');
+ setProp(el.sinceNote, 'hidden', !view.sinceNote);
+ setProp(el.controls, 'hidden', !shows.pano && !shows.since);
- setProp(el.legend, 'hidden', view.legend.length === 0);
this._renderRadios(
el.panoButtons,
(button) => button.dataset.slPano === view.filter.pano,
@@@ -454,6 -620,21 +485,17 @@@
}
}
- _renderMeta(view) {
- setProp(this._elements.coverageMeta, 'textContent', view.meta);
- }
-
+ _renderNearest(view) {
+ const button = this._elements.nearestBtn;
+ if (!button) return;
+ const { nearest } = view;
+ setProp(button, 'hidden', !nearest.visible);
+ if (!nearest.visible) return;
+ setProp(button, 'textContent', nearest.label);
+ setProp(button, 'title', nearest.title);
+ setProp(button, 'disabled', nearest.disabled);
+ }
+
/**
* Open the panel on a switch-on or when an image opens. Never persisted:
* the stored collapse state stays the user's own choice.
diff --cc src/ui/streetLevelControls.test.mjs
index 877292bed,eb572781b..1614fb0aa
--- a/src/ui/streetLevelControls.test.mjs
+++ b/src/ui/streetLevelControls.test.mjs
@@@ -2,7 -3,6 +3,7 @@@ import fs from 'node:fs'
import test from 'node:test';
import { StreetLevelControls } from './streetLevelControls.js';
import { createStreetLevelLayer } from '../layers/streetLevel/index.js';
- import { createMapillaryProvider } from '../layers/streetLevel/mapillaryProvider.js';
++import { createMapillaryProvider } from '../layers/streetLevel/providers/mapillary/index.js';
import { DataLayerManager } from '../data/manager.js';
import { LayerStateCoordinator } from '../data/layerStateCoordinator.js';
import {
@@@ -203,33 -287,14 +204,34 @@@ function panelDom({ fullscreen = true,
const add = (parent, tag, options) =>
parent.appendChild(new FakeNode(document, tag, options));
add(root, 'button', { id: 'sl-status' });
- const main = add(root, 'div', { classes: ['sl-main'] });
- // The viewer's own tool bar lives inside the wrap, as in the markup.
- const wrap = add(main, 'div', { id: 'sl-viewer-wrap' });
- add(wrap, 'button', { id: 'sl-viewer-expand' });
+ add(root, 'div', { id: 'sl-provider-chips' });
+ const wrap = add(root, 'div', { id: 'sl-viewer-wrap' });
+ if (fullscreen) wrap.requestFullscreen = async () => fullscreenTo(wrap);
+ if (popover) {
+ // `popover` reflects its attribute, as in the DOM.
+ Object.defineProperty(wrap, 'popover', {
+ get: () => wrap.getAttribute('popover'),
+ set: (value) => wrap.setAttribute('popover', value),
+ });
+ // The browser fires `toggle` after the popover opens or closes.
+ const toggleTo = (newState) =>
+ setTimeout(() => wrap.dispatchEvent({ type: 'toggle', newState }), 0);
+ wrap.showPopover = () => {
+ wrap.popoverOpen = true;
+ toggleTo('open');
+ };
+ wrap.hidePopover = () => {
+ wrap.popoverOpen = false;
+ toggleTo('closed');
+ };
+ }
+ const expand = add(wrap, 'button', { id: 'sl-viewer-expand' });
+ add(expand, 'span', { classes: ['sl-btn-icon'] });
+ add(expand, 'span', { classes: ['sl-btn-text'] });
++ const fit = add(wrap, 'div', { classes: ['sl-seg'] });
for (const mode of ['letterbox', 'fill'])
-- add(wrap, 'button', { dataset: { slRender: mode } });
- for (const id of ['sl-follow-btn', 'sl-viewer-close'])
- add(wrap, 'button', { id });
++ add(fit, 'button', { dataset: { slRender: mode } });
+ add(wrap, 'button', { id: 'sl-viewer-close' });
for (const id of [
'sl-viewer-placeholder',
'sl-viewer',
@@@ -238,15 -303,31 +240,20 @@@
'sl-image-link',
])
add(wrap, id === 'sl-image-link' ? 'a' : 'div', { id });
- const settings = add(main, 'div', { classes: ['sl-settings'] });
- for (const id of ['sl-provider-chips', 'sl-error', 'sl-error-text'])
- add(settings, 'div', { id });
- // A missing key gates the filters only; the chips stay outside the gate.
- const controls = add(settings, 'fieldset', { id: 'sl-controls' });
+ const error = add(root, 'div', { id: 'sl-error' });
+ add(error, 'span', { id: 'sl-error-text' });
+ const controls = add(root, 'fieldset', { id: 'sl-controls' });
+ const panoRow = add(controls, 'div', { id: 'sl-pano-row' });
for (const pano of ['all', 'pano', 'flat'])
- add(controls, 'button', { dataset: { slPano: pano } });
- add(controls, 'input', { id: 'sl-since' });
- add(controls, 'output', { id: 'sl-since-label' });
- add(root, 'div', { id: 'sl-coverage-meta' });
+ add(panoRow, 'button', { dataset: { slPano: pano } });
+ const sinceRow = add(controls, 'div', { id: 'sl-since-row' });
+ add(sinceRow, 'input', { id: 'sl-since' });
+ add(sinceRow, 'output', { id: 'sl-since-label' });
+ add(sinceRow, 'small', { id: 'sl-since-note' });
- add(settings, 'ul', { id: 'sl-legend' });
- const metaRow = add(settings, 'div', { classes: ['sl-meta-row'] });
++ const metaRow = add(root, 'div', { classes: ['sl-meta-row'] });
+ add(metaRow, 'div', { id: 'sl-coverage-meta' });
+ add(metaRow, 'button', { id: 'sl-nearest-btn' });
- // The globe's canvas is focusable too (tabindex=0).
- const globe = add(
- add(document.body, 'div', { id: 'cesiumContainer' }),
- 'canvas',
- );
- globe.setAttribute('tabindex', '0');
- // A field in another panel (the location search).
- const search = add(document.body, 'input', { id: 'location-search' });
- return { document, root, globe, search, main, wrap, settings };
+ return { document, root, wrap };
}
/** Run `fn` with the fake document and an immediate animation frame. */
@@@ -506,39 -584,24 +513,39 @@@ test('lighting a dark chip switches th
[{ mapillary: true }, { origin: 'user' }],
]);
assert.deepEqual(calls.setEnabled, [true]);
+ controls.destroy();
+ }));
+
+test('under KEY REQUIRED the provider chip stays live and explains the key instead of toggling', () =>
+ withDom(async (dom) => {
+ const { calls, chip, controls } = stubPanel(
+ dom,
+ uiState({ keyRequired: true }),
+ );
+ assert.equal(
+ dom.root.querySelector('#sl-controls').contains(chip()),
+ false,
+ 'the chip is outside the disabled fieldset',
+ );
+ chip().click();
+ await settle();
+ assert.deepEqual(calls.setEnabled, []);
+ assert.deepEqual(calls.setParams, []);
+ assert.equal(calls.toasts.length, 1);
+ assert.match(calls.toasts[0], /^Mapillary: Needs /);
+ controls.destroy();
}));
-test('the legend rebuilds when a swatch changes, even at the same count', () =>
+test('under KEY REQUIRED the filters are gated and the error line says how to add the key', () =>
withDom(async (dom) => {
- const { layer } = stubPanel(dom, uiState());
- const legend = dom.root.querySelector('#sl-legend');
- const swatch = () => legend.children[0].children[0].style.background;
- assert.equal(swatch(), '#05cb63');
- layer.publish(
- uiState({
- legend: [
- { key: 'panoramax', label: 'Panoramax', color: '#a66bff' },
- { key: 'selected', label: 'Selected', color: '#00d4ff' },
- ],
- }),
+ const { controls } = stubPanel(dom, uiState({ keyRequired: true }));
+ assert.equal(dom.root.querySelector('#sl-controls').disabled, true);
+ assert.equal(dom.root.querySelector('#sl-error').hidden, false);
+ assert.match(
+ dom.root.querySelector('#sl-error-text').textContent,
- /^Mapillary: Needs MAPILLARY_CLIENT_TOKEN/,
++ /^Needs MAPILLARY_CLIENT_TOKEN/,
);
- assert.equal(legend.childElementCount, 2);
- assert.equal(swatch(), '#a66bff');
+ controls.destroy();
}));
test('the viewer is resized once when it opens, not on every render', () =>
@@@ -855,3 -1042,242 +862,158 @@@ test('arrow keys move the selection wit
);
controls.destroy();
}));
+
+ test('under KEY REQUIRED the provider chip stays live and explains the key instead of toggling (P3)', () =>
+ withDom(async (dom) => {
+ const { calls, chip, controls } = stubPanel(
+ dom,
+ uiState({ keyRequired: true }),
+ );
+ assert.equal(dom.root.querySelector('#sl-controls').disabled, true);
+ assert.equal(
+ dom.root.querySelector('#sl-controls').contains(chip()),
+ false,
+ 'the chip is outside the disabled fieldset',
+ );
+ chip().click();
+ await settle();
+ assert.deepEqual(calls.setEnabled, []);
+ assert.deepEqual(calls.setParams, []);
+ assert.equal(calls.toasts.length, 1);
+ assert.match(calls.toasts[0], /^Mapillary: Needs /);
+ controls.destroy();
+ }));
+
-/* ── The expanded viewer goes back where it came from ──────────────────── */
-
-/** A node by name, so a failed comparison prints a word, not the DOM. */
-const nameOf = (node) =>
- node ? node.id || node.className || node.tagName.toLowerCase() : null;
-
-/** Where the viewer sits: its parent and the sibling it sits before. */
-const placeOf = (wrap) => [nameOf(wrap.parentNode), nameOf(wrap.nextSibling)];
-const PANEL_PLACE = ['sl-main', 'sl-settings'];
-
-test('shrinking returns the viewer into the panel at its own place', () =>
- withDom(async (dom) => {
- const { controls } = stubPanel(dom, uiState({ open: true }));
- assert.deepEqual(placeOf(dom.wrap), PANEL_PLACE);
- controls.setViewerExpanded(true);
- assert.equal(nameOf(dom.wrap.parentNode), 'body', 'lifted out');
- controls.setViewerExpanded(false);
- assert.deepEqual(placeOf(dom.wrap), PANEL_PLACE, 'before the settings');
- assert.equal(dom.main.children.indexOf(dom.wrap), 0);
- assert.equal(dom.root.contains(dom.wrap), true);
- // A second round trip lands in the same place.
- controls.setViewerExpanded(true);
- controls.setViewerExpanded(false);
- assert.deepEqual(placeOf(dom.wrap), PANEL_PLACE);
- controls.destroy();
- }));
-
-test('an image closed while expanded returns the viewer into the panel', () =>
- withDom(async (dom) => {
- const { layer, controls } = stubPanel(dom, uiState({ open: true }));
- controls.setViewerExpanded(true);
- layer.publish(uiState({ open: false }));
- assert.deepEqual(placeOf(dom.wrap), PANEL_PLACE);
- assert.equal(dom.wrap.hidden, true, 'and hidden there');
- controls.destroy();
- }));
-
-test('destroying the panel while expanded returns the viewer into it', () =>
- withDom(async (dom) => {
- const { controls } = stubPanel(dom, uiState({ open: true }));
- controls.setViewerExpanded(true);
- controls.destroy();
- assert.deepEqual(placeOf(dom.wrap), PANEL_PLACE);
- assert.equal(
- dom.document.body.children.includes(dom.wrap),
- false,
- 'nothing left on <body>',
- );
- }));
-
-test('a <body> child added while the viewer is expanded goes inert with the rest', () =>
- withObserver((observer) =>
- withDom(async (dom) => {
- const { controls } = stubPanel(dom, uiState({ open: true }));
- controls.setViewerExpanded(true);
- // A toast, a menu or another panel's popup, appended later.
- const toast = dom.document.body.appendChild(
- new FakeNode(dom.document, 'div', { id: 'toast' }),
- );
- assert.equal(toast.inert, undefined, 'not before the observer runs');
- await settle(); // records are delivered in a microtask
- assert.equal(toast.inert, true);
- // Changes inside the app are not the modal's business: nothing runs.
- let syncs = 0;
- const sync = controls._syncModal.bind(controls);
- controls._syncModal = () => {
- syncs++;
- return sync();
- };
- dom.root.querySelector('#sl-status').setAttribute('class', 'x');
- dom.root.appendChild(new FakeNode(dom.document, 'div'));
- await settle();
- assert.equal(syncs, 0);
- controls.destroy();
- assert.equal(toast.inert, false, 'destroy releases it too');
- assert.equal(observer.watching(), false);
- }),
- ));
-
+ test('OPEN STREET VIEW opens the nearest panorama at the view centre without moving the camera', () =>
+ withDom(async (dom) => {
+ const state = uiState();
+ state.providers.push({
+ ...state.providers[0],
+ id: 'google',
+ name: 'Google Street View',
+ label: 'STREET VIEW',
+ groundClick: true,
+ count: 0,
+ });
+ state.groundClickReady = true;
+ const { layer } = stubPanel(dom, state);
+ const asked = [];
+ layer.openNearest = (point, options) => asked.push([point, options]);
+ const button = dom.root.querySelector('#sl-nearest-btn');
+ assert.equal(button.hidden, false);
+ assert.equal(button.textContent, 'OPEN STREET VIEW');
+ button.click();
+ assert.deepEqual(asked, [
+ [
+ undefined,
+ { providerIds: ['google'], frame: false, aim: 'screen-centre' },
+ ],
+ ]);
+ // Too high to mean a street: disabled, and a click does nothing.
+ layer.publish({ ...state, groundClickReady: false });
+ assert.equal(button.disabled, true);
+ button.click();
+ assert.equal(asked.length, 1);
+ // Off Google 3D the provider is not listed: no button.
+ layer.publish({ ...state, providers: [state.providers[0]] });
+ assert.equal(button.hidden, true);
+ }));
+
+ test('a refused Street View key cannot lock Mapillary out; its chip only explains itself', () =>
+ withDom(async (dom) => {
+ const state = uiState({ on: false, keyRequired: true });
+ state.providers.push({
+ ...state.providers[0],
+ id: 'google',
+ name: 'Google Street View',
+ label: 'STREET VIEW',
+ on: true,
+ keyRequired: true,
+ keyRejected: true,
+ error: 'Google refused GOOGLE_MAPS_API_KEY for Street View',
+ });
+ state.providers[0].keyRequired = false;
+ const { calls, layer } = stubPanel(dom, state);
+ const chips = () => dom.root.querySelector('#sl-provider-chips').children;
+ chips()[0].click(); // Mapillary: configured, dark
+ await settle();
+ // One source at a time: lighting Mapillary darkens Street View too.
+ assert.deepEqual(calls.setParams, [
+ [{ mapillary: true, google: false }, { origin: 'user' }],
+ ]);
+ // Now dark, the refused chip says why instead of lighting.
+ state.providers[0].on = true;
+ state.providers[1].on = false;
+ state.keyRequired = false;
+ layer.publish({ ...state });
+ chips()[1].click();
+ await settle();
+ assert.equal(calls.setParams.length, 1);
+ assert.deepEqual(calls.toasts, [
+ dom.root.querySelector('#sl-provider-chips').children[1].title,
+ ]);
+ }));
+
+ test('a swap names every registered provider, also those hidden on this map', () =>
+ withDom(async (dom) => {
+ const state = uiState({ on: false });
+ const { calls, layer, chip } = stubPanel(dom, state);
+ // Off Google 3D the Street View chip is not listed, but stays registered.
+ layer.providerIds = ['mapillary', 'google'];
+ chip().click();
+ await settle();
+ assert.deepEqual(calls.setParams, [
+ [{ mapillary: true, google: false }, { origin: 'user' }],
+ ]);
+ }));
+
+ test('a note under SINCE says what date it compares, only while one is given', () =>
+ withDom(async (dom) => {
+ const state = uiState();
+ const { layer } = stubPanel(dom, state);
+ const note = () => dom.root.querySelector('#sl-since-note');
+ assert.equal(note().hidden, true, 'none for Mapillary');
+ layer.publish({ ...state, sinceNote: 'KartaView: by upload date' });
+ assert.equal(note().hidden, false);
+ assert.equal(note().textContent, 'KartaView: by upload date');
+ layer.publish(state);
+ assert.equal(note().hidden, true);
+ // The panel's own markup has it, read out with the slider.
+ const template = fs.readFileSync(
+ new URL('./templates/layer-panels.html', import.meta.url),
+ 'utf8',
+ );
+ assert.match(template, /<small id="sl-since-note"[^>]* hidden>/);
+ assert.match(template, /aria-describedby="sl-since-label sl-since-note"/);
+ }));
+
-test('Street View lit hides the imagery filters and the legend; Mapillary lit shows them', () =>
++test('Street View lit hides the imagery filters; Mapillary lit shows them', () =>
+ withDom(async (dom) => {
+ const state = uiState();
+ const { layer } = stubPanel(dom, state);
+ const shown = () => ({
+ pano: !dom.root.querySelector('#sl-pano-row').hidden,
+ since: !dom.root.querySelector('#sl-since-row').hidden,
+ controls: !dom.root.querySelector('#sl-controls').hidden,
- legend: !dom.root.querySelector('#sl-legend').hidden,
+ });
+ assert.deepEqual(shown(), {
+ pano: true,
+ since: true,
+ controls: true,
- legend: true,
+ });
+ layer.publish({
+ ...state,
+ filterControls: { pano: false, since: false },
- legend: [],
+ });
+ assert.deepEqual(shown(), {
+ pano: false,
+ since: false,
+ controls: false,
- legend: false,
+ });
+ layer.publish(state);
+ assert.deepEqual(shown(), {
+ pano: true,
+ since: true,
+ controls: true,
- legend: true,
+ });
+ }));
diff --cc src/ui/streetLevelPresentation.js
index 5c5f196bd,d7d31da2e..7df0e298e
--- a/src/ui/streetLevelPresentation.js
+++ b/src/ui/streetLevelPresentation.js
@@@ -117,56 -181,151 +181,150 @@@ function presentViewer(state)
open: street.open === true,
loading: street.loading === true && !street.imageId,
renderMode: street.renderMode === 'fill' ? 'fill' : 'letterbox',
- captionLeft: street.creator ? `Image by ${street.creator}` : '',
+ renderModes: street.renderModes !== false,
+ captionLeft: left.join(' · '),
captionRight: right.join(' · '),
link: street.externalUrl || null,
- linkLabel: street.providerLabel ? `${street.providerLabel} ↗` : '',
+ linkLabel: street.providerLabel
+ ? `${translateKnown(street.providerLabel)} ↗`
+ : '',
- follow: {
- pressed: street.follow === true,
- disabled: street.open !== true || street.followAvailable !== true,
- title:
- street.followAvailable === true
- ? t(
- 'Camera follows view: move the globe camera wherever the street-level view looks',
- )
- : t(
- 'Camera follow needs the Google 3D map: choose Google 3D under MAP SOURCE',
- ),
- },
};
}
+ /** OPEN STREET VIEW: the keyboard path to providers with no coverage to click. */
+ function presentNearest(state) {
+ const targets = (state.providers || []).filter(
+ (provider) =>
+ provider.on && provider.groundClick && provider.keyRequired !== true,
+ );
+ if (state.enabled !== true || !targets.length)
+ return {
+ visible: false,
+ label: '',
+ title: '',
+ disabled: true,
+ providerIds: [],
+ };
+ const names = targets
+ .map((provider) => translateKnown(provider.name))
+ .join(t(' or '));
+ const labels = targets
+ .map((provider) => translateKnown(provider.label))
+ .join(' / ');
+ const ready = state.groundClickReady === true;
+ return {
+ visible: true,
+ label: t('OPEN {labels}', { labels }),
+ title: ready
+ ? t('Open {names} at the centre of the view', { names })
+ : t('Zoom in to a street to open {names} here', { names }),
+ disabled: !ready || state.street.loading === true,
+ providerIds: targets.map((provider) => provider.id),
+ };
+ }
+
+ /** Provider hints are English data joined by " · "; translate each part. */
+ function translateHint(hint) {
+ return hint ? hint.split(' · ').map(translateKnown).join(' · ') : '';
+ }
+
function presentMeta(state) {
- if (state.providers.length === 0) return translateHint(state.coverage.hint);
- if (!state.enabled) return t('Switch a provider on to draw its coverage.');
+ const providers = state.providers || [];
- if (providers.length === 0) return state.coverage.hint || '';
- if (!state.enabled) return 'Switch Street Level on to draw its coverage.';
++ if (providers.length === 0) return translateHint(state.coverage.hint);
++ if (!state.enabled) return t('Switch Street Level on to draw its coverage.');
+ if (!providers.some((p) => p.on))
- return 'Every provider is switched off: light a chip to draw its coverage.';
++ return t(
++ 'Every provider is switched off: light a chip to draw its coverage.',
++ );
+ // Key-gated with another source ready: say how to use it.
+ if (state.keyRequired && state.keyAlternatives?.length)
+ return keyGuidance(state);
if (state.sequence.selectedId)
return state.sequence.loading
- ? 'Loading this sequence…'
- : `${state.sequence.images.toLocaleString()} images in this sequence · Esc clears`;
- if (state.coverage.count > 0)
- return `${state.coverage.count.toLocaleString()} sequences in view · click a line for its photos`;
- if (state.coverage.hint) return state.coverage.hint;
+ ? t('Loading this sequence…')
+ : tn(
+ state.sequence.images,
+ '{n} image in this sequence · Esc clears',
+ '{n} images in this sequence · Esc clears',
+ { n: formatNumber(state.sequence.images) },
+ );
+ const hint = translateHint(state.coverage.hint);
+ if (state.coverage.count > 0) {
+ const countLine = coverageCountLine(state.coverage);
+ return [countLine, hint].filter(Boolean).join(' · ');
+ }
- return hint;
++ if (hint) return hint;
+ // Still loading, or the error line already says why.
+ if (state.coverage.loading || state.keyRequired || state.coverage.error)
+ return '';
+ const filter = state.filter || {};
+ return (filter.pano || 'all') !== 'all' || Number(filter.sinceDays) > 0
- ? 'No sequences in view match the filter'
- : 'No coverage in view';
++ ? t('No sequences in view match the filter')
++ : t('No coverage in view');
+ }
+
+ /**
+ * The coverage count line. Providers carry their wording as data
+ * (coverageLabel noun/action); each combination needs its own literal tn
+ * pair so every language gets real plural forms — the noun cannot inflect
+ * through a placeholder in Russian. New wording: add a pair here and to the
+ * catalogs (es.json/ru.json).
+ * @param {{count: number, label?: {noun?: string, action?: string}|null}} coverage
+ */
+ function coverageCountLine(coverage) {
+ const count = coverage.count;
+ const values = { n: formatNumber(count) };
+ if (coverage.label?.action === 'click a line for its nearest photo')
+ return coverage.label.noun === 'streets'
+ ? tn(
+ count,
+ '{n} street in view · click a line for its nearest photo',
+ '{n} streets in view · click a line for its nearest photo',
+ values,
+ )
+ : tn(
+ count,
+ '{n} sequence in view · click a line for its nearest photo',
+ '{n} sequences in view · click a line for its nearest photo',
+ values,
+ );
+ return tn(
+ count,
+ '{n} sequence in view · click a line for its photos',
+ '{n} sequences in view · click a line for its photos',
+ values,
+ );
}
/** @param {{now?: number}} [options] Clock for the SINCE readout. */
export function presentStreetLevelPanel(state, { now = Date.now() } = {}) {
- const enabled = state.enabled === true;
const keyRequired = state.keyRequired === true;
const filter = state.filter || { pano: 'all', sinceDays: 0 };
- // A missing key is already shown by the status and chip tooltip; only a
- // rejected key keeps its error line, since that message names the fix.
+ // A missing key says how to add it; a rejected key's own error names the fix.
const keyMissing = keyRequired && state.keyRejected !== true;
return {
- enabled,
+ enabled: state.enabled === true,
keyRequired,
status: presentStatus(state),
- controlsDisabled: keyRequired || state.providers.length === 0,
+ controlsDisabled: keyRequired || (state.providers || []).length === 0,
providers: presentProviders(state),
error: keyMissing
- ? keyHint(state)
- : state.street.error ||
- state.sequence.error ||
- state.coverage.error ||
- null,
- ? null
++ ? keyGuidance(state) || null
+ : translateStreetLevelError(
- state.street.error || state.coverage.error || '',
++ state.street.error ||
++ state.sequence.error ||
++ state.coverage.error ||
++ '',
+ ) || null,
filter: { pano: filter.pano, sinceDays: Number(filter.sinceDays) || 0 },
+ filterControls: {
+ pano: state.filterControls?.pano !== false,
+ since: state.filterControls?.since !== false,
+ },
since: presentSince(filter.sinceDays, now),
+ sinceNote: state.sinceNote || null,
- legend: state.legend || [],
viewer: presentViewer(state),
meta: presentMeta(state),
+ nearest: presentNearest(state),
- wantsOpen: state.street.open === true,
};
}
diff --cc src/ui/streetLevelPresentation.test.mjs
index 82f7f2035,40cc4d14a..b81e203cb
--- a/src/ui/streetLevelPresentation.test.mjs
+++ b/src/ui/streetLevelPresentation.test.mjs
@@@ -79,12 -88,13 +79,12 @@@ test('KEY REQUIRED disables every contr
enabled: true,
keyRequired: true,
coverage: { error: 'no_key' },
- providers: [provider({ keyRequired: true, error: 'no_key' })],
}),
);
+ assert.equal(view.controlsDisabled, true);
assert.equal(view.status.text, 'KEY REQUIRED');
- assert.equal(view.error, null);
- // The chip still says how to add the key.
- assert.match(view.providers[0].title, /^Mapillary: Needs /);
+ assert.equal(view.status.tone, 'warn');
- assert.match(view.error, /^Mapillary: Needs MAPILLARY_CLIENT_TOKEN/);
++ assert.match(view.error, /^Needs MAPILLARY_CLIENT_TOKEN/);
});
test('a key Mapillary rejected reads KEY REJECTED and names the fix', () => {
@@@ -284,3 -384,182 +284,161 @@@ test('an image without a creator name l
assert.equal(view.viewer.link, null);
assert.equal(view.viewer.linkLabel, '');
});
+
-test('FOLLOW is disabled off Google 3D and says where to switch', () => {
- const open = { open: true, imageId: '1' };
- const off3d = presentStreetLevelPanel(
- snapshot({ street: { ...open, followAvailable: false } }),
- );
- assert.equal(off3d.viewer.follow.disabled, true);
- assert.match(
- off3d.viewer.follow.title,
- /needs the Google 3D map.*MAP SOURCE/,
- );
- const on3d = presentStreetLevelPanel(
- snapshot({ street: { ...open, followAvailable: true } }),
- );
- assert.equal(on3d.viewer.follow.disabled, false);
- assert.match(on3d.viewer.follow.title, /^Camera follows view/);
- const closed = presentStreetLevelPanel(
- snapshot({ street: { open: false, followAvailable: true } }),
- );
- assert.equal(closed.viewer.follow.disabled, true, 'nothing to follow');
-});
-
+ test('a Street View caption names the place, dates it by month, and offers no FIT/FILL', () => {
+ const view = presentStreetLevelPanel(
+ snapshot({
+ enabled: true,
+ street: {
+ open: true,
+ providerId: 'google',
+ providerName: 'Google Street View',
+ providerLabel: 'STREET VIEW',
+ imageId: 'pano-1',
+ title: '1014 10th St',
+ creator: 'Google',
+ capturedAt: Date.UTC(2023, 0, 1),
+ capturedAtPrecision: 'month',
+ bearing: 0,
+ isPano: true,
+ renderModes: false,
+ externalUrl:
+ 'https://www.google.com/maps/@?api=1&map_action=pano&pano=pano-1',
+ },
+ }),
+ );
+ assert.equal(view.viewer.captionLeft, '1014 10th St · Image by Google');
+ assert.equal(view.viewer.captionRight, '360° · 0° · 2023-01');
+ assert.equal(view.viewer.linkLabel, 'STREET VIEW ↗');
+ assert.equal(view.viewer.renderModes, false);
+ });
+
+ test('the meta line keeps the sequence count and adds the other providers’ hints', () => {
+ const view = presentStreetLevelPanel(
+ snapshot({
+ enabled: true,
+ coverage: {
+ loading: false,
+ count: 2514,
+ hint: 'click a street to open Street View',
+ error: null,
+ },
+ }),
+ );
+ // The count follows the app locale (formatNumber under the default 'en'),
+ // not the system locale of the Node process running the tests.
+ assert.equal(
+ view.meta,
+ '2,514 sequences in view · click a line for its photos · click a street to open Street View',
+ );
+ });
+
+ test('OPEN STREET VIEW shows while Street View is on, and waits for street zoom', () => {
+ const streetView = provider({
+ id: 'google',
+ name: 'Google Street View',
+ label: 'STREET VIEW',
+ groundClick: true,
+ requiresKeyId: 'google-maps',
+ });
+ const view = (overrides) =>
+ presentStreetLevelPanel(
+ snapshot({
+ enabled: true,
+ providers: [provider(), streetView],
+ ...overrides,
+ }),
+ ).nearest;
+ const ready = view({ groundClickReady: true });
+ assert.deepEqual(ready, {
+ visible: true,
+ label: 'OPEN STREET VIEW',
+ title: 'Open Google Street View at the centre of the view',
+ disabled: false,
+ providerIds: ['google'],
+ });
+ const high = view({ groundClickReady: false });
+ assert.equal(high.disabled, true);
+ assert.equal(
+ high.title,
+ 'Zoom in to a street to open Google Street View here',
+ );
+ // Hidden with Street View off, without its key, or with the layer off
+ // (off Google 3D the provider is not listed at all).
+ assert.equal(
+ view({ providers: [provider(), { ...streetView, on: false }] }).visible,
+ false,
+ );
+ assert.equal(
+ view({ providers: [provider(), { ...streetView, keyRequired: true }] })
+ .visible,
+ false,
+ );
+ assert.equal(view({ providers: [provider()] }).visible, false);
+ assert.equal(
+ presentStreetLevelPanel(snapshot({ providers: [provider(), streetView] }))
+ .nearest.visible,
+ false,
+ );
+ });
+
+ test('KEY REQUIRED points at Street View when it would draw with the Google key', () => {
+ const view = presentStreetLevelPanel(
+ snapshot({
+ enabled: true,
+ keyRequired: true,
+ providers: [
+ provider({ keyRequired: true, configured: false }),
+ provider({
+ id: 'google',
+ name: 'Google Street View',
+ label: 'STREET VIEW',
+ on: false,
+ configured: true,
+ requiresKeyId: 'google-maps',
+ }),
+ ],
+ keyAlternatives: [
+ { id: 'google', label: 'STREET VIEW', requiresKeyId: 'google-maps' },
+ ],
+ }),
+ );
+ const guidance =
+ 'Needs MAPILLARY_CLIENT_TOKEN — add it in Provider Settings, or light STREET VIEW to use your Google Maps key';
+ assert.equal(view.status.text, 'KEY REQUIRED');
+ assert.equal(view.status.title, guidance);
+ assert.equal(view.meta, guidance);
+ // Off Google 3D Street View is not listed: plain KEY REQUIRED.
+ const plain = presentStreetLevelPanel(
+ snapshot({
+ enabled: true,
+ keyRequired: true,
+ providers: [provider({ keyRequired: true, configured: false })],
+ keyAlternatives: [],
+ }),
+ );
+ assert.equal(plain.status.text, 'KEY REQUIRED');
+ assert.notEqual(plain.meta, guidance);
+ });
+
+ test('the caption names an image’s own licence after its author, and leaves it out when there is none', () => {
+ const caption = (street) =>
+ presentStreetLevelPanel({
+ enabled: true,
+ providers: [],
+ coverage: {},
+ legend: [],
+ filter: {},
+ sequence: {},
+ street: { open: true, imageId: '1', ...street },
+ }).viewer.captionLeft;
+ assert.equal(
+ caption({ creator: 'Fixture Mapper', license: 'CC BY-SA 4.0' }),
+ 'Image by Fixture Mapper · CC BY-SA 4.0',
+ );
+ assert.equal(
+ caption({ license: 'Licence Ouverte 2.0' }),
+ 'Licence Ouverte 2.0',
+ );
+ assert.equal(caption({ creator: 'Someone' }), 'Image by Someone');
+ });
diff --cc src/ui/styles/street-level.css
index 507bfcb67,4e72d87b8..c218765d9
--- a/src/ui/styles/street-level.css
+++ b/src/ui/styles/street-level.css
@@@ -1,8 -1,17 +1,14 @@@
/* ── Street Level panel ─────────────────────────────────────────
- The rail owns position and width (layers.css). The expanded viewer is
- re-parented to <body>, so it carries the tokens too. */
-#street-level-panel,
-.sl-viewer-wrap {
+ The rail owns position and width (layers.css). */
+#street-level-panel {
--sl-green: #05cb63;
+ /* KartaView's purple for lines; a lighter one where it is text (WCAG AA). */
+ --sl-kartaview: #635bff;
+ --sl-kartaview-text: #8f8aff;
+ /* Panoramax's orange; the darker one sits behind white text. */
+ --sl-panoramax: #ff6f00;
+ --sl-panoramax-fill: #b84e00;
- --sl-text: 0.62rem;
- --sl-text-small: 0.6rem;
+ --sl-text: 0.6rem;
}
#street-level-panel .panel-glow {
@@@ -184,9 -253,17 +230,16 @@@ html:not([lang='en']) .sl-meta-row .sl-
border-radius: 999px;
}
+ .sl-seg[hidden],
+ .sl-controls[hidden],
+ .sl-filters[hidden],
-.sl-since[hidden],
-.sl-legend[hidden] {
++.sl-since[hidden] {
+ display: none;
+ }
+
.sl-seg-btn {
font-family: var(--font-mono);
- font-size: var(--sl-text-small);
+ font-size: var(--sl-text);
letter-spacing: 0.08em;
padding: 4px 9px;
border: 0;
@@@ -461,6 -619,136 +525,107 @@@
aspect-ratio: auto;
}
-.sl-viewer-wrap-expanded .sl-image-meta {
- font-size: 0.66rem;
- padding: 10px 14px;
-}
-
-.sl-viewer-wrap-expanded .sl-viewer-bar {
- padding: 8px 10px;
-}
-
-.sl-viewer-wrap-expanded .sl-viewer-tools .scene-btn {
- padding: 8px 14px;
- font-size: 0.7rem;
- letter-spacing: 0.12em;
- color: var(--text-primary);
- border-color: rgba(0, 212, 255, 0.6);
- background: rgba(10, 10, 15, 0.82);
-}
-
-.sl-viewer-wrap-expanded #sl-viewer-expand::after {
- content: ' · ESC';
- color: var(--text-secondary);
-}
-
-.sl-viewer-wrap-expanded .sl-viewer-x {
- width: 34px;
- height: 34px;
- font-size: 1.3rem;
-}
-
+ /* ── Photo viewer (KartaView, Panoramax) ─────────────────────────────────── */
+ .sl-photo-viewer {
+ /* The lit source's colour: a focus ring, and behind the white ‹ › glyphs. */
+ --sl-photo-ring: var(--sl-kartaview-text);
+ --sl-photo-fill: color-mix(in srgb, var(--sl-kartaview) 85%, transparent);
+ position: absolute;
+ inset: 0;
+ background: #000;
+ outline: none;
+ overflow: hidden;
+ }
+
+ .sl-photo-viewer:focus-visible {
+ outline: none;
+ }
+
+ /* The photo and canvas fill the viewer and would cover a ring drawn on it:
+ draw the ring on a layer above them (clicks pass through). */
+ .sl-photo-viewer:focus-visible::after {
+ content: '';
+ position: absolute;
+ inset: 0;
+ z-index: 3;
+ border: 2px solid var(--sl-photo-ring);
+ pointer-events: none;
+ }
+
+ /* White on #ff6f00 is 2.8:1; on the darker orange behind ‹ › it is 5.1:1. */
+ .sl-photo-viewer[data-provider='panoramax'] {
+ --sl-photo-ring: var(--sl-panoramax);
+ --sl-photo-fill: var(--sl-panoramax-fill);
+ }
+
+ .sl-photo-flat,
+ .sl-photo-pano {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ user-select: none;
+ }
+
+ .sl-photo-flat {
+ object-fit: contain;
+ }
+
+ .sl-photo-pano {
+ cursor: grab;
+ touch-action: none;
+ }
+
+ .sl-photo-pano.sl-photo-dragging {
+ cursor: grabbing;
+ }
+
+ .sl-photo-flat[hidden],
+ .sl-photo-pano[hidden] {
+ display: none;
+ }
+
+ .sl-photo-step {
+ position: absolute;
+ top: 50%;
+ z-index: 2;
+ width: 34px;
+ height: 44px;
+ margin-top: -22px;
+ border: 1px solid rgba(255, 255, 255, 0.18);
+ border-radius: 8px;
+ background: rgba(10, 10, 15, 0.62);
+ color: #fff;
+ font-size: 1.5rem;
+ line-height: 1;
+ cursor: pointer;
+ }
+
+ .sl-photo-step-prev {
+ left: 6px;
+ }
+
+ .sl-photo-step-next {
+ right: 6px;
+ }
+
+ .sl-photo-step:hover:not(:disabled),
+ .sl-photo-step:focus-visible {
+ background: var(--sl-photo-fill);
+ outline: none;
+ }
+
+ .sl-photo-step:disabled {
+ opacity: 0.3;
+ cursor: default;
+ }
+
+ /* Nothing to step through until a photo shows. */
+ .sl-photo-viewer:not([data-kind='flat']):not([data-kind='pano'])
+ .sl-photo-step {
+ display: none;
+ }
+
/* ── Short viewports ─────────────────────────────────────────────────────── */
@media (max-height: 640px) {
.street-level-panel-inner {
diff --cc src/ui/templates/layer-panels.html
index 12e78fae2,363cfe0af..b170b01e3
--- a/src/ui/templates/layer-panels.html
+++ b/src/ui/templates/layer-panels.html
@@@ -76,60 -77,71 +77,65 @@@
<div class="panel-glow"></div>
<div class="street-level-panel-inner" data-rail-scroller>
<div class="panel-header">
- <span class="panel-title">STREET LEVEL</span>
+ <span class="panel-title" data-i18n>STREET LEVEL</span>
<span class="panel-divider"></span>
- <button id="sl-status" class="sl-status" type="button" aria-pressed="false" title="Turn Street Level on or off">OFF</button>
- <button class="panel-collapse-btn" data-collapse-target="street-level-panel" title="Expand panel">◀</button>
+ <button id="sl-status" class="sl-status" type="button" aria-pressed="false" title="Turn Street Level on or off" data-i18n-title data-i18n>OFF</button>
+ <button class="panel-collapse-btn" data-collapse-target="street-level-panel" title="Expand panel" data-i18n-title>◀</button>
</div>
<div id="sl-body" class="sl-body">
- <div class="sl-main">
- <div id="sl-viewer-wrap" class="sl-viewer-wrap" hidden>
- <div class="sl-viewer-bar">
- <div class="sl-viewer-tools">
- <button id="sl-viewer-expand" class="scene-btn" type="button" aria-pressed="false" title="Expand the street-level view (Esc shrinks it)" data-i18n-title><span class="sl-btn-icon" aria-hidden="true">⤢</span><span class="sl-btn-text" data-i18n>EXPAND</span></button>
- <div class="sl-seg" role="radiogroup" aria-label="Image fit" data-i18n-aria-label>
- <button type="button" class="sl-seg-btn is-active" data-sl-render="letterbox" role="radio" aria-checked="true" title="Fit: show the whole photo, with dark bars where its shape differs from the frame" data-i18n-title data-i18n>FIT</button>
- <button type="button" class="sl-seg-btn" data-sl-render="fill" role="radio" aria-checked="false" tabindex="-1" title="Fill: fill the frame edge to edge, cropping the photo" data-i18n-title data-i18n>FILL</button>
- </div>
- <button id="sl-follow-btn" class="scene-btn" type="button" aria-pressed="false" aria-label="Camera follows view" title="Camera follows view: move the globe camera wherever the street-level view looks" data-i18n-aria-label data-i18n-title><span class="sl-btn-icon" aria-hidden="true">⌖</span><span class="sl-btn-text" data-i18n>FOLLOW</span></button>
+ <div id="sl-viewer-wrap" class="sl-viewer-wrap" hidden>
+ <div class="sl-viewer-bar">
+ <div class="sl-viewer-tools">
- <button id="sl-viewer-expand" class="scene-btn" type="button" aria-pressed="false" title="Show the street-level view full screen (Esc shrinks it)"><span class="sl-btn-icon" aria-hidden="true">⤢</span><span class="sl-btn-text">EXPAND</span></button>
- <div class="sl-seg" role="radiogroup" aria-label="Image fit">
- <button type="button" class="sl-seg-btn is-active" data-sl-render="letterbox" role="radio" aria-checked="true" title="Fit: show the whole photo, with dark bars where its shape differs from the frame">FIT</button>
- <button type="button" class="sl-seg-btn" data-sl-render="fill" role="radio" aria-checked="false" tabindex="-1" title="Fill: fill the frame edge to edge, cropping the photo">FILL</button>
++ <button id="sl-viewer-expand" class="scene-btn" type="button" aria-pressed="false" title="Show the street-level view full screen (Esc shrinks it)" data-i18n-title><span class="sl-btn-icon" aria-hidden="true">⤢</span><span class="sl-btn-text" data-i18n>EXPAND</span></button>
++ <div class="sl-seg" role="radiogroup" aria-label="Image fit" data-i18n-aria-label>
++ <button type="button" class="sl-seg-btn is-active" data-sl-render="letterbox" role="radio" aria-checked="true" title="Fit: show the whole photo, with dark bars where its shape differs from the frame" data-i18n-title data-i18n>FIT</button>
++ <button type="button" class="sl-seg-btn" data-sl-render="fill" role="radio" aria-checked="false" tabindex="-1" title="Fill: fill the frame edge to edge, cropping the photo" data-i18n-title data-i18n>FILL</button>
</div>
- <div class="sl-viewer-tools sl-viewer-tools-right">
- <button id="sl-viewer-close" class="sl-viewer-x" type="button" title="Close the image and deselect it on the map" aria-label="Close the street-level image" data-i18n-title data-i18n-aria-label>×</button>
- </div>
- </div>
- <div class="sl-viewer-stage">
- <div id="sl-viewer-placeholder" class="sl-viewer-placeholder" hidden></div>
- <div id="sl-viewer" class="sl-viewer" aria-label="Street-level viewer" data-i18n-aria-label></div>
</div>
- <div id="sl-image-meta" class="sl-image-meta">
- <span id="sl-image-by" class="sl-image-by"></span>
- <span class="sl-image-right">
- <span id="sl-image-when" class="sl-image-when"></span>
- <a id="sl-image-link" class="sl-image-link" href="#" target="_blank" rel="noopener noreferrer" title="Open this image on the provider's site" data-i18n-title hidden></a>
- </span>
+ <div class="sl-viewer-tools sl-viewer-tools-right">
- <button id="sl-viewer-close" class="sl-viewer-x" type="button" title="Close the image and deselect it on the map" aria-label="Close the street-level image">×</button>
++ <button id="sl-viewer-close" class="sl-viewer-x" type="button" title="Close the image and deselect it on the map" aria-label="Close the street-level image" data-i18n-title data-i18n-aria-label>×</button>
</div>
</div>
- <div class="sl-settings">
- <div class="sl-providers" role="group" aria-label="Imagery providers" data-i18n-aria-label>
- <span class="cctv-summary-label" data-i18n>PROVIDERS</span>
- <div id="sl-provider-chips" class="sl-chips"></div>
- </div>
- <div id="sl-error" class="sl-error" role="alert" hidden><span aria-hidden="true">⚠</span> <span id="sl-error-text"></span></div>
- <!-- A missing key gates the filters only: the chips above stay
- focusable so their tooltip can say how to add the key. -->
- <fieldset id="sl-controls" class="sl-controls">
- <div id="sl-pano-row" class="sl-filters" role="group" aria-label="Imagery filters" data-i18n-aria-label>
- <span class="cctv-summary-label" data-i18n>IMAGERY</span>
- <div class="sl-seg" role="radiogroup" aria-label="Panorama filter" data-i18n-aria-label>
- <button type="button" class="sl-seg-btn is-active" data-sl-pano="all" role="radio" aria-checked="true" data-i18n>ALL</button>
- <button type="button" class="sl-seg-btn" data-sl-pano="pano" role="radio" aria-checked="false" tabindex="-1">360°</button>
- <button type="button" class="sl-seg-btn" data-sl-pano="flat" role="radio" aria-checked="false" tabindex="-1" data-i18n>FLAT</button>
- </div>
- </div>
- <div id="sl-since-row" class="sl-since">
- <label class="cctv-summary-label" for="sl-since" data-i18n>SINCE</label>
- <input id="sl-since" class="sl-range" type="range" min="0" max="8" step="1" value="0" aria-valuetext="ANY DATE" aria-describedby="sl-since-label sl-since-note" />
- <output id="sl-since-label" class="sl-since-label" for="sl-since" data-i18n>ANY DATE</output>
- <small id="sl-since-note" class="sl-since-note" hidden></small>
- </div>
- </fieldset>
- <ul id="sl-legend" class="sl-legend" aria-label="Coverage colours" data-i18n-aria-label></ul>
- <!-- The hint says how to open imagery; the button does it without a pointer. -->
- <div class="sl-meta-row">
- <div id="sl-coverage-meta" class="sl-meta"></div>
- <button id="sl-nearest-btn" class="scene-btn sl-nearest-btn" type="button" hidden data-i18n-runtime>OPEN STREET VIEW</button>
+ <div class="sl-viewer-stage">
+ <div id="sl-viewer-placeholder" class="sl-viewer-placeholder" hidden></div>
- <div id="sl-viewer" class="sl-viewer" aria-label="Street-level viewer"></div>
++ <div id="sl-viewer" class="sl-viewer" aria-label="Street-level viewer" data-i18n-aria-label></div>
+ </div>
+ <div id="sl-image-meta" class="sl-image-meta">
+ <span id="sl-image-by" class="sl-image-by"></span>
+ <span class="sl-image-right">
+ <span id="sl-image-when" class="sl-image-when"></span>
- <a id="sl-image-link" class="sl-image-link" href="#" target="_blank" rel="noopener noreferrer" title="Open this image on the provider's site" hidden></a>
++ <a id="sl-image-link" class="sl-image-link" href="#" target="_blank" rel="noopener noreferrer" title="Open this image on the provider's site" data-i18n-title hidden></a>
+ </span>
+ </div>
+ </div>
- <div class="sl-providers" role="group" aria-label="Imagery providers">
- <span class="cctv-summary-label">PROVIDERS</span>
++ <div class="sl-providers" role="group" aria-label="Imagery providers" data-i18n-aria-label>
++ <span class="cctv-summary-label" data-i18n>PROVIDERS</span>
+ <div id="sl-provider-chips" class="sl-chips"></div>
+ </div>
+ <div id="sl-error" class="sl-error" role="alert" hidden><span aria-hidden="true">⚠</span> <span id="sl-error-text"></span></div>
+ <!-- A missing key gates the filters only: the chips above stay
+ focusable so their tooltip can say how to add the key. -->
+ <fieldset id="sl-controls" class="sl-controls">
- <div class="sl-filters" role="group" aria-label="Imagery filters">
- <span class="cctv-summary-label">IMAGERY</span>
- <div class="sl-seg" role="radiogroup" aria-label="Panorama filter">
- <button type="button" class="sl-seg-btn is-active" data-sl-pano="all" role="radio" aria-checked="true">ALL</button>
++ <div id="sl-pano-row" class="sl-filters" role="group" aria-label="Imagery filters" data-i18n-aria-label>
++ <span class="cctv-summary-label" data-i18n>IMAGERY</span>
++ <div class="sl-seg" role="radiogroup" aria-label="Panorama filter" data-i18n-aria-label>
++ <button type="button" class="sl-seg-btn is-active" data-sl-pano="all" role="radio" aria-checked="true" data-i18n>ALL</button>
+ <button type="button" class="sl-seg-btn" data-sl-pano="pano" role="radio" aria-checked="false" tabindex="-1">360°</button>
- <button type="button" class="sl-seg-btn" data-sl-pano="flat" role="radio" aria-checked="false" tabindex="-1">FLAT</button>
++ <button type="button" class="sl-seg-btn" data-sl-pano="flat" role="radio" aria-checked="false" tabindex="-1" data-i18n>FLAT</button>
</div>
</div>
- <div class="sl-since">
- <label class="cctv-summary-label" for="sl-since">SINCE</label>
- <input id="sl-since" class="sl-range" type="range" min="0" max="8" step="1" value="0" aria-valuetext="ANY DATE" aria-describedby="sl-since-label" />
- <output id="sl-since-label" class="sl-since-label" for="sl-since">ANY DATE</output>
++ <div id="sl-since-row" class="sl-since">
++ <label class="cctv-summary-label" for="sl-since" data-i18n>SINCE</label>
++ <input id="sl-since" class="sl-range" type="range" min="0" max="8" step="1" value="0" aria-valuetext="ANY DATE" aria-describedby="sl-since-label sl-since-note" />
++ <output id="sl-since-label" class="sl-since-label" for="sl-since" data-i18n>ANY DATE</output>
++ <small id="sl-since-note" class="sl-since-note" hidden></small>
+ </div>
+ </fieldset>
- <div id="sl-coverage-meta" class="sl-meta"></div>
++ <!-- The hint says how to open imagery; the button does it without a pointer. -->
++ <div class="sl-meta-row">
++ <div id="sl-coverage-meta" class="sl-meta"></div>
++ <button id="sl-nearest-btn" class="scene-btn sl-nearest-btn" type="button" hidden data-i18n-runtime>OPEN STREET VIEW</button>
+ </div>
</div>
</div>
</div>